Skip to content

A peer-to-peer stack for code collaboration

Allow any value to be key of dict. (#45)

Julian Arni743956f2ab54
diff --git a/repl/config.rad b/repl/config.rad
index 3a0768f..6c00c23 100644
--- a/repl/config.rad
+++ b/repl/config.rad
@@ -1,8 +1,8 @@
(define repl
(dict
- name "repl"
+ 'name "repl"
;; Parse errors are thrown here
- getter (lambda () (catch 'parse-error (get-line!) print!))))
+ 'getter (lambda () (catch 'parse-error (get-line!) print!))))
;; Evaluation errors are thrown here
(catch 'any
diff --git a/repl/prelude.rad b/repl/prelude.rad
index 827a2a7..4283107 100644
--- a/repl/prelude.rad
+++ b/repl/prelude.rad
@@ -64,8 +64,8 @@
(insert key (fn (lookup key mp)) mp)))
(should-be "modify-map"
- (modify-map 'a (lambda (x) (+ x 1)) (dict a 5))
- (dict a 6))
+ (modify-map 'a (lambda (x) (+ x 1)) (dict 'a 5))
+ (dict 'a 6))
;; Account stuff. Should be moved elsewhere when we have an import mechanism
@@ -119,9 +119,9 @@
(define repl
(dict
- name "repl"
+ 'name "repl"
;; Parse errors are thrown here
- getter (lambda () (catch 'parse-error (get-line!) print!))))
+ 'getter (lambda () (catch 'parse-error (get-line!) print!))))
(catch 'any
(subscribe-to! repl print!)
diff --git a/src/Radicle.hs b/src/Radicle.hs
index 5cd74be..f493a8b 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -19,8 +19,6 @@ module Radicle
, ($$)
, Ident
, Reference(..)
- , makeRefs
- , coerceRefs
, fromIdent
, mkIdent
, quote
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index c32d5ce..3406142 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -1,13 +1,9 @@
-{-# LANGUAGE TemplateHaskell #-}
-
module Radicle.Internal.Core where
import Control.Monad.Except (ExceptT(..), MonadError, runExceptT,
throwError)
import Control.Monad.State
import Data.Data (Data)
-import Data.Deriving (deriveEq1, deriveShow1)
-import Data.Functor.Foldable (Fix(..), cata)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.List.NonEmpty (NonEmpty)
@@ -22,7 +18,6 @@ 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
@@ -44,8 +39,8 @@ data LangError r =
-- catching exceptions.
errorToValue
:: Monad m
- => LangError (Value Reference)
- -> Lang m (Ident, Value Reference)
+ => LangError Value
+ -> Lang m (Ident, Value)
errorToValue e = case e of
UnknownIdentifier i -> makeVal
( "unknown-identifier"
@@ -72,13 +67,13 @@ errorToValue e = case e of
Exit -> makeVal ("exit", [])
where
makeA = quote . Atom
- makeVal (t,v) = pure (Ident t, Dict $ Map.mapKeys Ident . fromList $ v)
+ makeVal (t,v) = pure (Ident t, Dict $ Map.mapKeys (Atom . Ident) . fromList $ v)
newtype Reference = Reference { getReference :: Int }
deriving (Show, Read, Ord, Eq, Generic)
-- | Create a new ref with the supplied initial value.
-newRef :: Monad m => Value Reference -> Lang m (Value Reference)
+newRef :: Monad m => Value -> Lang m Value
newRef v = do
b <- get
let ix = bindingsNextRef b
@@ -88,7 +83,7 @@ newRef v = do
pure . Ref $ Reference ix
-- | Read the value of a reference.
-readRef :: MonadError (LangError (Value Reference)) m => Reference -> Lang m (Value Reference)
+readRef :: MonadError (LangError Value) m => Reference -> Lang m Value
readRef (Reference r) = do
refs <- gets bindingsRefs
case IntMap.lookup r refs of
@@ -96,52 +91,24 @@ readRef (Reference r) = do
Just v -> pure v
-- | An expression or value in the language.
---
--- The parameter is for refs. Usually it is 'Reference'. 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 =
+data Value =
-- | A regular (hyperstatic) variable.
Atom Ident
| String Text
| Number Scientific
| Boolean Bool
- | List [Value r]
+ | List [Value]
| Primop Ident
- | Dict (Map.Map Ident (Value r))
- | Ref r
+ | Dict (Map.Map Value Value)
+ | Ref Reference
-- | 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 for effects.
- | Lambda [Ident] (NonEmpty (Value r)) (Maybe (Env (Value r)))
- deriving (Eq, Show, Read, Generic, Functor, Foldable, Traversable)
+ | Lambda [Ident] (NonEmpty Value) (Maybe (Env Value))
+ deriving (Eq, Show, Ord, Read, Generic)
--- | Replace all Refs containing 'Fix Value' into ones containing references to
--- those values.
-makeRefs :: Monad m => Value (Fix Value) -> Lang m (Value Reference)
-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
- Dict m -> Dict <$> sequence (go <$> m)
- List vs -> List <$> sequence (go <$> vs)
- Ref i -> i >>= eval >>= newRef
- Lambda is bd e -> Lambda is <$> sequence (go <$> bd)
- <*> traverse sequence (fmap go <$> e)
-
--- | 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.
--
-- Not all `Text`s are valid identifiers, so we do not export the constructor.
@@ -156,7 +123,7 @@ toIdent = Ident . fromString
-- | The environment, which keeps all known bindings.
newtype Env s = Env { fromEnv :: Map Ident s }
- deriving (Eq, Semigroup, Monoid, Show, Read, Generic, Functor, Foldable, Traversable)
+ deriving (Eq, Semigroup, Monoid, Ord, Show, Read, Generic, Functor, Foldable, Traversable)
instance IsList (Env s) where
type Item (Env s) = (Ident, s)
@@ -164,13 +131,13 @@ instance IsList (Env s) where
toList = GHC.Exts.toList . fromEnv
-- | Primop mappings. The parameter specifies the monad the primops run in.
-type Primops m = Map Ident ([Value Reference] -> Lang m (Value Reference))
+type Primops m = Map Ident ([Value ] -> Lang m Value)
-- | Bindings, either from the env or from the primops.
data Bindings m = Bindings
- { bindingsEnv :: Env (Value Reference)
+ { bindingsEnv :: Env Value
, bindingsPrimops :: Primops m
- , bindingsRefs :: IntMap (Value Reference)
+ , bindingsRefs :: IntMap Value
, bindingsNextRef :: Int
} deriving (Generic)
@@ -194,8 +161,8 @@ instance Monoid (Bindings m) where
-- | The environment in which expressions are evaluated.
newtype LangT r m a = LangT
- { fromLangT :: ExceptT (LangError (Value Reference)) (StateT r m) a }
- deriving (Functor, Applicative, Monad, MonadError (LangError (Value Reference)), MonadState r)
+ { fromLangT :: ExceptT (LangError Value) (StateT r m) a }
+ deriving (Functor, Applicative, Monad, MonadError (LangError Value), MonadState r)
instance MonadTrans (LangT r) where lift = LangT . lift . lift
@@ -206,7 +173,7 @@ type Lang m = LangT (Bindings m) m
runLang
:: Bindings m
-> Lang m a
- -> m (Either (LangError (Value Reference)) a, Bindings m)
+ -> m (Either (LangError Value) a, Bindings m)
runLang e l = runStateT (runExceptT $ fromLangT l) e
-- | Like 'local' or 'withState'
@@ -220,32 +187,32 @@ withEnv modifier action = do
-- * Functions
-addBinding :: Ident -> Value Reference -> Bindings m -> Bindings m
+addBinding :: Ident -> Value -> Bindings m -> Bindings 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 Reference)
+lookupAtom :: Monad m => Ident -> Lang m Value
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 Reference] -> Lang m (Value Reference))
+lookupPrimop :: Monad m => Ident -> Lang m ([Value] -> Lang m Value)
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 Reference -> Lang m ()
+defineAtom :: Monad m => Ident -> Value -> Lang m ()
defineAtom i v = modify $ addBinding i v
-quote :: Value r -> Value r
+quote :: Value -> Value
quote v = List [Primop (Ident "quote"), v]
-- * Eval
-- | The buck-passing eval. Uses whatever 'eval' is in scope.
-eval :: Monad m => Value Reference -> Lang m (Value Reference)
+eval :: Monad m => Value -> Lang m Value
eval val = do
e <- lookupAtom (toIdent "eval")
case e of
@@ -264,7 +231,7 @@ eval val = do
_ -> throwError $ TypeError "Trying to apply a non-function"
-- | The built-in, original, eval.
-baseEval :: Monad m => Value Reference -> Lang m (Value Reference)
+baseEval :: Monad m => Value -> Lang m Value
baseEval val = case val of
Atom i -> lookupAtom i
Ref i -> pure $ Ref i
@@ -289,7 +256,7 @@ baseEval val = case val of
-- | Infix function application
infixr 1 $$
-($$) :: Monad m => Value Reference -> [Value Reference] -> Lang m (Value Reference)
+($$) :: Monad m => Value -> [Value] -> Lang m Value
mfn $$ vs = do
mfn' <- baseEval mfn
case mfn' of
@@ -322,12 +289,5 @@ mfn $$ vs = do
(traverse baseEval body)
_ -> throwError $ TypeError "Trying to apply a non-function"
-nil :: Value r
+nil :: Value
nil = List []
-
--- TH
--- Needed for the Eq and Show instances for Fix.
-deriveEq1 ''Env
-deriveEq1 ''Value
-deriveShow1 ''Env
-deriveShow1 ''Value
diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hs
index 4fb933b..5875c0c 100644
--- a/src/Radicle/Internal/Parse.hs
+++ b/src/Radicle/Internal/Parse.hs
@@ -1,14 +1,13 @@
module Radicle.Internal.Parse where
import Control.Applicative (many, (<|>))
-import Control.Monad (void, (>=>))
+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)
@@ -25,12 +24,12 @@ import qualified Text.Megaparsec.Char.Lexer as L
import qualified Text.Megaparsec.Error as Par
import Radicle.Internal.Core
-import Radicle.Internal.Primops
+import Radicle.Internal.Primops
-- * The parser
type Parser a = ParsecT Void Text (Reader [Ident]) a
-type VParser = Parser (Value (Fix Value))
+type VParser = Parser Value
spaceConsumer :: Parser ()
spaceConsumer = L.space space1 lineComment blockComment
@@ -81,13 +80,6 @@ applyP = List <$> valueP `sepBy` spaceConsumer
quoteP :: VParser
quoteP = List . ((Primop $ toIdent "quote") :) . pure <$> (char '\'' >> valueP)
-dictP :: VParser
-dictP = do
- void $ symbol "dict"
- Dict . Map.fromList <$> pairP `sepBy` spaceConsumer
- where
- pairP = (,) <$> identP <*> valueP
-
lambdaP :: VParser
lambdaP = do
void $ symbol "lambda"
@@ -95,11 +87,6 @@ lambdaP = do
body <- fromList <$> some valueP
pure $ Lambda vars body Nothing
-refP :: VParser
-refP = do
- void $ symbol "ref"
- Ref . Fix <$> valueP
-
valueP :: VParser
valueP = do
v <- choice
@@ -115,8 +102,6 @@ valueP = do
where
appLike = choice
[ lambdaP <?> "lambda"
- , dictP <?> "dict"
- , refP <?> "ref"
, applyP <?> "application"
]
@@ -138,13 +123,13 @@ interpret
=> String
-> Text
-> Bindings m
- -> m (Either (LangError (Value Reference)) (Value Reference))
+ -> m (Either (LangError Value) Value)
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 -> fst <$> runLang bnds (makeRefs v >>= eval)
+ Right v -> fst <$> runLang bnds (eval v)
-- | Parse and evaluate a Text as multiple expressions.
--
@@ -152,19 +137,19 @@ interpret sourceName expr bnds = do
--
-- >>> fmap fst <$> runLang pureEnv $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"
-- Right (Boolean True)
-interpretMany :: Monad m => String -> Text -> Lang m (Value Reference)
+interpretMany :: Monad m => String -> Text -> Lang m Value
interpretMany sourceName src = do
primopNames <- gets $ Map.keys . bindingsPrimops
let parsed = parseValues sourceName src primopNames
case partitionEithers parsed of
- ([], vs) -> last <$> mapM (makeRefs >=> eval) vs
+ ([], vs) -> last <$> mapM 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 (Fix Value))]
+parseValues :: String -> Text -> [Ident] -> [Either (Par.ParseError Char Void) Value]
parseValues sourceName srcCode prims = go $ initial
where
initial = State
@@ -181,15 +166,15 @@ parseValues sourceName srcCode prims = go $ initial
--
-- Examples:
--
--- >>> parse "test" "#t" [] :: Either String (Value (Fix Value))
+-- >>> parse "test" "#t" [] :: Either String Value
-- Right (Boolean True)
--
--- >>> parse "test" "hi" [toIdent "hi"] :: Either String (Value (Fix Value))
+-- >>> parse "test" "hi" [toIdent "hi"] :: Either String Value
-- Right (Primop (Ident {fromIdent = "hi"}))
--
--- >>> parse "test" "hi" [] :: Either String (Value (Fix Value))
+-- >>> parse "test" "hi" [] :: Either String Value
-- Right (Atom (Ident {fromIdent = "hi"}))
-parse :: MonadError String m => String -> Text -> [Ident] -> m (Value (Fix Value))
+parse :: MonadError String m => String -> Text -> [Ident] -> m Value
parse file src ids = do
let res = runReader (M.runParserT (valueP <* eof) file src) ids
case res of
@@ -198,7 +183,7 @@ 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 (Fix Value))
+parseTest :: MonadError String m => Text -> m Value
parseTest t = parse "(test)" t (Map.keys $ bindingsPrimops e)
where
e :: Bindings (Lang Identity)
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index 9f89e75..d650cfb 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -1,7 +1,6 @@
{-# 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)
@@ -20,7 +19,7 @@ instance Pretty Reference where
instance Pretty Ident where
pretty (Ident i) = pretty i
-instance Pretty r => Pretty (Value r) where
+instance Pretty Value where
pretty v = case v of
Atom i -> pretty i
Ref i -> parens $ "ref" <+> pretty i
@@ -39,10 +38,6 @@ instance Pretty r => Pretty (Value r) where
where
escapeStr = T.replace "\"" "\\\"" . T.replace "\\" "\\\\"
-instance Pretty (Fix Value) where
- -- pretty indeed!
- pretty = pretty . unfix
-
instance Pretty r => Pretty (LangError r) where
pretty v = case v of
UnknownIdentifier i -> "Unknown identifier:" <+> pretty i
@@ -61,8 +56,7 @@ instance Pretty r => Pretty (LangError r) where
--
-- Examples:
--
--- >>> import Data.Void
--- >>> renderCompactPretty (List [String "hi", String "there"] :: Value Void)
+-- >>> renderCompactPretty (List [String "hi", String "there"])
-- "(\"hi\"\n\"there\")"
renderCompactPretty :: Pretty v => v -> Text
renderCompactPretty = renderStrict . layoutCompact . pretty
@@ -72,11 +66,10 @@ renderCompactPretty = renderStrict . layoutCompact . pretty
-- Examples:
--
-- >>> import Data.Void
--- >>> renderPretty Unbounded (List [String "hi", String "there"] :: Value Void)
+-- >>> renderPretty Unbounded (List [String "hi", String "there"])
-- "(\"hi\" \"there\")"
--
--- >>> import Data.Void
--- >>> renderPretty (AvailablePerLine 6 0.5) (List [String "hi", String "there"] :: Value Void)
+-- >>> renderPretty (AvailablePerLine 6 0.5) (List [String "hi", String "there"])
-- "(\"hi\"\n\"there\")"
renderPretty :: Pretty v => PageWidth -> v -> Text
renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
@@ -86,7 +79,7 @@ renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
-- Examples:
--
-- >>> import Data.Void
--- >>> renderPrettyDef (List [String "hi", String "there"] :: Value Void)
+-- >>> renderPrettyDef (List [String "hi", String "there"])
-- "(\"hi\" \"there\")"
renderPrettyDef :: Pretty v => v -> Text
renderPrettyDef = renderStrict . layoutSmart defaultLayoutOptions . pretty
diff --git a/src/Radicle/Internal/Primops.hs b/src/Radicle/Internal/Primops.hs
index 573e23a..c6ad838 100644
--- a/src/Radicle/Internal/Primops.hs
+++ b/src/Radicle/Internal/Primops.hs
@@ -32,6 +32,13 @@ purePrimops = Map.fromList $ first Ident <$>
[x] -> baseEval x
xs -> throwError $ WrongNumberOfArgs "base-eval" 1 (length xs))
, ("list", evalArgs $ \args -> pure $ List args)
+ , ("dict", evalArgs $ \args ->
+ let go (k:v:rest) = Map.insert k v $ go rest
+ go [] = mempty
+ go _ = error "impossible"
+ in if length args `mod` 2 == 0
+ then pure . Dict $ go args
+ else throwError $ OtherError "'dict' expects even number of args")
, ("quote", \args -> case args of
[v] -> pure v
xs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs))
@@ -75,15 +82,12 @@ purePrimops = Map.fromList $ first Ident <$>
[_] -> throwError $ TypeError "tail: expects list argument"
xs -> throwError $ WrongNumberOfArgs "tail" 1 (length xs))
, ("lookup", evalArgs $ \args -> case args of
- [Atom a, Dict m] -> pure $ case Map.lookup a m of
+ [a, Dict m] -> pure $ case Map.lookup a m of
Just v -> v
-- Probably an exception is better, but that seems cruel
-- when you have no exception handling facilities.
Nothing -> nil
- [Atom _, _] -> throwError
- $ TypeError "lookup: second argument must be map"
- [_, Dict _] -> throwError
- $ TypeError "lookup: first argument must be atom"
+ [_, _] -> throwError $ TypeError "lookup: second argument must be map"
xs -> throwError $ WrongNumberOfArgs "lookup" 2 (length xs))
, ("string-append", evalArgs $ \args ->
let fromStr (String s) = Just s
@@ -93,11 +97,9 @@ purePrimops = Map.fromList $ first Ident <$>
then pure . String . mconcat $ catMaybes ss
else throwError $ TypeError "string-append: non-string argument")
, ("insert", evalArgs $ \args -> case args of
- [Atom k, v, Dict m] -> pure . Dict $ Map.insert k v m
- [Atom _, _, _] -> throwError
- $ TypeError "insert: third argument must be map"
+ [k, v, Dict m] -> pure . Dict $ Map.insert k v m
[_, _, _] -> throwError
- $ TypeError "insert: first argument must be an atom"
+ $ TypeError "insert: third argument must be a dict"
xs -> throwError $ WrongNumberOfArgs "insert" 3 (length xs))
-- The semantics of + and - in Scheme is a little messed up. (+ 3)
-- evaluates to 3, and of (- 3) to -3. That's pretty intuitive.
@@ -156,6 +158,9 @@ purePrimops = Map.fromList $ first Ident <$>
-- in Lisps a lot of things that one might object to are True...
if b == Boolean False then baseEval f else baseEval t
xs -> throwError $ WrongNumberOfArgs "if" 3 (length xs))
+ , ("ref", evalArgs $ \args -> case args of
+ [x] -> newRef x
+ xs -> throwError $ WrongNumberOfArgs "ref" 1 (length xs))
, ("read-ref", evalArgs $ \args -> case args of
[Ref (Reference x)] -> gets bindingsRefs >>= \m -> case IntMap.lookup x m of
Nothing -> throwError $ Impossible "undefined reference"
@@ -183,7 +188,7 @@ purePrimops = Map.fromList $ first Ident <$>
numBinop :: (Scientific -> Scientific -> Scientific)
-> Text
- -> (Text, [Value Reference] -> Lang m (Value Reference))
+ -> (Text, [Value] -> Lang m Value)
numBinop fn name = (name, evalArgs $ \args -> case args of
Number x:x':xs -> foldM go (Number x) (x':xs)
where
diff --git a/src/Radicle/Internal/Subscriber.hs b/src/Radicle/Internal/Subscriber.hs
index ee1551a..2d25e6e 100644
--- a/src/Radicle/Internal/Subscriber.hs
+++ b/src/Radicle/Internal/Subscriber.hs
@@ -25,8 +25,8 @@ import Radicle.Internal.Subscriber.Capabilities
type ReplM m =
( Monad m, Stdout (Lang m), Stdin (Lang m)
- , GetEnv (Lang m) (Value Reference)
- , SetEnv (Lang m) (Value Reference) )
+ , GetEnv (Lang m) Value
+ , SetEnv (Lang m) Value )
repl :: FilePath -> Text -> IO ()
repl histFile preCode = do
@@ -82,7 +82,7 @@ replPrimops = Map.fromList $ first toIdent <$>
allPrims <- gets bindingsPrimops
let p = parse "[stdin]" ln (Map.keys allPrims)
case p of
- Right v -> makeRefs v
+ Right v -> pure v
Left e -> throwError $ ThrownError (Ident "parse-error")
(String $ T.pack e)
xs -> throwError $ WrongNumberOfArgs "get-line!" 0 (length xs))
@@ -93,7 +93,7 @@ replPrimops = Map.fromList $ first toIdent <$>
v' <- eval v
s <- get
case (x', v') of
- (Dict m, fn) -> case Map.lookup (toIdent "getter") m of
+ (Dict m, fn) -> case Map.lookup (Atom $ toIdent "getter") m of
Nothing -> throwError
$ OtherError "subscribe-to!: Expected 'getter' key"
Just g -> forever go
diff --git a/src/Radicle/Internal/Subscriber/Capabilities.hs b/src/Radicle/Internal/Subscriber/Capabilities.hs
index 69f2f40..f5f236b 100644
--- a/src/Radicle/Internal/Subscriber/Capabilities.hs
+++ b/src/Radicle/Internal/Subscriber/Capabilities.hs
@@ -36,12 +36,12 @@ instance Exit m => Exit (Lang m) where
class (Monad m) => GetEnv m r | m -> r where
getEnvS :: m (Env r)
-instance Monad m => GetEnv (Lang m) (Value Reference) where
+instance Monad m => GetEnv (Lang m) Value where
getEnvS = gets bindingsEnv
class (Monad m) => SetEnv m r | m -> r where
setEnvS :: Env r -> m ()
-instance Monad m => SetEnv (Lang m) (Value Reference) where
+instance Monad m => SetEnv (Lang m) Value where
setEnvS e = modify (\bnds -> bnds {bindingsEnv = e})
class (Monad m) => GetSourceName m where
@@ -49,9 +49,9 @@ 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 r -> m ())]
+ getSubsS :: m [(Text, Value -> m ())]
class (Monad m) => SetSubs m where
- setSubS :: Text -> (Value r -> m ()) -> m ()
+ setSubS :: Text -> (Value -> m ()) -> m ()
putStrLnS :: (Stdout m) => Text -> m ()
putStrLnS t = putStrS t >> putStrS "\n"
diff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hs
index 649b669..41760ad 100644
--- a/test/spec/Radicle/Internal/Arbitrary.hs
+++ b/test/spec/Radicle/Internal/Arbitrary.hs
@@ -3,12 +3,10 @@ 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 ()
@@ -20,16 +18,20 @@ import Radicle.Internal.Primops (purePrimops)
instance Arbitrary r => Arbitrary (Env r) where
arbitrary = Env <$> arbitrary
-instance {-# OVERLAPPING #-} Arbitrary (Value Void) where
+instance Arbitrary Value where
arbitrary = sized go
where
+ -- There's no literal syntax for dicts, only the 'dict' primop. If we
+ -- generated them directly, we would generate something that can only
+ -- be got at after an eval, and which doesn't really correspond to
+ -- anything a user can write. So we don't generate dicts directly,
+ -- instead requiring they go via the primop.
freqs = [ (3, Atom <$> (arbitrary `suchThat` (\x -> not (isPrimop x || isNum x))))
, (3, String <$> arbitrary)
, (3, Boolean <$> arbitrary)
, (3, Number <$> arbitrary)
, (1, List <$> sizedList)
- , (3, Primop <$> elements (Map.keys prims))
- , (3, Dict . Map.fromList <$> sizedList)
+ , (6, Primop <$> elements (Map.keys prims))
, (1, Lambda <$> sizedList
<*> scale (`div` 3) arbitrary
<*> scale (`div` 3) arbitrary)
@@ -40,19 +42,11 @@ instance {-# OVERLAPPING #-} Arbitrary (Value Void) where
sizedList = sized $ \n -> do
k <- choose (0, n)
scale (`div` (k + 1)) $ vectorOf k arbitrary
- prims :: Map.Map Ident ([Value Reference] -> Lang Identity (Value Reference))
+ prims :: Map.Map Ident ([Value] -> Lang Identity Value)
prims = purePrimops
isPrimop x = x `elem` Map.keys prims
isNum x = isJust (readMay (T.unpack $ fromIdent x) :: Maybe Scientific)
-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)
where
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index c76aba9..d51268e 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -12,7 +12,7 @@ import Radicle.Internal.Subscriber.Capabilities
data WorldState = WorldState
{ worldStateStdin :: [Text]
, worldStateStdout :: [Text]
- , worldStateEnv :: Env (Value Reference)
+ , worldStateEnv :: Env Value
}
@@ -23,7 +23,7 @@ runTestWith
:: Bindings (State WorldState)
-> [Text] -- The stdin (errors if it runs out)
-> Text -- The program
- -> (Either (LangError (Value Reference)) (Value Reference), [Text])
+ -> (Either (LangError Value) Value, [Text])
runTestWith bindings inputs action =
let ws = WorldState
{ worldStateStdin = inputs
@@ -37,18 +37,18 @@ runTestWith bindings inputs action =
runTestWith'
:: [Text]
-> Text
- -> (Either (LangError (Value Reference)) (Value Reference), [Text])
+ -> (Either (LangError Value) Value, [Text])
runTestWith' = runTestWith pureEnv
-- | Run a test without stdin/stdout
runTest
:: Bindings (State WorldState)
-> Text
- -> Either (LangError (Value Reference)) (Value Reference)
+ -> Either (LangError Value) Value
runTest bnds prog = fst $ runTestWith bnds [] prog
-- | Like 'runTest', but uses the pureEnv
-runTest' :: Text -> Either (LangError (Value Reference)) (Value Reference)
+runTest' :: Text -> Either (LangError Value) Value
runTest' = runTest pureEnv
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index ba3d957..17cda21 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -2,7 +2,6 @@
module Radicle.Tests where
import Data.Either (isLeft)
-import Data.Functor.Foldable (Fix(..), unfix)
import Data.Functor.Identity (runIdentity)
import Data.List (isSuffixOf)
import Data.Semigroup ((<>))
@@ -10,7 +9,6 @@ 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
@@ -37,8 +35,10 @@ test_eval =
prog `succeedsWith` String "Steve Wozniak"
, testCase "'dict' creates a Dict with given key/vals" $ do
- let prog = [s|(dict why "not")|]
- prog `succeedsWith` Dict (fromList [(toIdent "why", String "not")])
+ let prog1 = [s|(dict 'why "not")|]
+ prog1 `succeedsWith` Dict (fromList [(Atom $ toIdent "why", String "not")])
+ let prog2 = [s|(dict 3 1)|]
+ prog2 `succeedsWith` Dict (fromList [(Number 3, Number 1)])
, testCase "'cons' conses an element" $ do
let prog = [s|(cons #t (list #f))|]
@@ -52,7 +52,7 @@ test_eval =
let prog = [s|(tail (list #t #f #t))|]
prog `succeedsWith` List [Boolean False, Boolean True]
- , testProperty "'eq?' considers equal values equal" $ \(val :: Value Void) -> do
+ , testProperty "'eq?' considers equal values equal" $ \(val :: Value) -> do
let prog = [i|(eq? #{renderPrettyDef val} #{renderPrettyDef val})|]
res = runTest' $ T.pack prog
counterexample prog $ isLeft res || res == Right (Boolean True)
@@ -62,7 +62,7 @@ test_eval =
prog `succeedsWith` Boolean True
, testProperty "'eq?' considers different values different"
- $ \(v1 :: Value Int, v2 :: Value Int) ->
+ $ \(v1 :: Value , v2 :: Value ) ->
v1 /= v2 ==> do
-- We quote the values to prevent errors from being thrown
let prog = [i|(eq? (quote #{renderPrettyDef v1})
@@ -80,19 +80,31 @@ test_eval =
prog `succeedsWith` Boolean False
, testCase "'lookup' returns value of key in map" $ do
- let prog = [s|(lookup 'key1 (dict key1 "a" key2 "b"))|]
- prog `succeedsWith` String "a"
+ let prog1 = [s|(lookup 'key1 (dict 'key1 "a" 'key2 "b"))|]
+ prog1 `succeedsWith` String "a"
+ let prog2 = [s|(lookup 5 (dict 5 "a" 'key2 "b"))|]
+ prog2 `succeedsWith` String "a"
+ let prog3 = [s|(lookup '(2 3) (dict '(2 3) "a" 'key2 "b"))|]
+ prog3 `succeedsWith` String "a"
, testCase "'insert' updates the value of key in map" $ do
- let prog = [s|(lookup 'key1 (insert 'key1 "b" (dict key1 "a" key2 "b")))|]
- prog `succeedsWith` String "b"
-
- , testCase "'insert' insert the value of key in map" $ do
- let prog = [s|(lookup 'key1 (insert 'key1 "b" (dict)))|]
- prog `succeedsWith` String "b"
+ let prog1 = [s|(lookup 'key1 (insert 'key1 "b" (dict 'key1 "a" 'key2 "b")))|]
+ prog1 `succeedsWith` String "b"
+ let prog2 = [s|(lookup 5 (insert 5 "b" (dict 5 "a" 'key2 "b")))|]
+ prog2 `succeedsWith` String "b"
+ let prog3 = [s|(lookup '(2 3) (insert '(2 3) "b" (dict '(2 3) "a" 'key2 "b")))|]
+ prog3 `succeedsWith` String "b"
+
+ , testCase "'insert' inserts the value of key in map" $ do
+ let prog1 = [s|(lookup 'key1 (insert 'key1 "b" (dict)))|]
+ prog1 `succeedsWith` String "b"
+ let prog2 = [s|(lookup 5 (insert 5 "b" (dict)))|]
+ prog2 `succeedsWith` String "b"
+ let prog3 = [s|(lookup '(2 3) (insert '(2 3) "b" (dict)))|]
+ prog3 `succeedsWith` String "b"
, testProperty "'string-append' concatenates string" $ \ss -> do
- let args = T.unwords $ renderPrettyFix . String <$> ss
+ let args = T.unwords $ renderPrettyDef . String <$> ss
prog = "(string-append " <> args <> ")"
res = runTest' prog
expected = Right . String $ mconcat ss
@@ -123,7 +135,7 @@ test_eval =
res2 = runTest' prog2
res1 @?= res2
- , testProperty "'eval' does not alter functions" $ \(_v :: Value Int) -> do
+ , testProperty "'eval' does not alter functions" $ \(_v :: Value) -> do
let prog1 = [i| (eval (lambda () #{renderPrettyDef _v})) |]
prog2 = [i| (lambda () #{renderPrettyDef _v}) |]
res1 = runTest' $ T.pack prog1
@@ -221,12 +233,12 @@ test_eval =
prog `succeedsWith` Number 6
, testProperty "'>' works" $ \(x, y) -> do
- let prog = [i|(> #{renderPrettyFix $ Number x} #{renderPrettyFix $ Number y})|]
+ let prog = [i|(> #{renderPrettyDef $ Number x} #{renderPrettyDef $ Number y})|]
res = runTest' $ T.pack prog
counterexample prog $ res == Right (Boolean (x > y))
, testProperty "'<' works" $ \(x, y) -> do
- let prog = [i|(< #{renderPrettyFix $ Number x} #{renderPrettyFix $ Number y})|]
+ let prog = [i|(< #{renderPrettyDef $ Number x} #{renderPrettyDef $ Number y})|]
res = runTest' $ T.pack prog
counterexample prog $ res == Right (Boolean (x < y))
@@ -270,9 +282,9 @@ test_eval =
res = runTest' prog
res @?= Right (Number 6)
- , testProperty "read-ref . ref == id" $ \v -> do
- let derefed = runTest' $ T.pack [i|(read-ref (ref #{renderPrettyFix v}))|]
- orig = runTest' $ T.pack [i|#{renderPrettyFix v}|]
+ , testProperty "read-ref . ref == id" $ \(v :: Value) -> do
+ let derefed = runTest' $ T.pack [i|(read-ref (ref #{renderPrettyDef v}))|]
+ orig = runTest' $ T.pack [i|#{renderPrettyDef v}|]
info = "Expected:\n" <> T.unpack (prettyEither orig)
<> "\nGot:\n" <> T.unpack (prettyEither derefed)
counterexample info $ derefed == orig
@@ -286,7 +298,7 @@ test_eval =
runTest' "(show #f)" @?= Right (String "#f")
runTest' "(show (list 'a 1 \"foo\" (list 'b ''x 2 \"bar\")))" @?= Right (String "(a 1.0 \"foo\" (b (quote x) 2.0 \"bar\"))")
runTest' "eval" @?= Right (Primop (toIdent "base-eval"))
- runTest' "(show (dict 'a 1))" @?= Right (String "(dict 'a 1)")
+ runTest' "(show (dict 'a 1))" @?= Right (String "(dict a 1.0)")
runTest' "(show (lambda (x) x))" @?= Right (String "(lambda (x) x)")
]
where
@@ -342,10 +354,10 @@ test_binding =
test_pretty :: [TestTree]
test_pretty =
- [ testProperty "parse . pretty == identity" $ \(val :: Value (Fix Value)) ->
+ [ testProperty "parse . pretty == identity" $ \(val :: Value) ->
let rendered = renderPrettyDef val
actual = parseTest rendered
- original = removeEnv' val
+ original = removeEnv val
info = case actual of
Left e -> "parse error in: " <> T.unpack rendered <> "\n"
<> e
@@ -357,20 +369,20 @@ test_pretty =
test_env :: [TestTree]
test_env =
- [ testProperty "fromList . toList == identity" $ \(env' :: Env (Value Int)) ->
+ [ testProperty "fromList . toList == identity" $ \(env' :: Env Value) ->
fromList (toList env') == env'
]
test_repl_primops :: [TestTree]
test_repl_primops =
- [ testProperty "get-line! returns the input line" $ \(v :: Value Void) ->
+ [ testProperty "get-line! returns the input line" $ \(v :: Value) ->
let prog = [i|(eq? (get-line!) (quote #{renderPrettyDef v}))|]
res = run [renderPrettyDef v] $ T.pack prog
in counterexample prog $ res == Right (Boolean True)
, testCase "catch catches get-line errors" $ do
let prog = [s|
- (define repl (dict name "repl" getter get-line!))
+ (define repl (dict 'name "repl" 'getter get-line!))
(catch 'any
(subscribe-to! repl (lambda (x) (print! x)))
(lambda (x) "caught"))
@@ -452,22 +464,16 @@ test_source_files = testGroup "Radicle source file tests" <$> do
-- | Environments are neither printed nor parsed, but are generated by the
-- arbitrary instance.
-removeEnv :: Value s -> Value s
+removeEnv :: Value -> Value
removeEnv v = case v of
List xs -> List $ removeEnv <$> xs
Dict m -> Dict $ 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)) (Value s) -> T.Text
+prettyEither :: Either (LangError Value) Value -> 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