A peer-to-peer stack for code collaboration
Rewrite effect system
Julian K. Arni136816bafcc7
diff --git a/config.rad b/config.radnew file mode 100644index 0000000..1be1df9--- /dev/null+++ b/config.rad@@ -0,0 +1,5 @@+(define repl+ (sorted-map name "repl" getter (quote (get-line!))))++(subscribe-to! repl+ (lambda (x) (print! x)))diff --git a/exe/Repl.hs b/exe/Repl.hsnew file mode 100644index 0000000..94327bd--- /dev/null+++ b/exe/Repl.hs@@ -0,0 +1,14 @@+module Main (main) where++import System.Environment+import qualified Data.Text.IO as T+import Control.Concurrent++import Radicle++main :: IO ()+main = do+ [file] <- getArgs+ src <- T.readFile file+ _ <- forkIO $ repl src+ threadDelay maxBounddiff --git a/package.yaml b/package.yamlindex a6d8fd0..2e47925 100644--- a/package.yaml+++ b/package.yaml@@ -11,6 +11,8 @@ extra-source-files:dependencies:- base >=4 && <5- containers+- haskeline+- lens- megaparsec- mmorph- mtl@@ -49,16 +51,29 @@ tests:- Glob- hpack+executables:+ repl:+ main: Repl.hs+ source-dirs:+ - exe+ dependencies:+ - radicle+ ghc-options: -Wall -threaded+default-extensions:- AutoDeriveTypeable+- ConstraintKinds- DeriveDataTypeable- DeriveFunctor- DeriveGeneric-- GeneralizedNewtypeDeriving- FlexibleContexts+- FlexibleInstances+- FunctionalDependencies+- GeneralizedNewtypeDeriving+- MultiParamTypeClasses- OverloadedStrings+- RankNTypes+- RecordWildCards- TupleSections- TypeFamilies- TypeOperators-- RankNTypes-- RecordWildCardsdiff --git a/radicle.cabal b/radicle.cabalindex c4bf5eb..c7e150f 100644--- a/radicle.cabal+++ b/radicle.cabal@@ -2,7 +2,7 @@---- see: https://github.com/sol/hpack----- hash: 650d134dbbffbd2db37d84261d172a107bc0865d8252df4b363e7bdca4bedeb5+-- hash: b5ccc8731a18aa5cabe0cb961e8822afbf3fcf733448169921e2052611053d81name: radicleversion: 0.0.0@@ -24,11 +24,13 @@ source-repository headlibraryhs-source-dirs:src- default-extensions: AutoDeriveTypeable DeriveDataTypeable DeriveFunctor DeriveGeneric GeneralizedNewtypeDeriving FlexibleContexts OverloadedStrings TupleSections TypeFamilies TypeOperators RankNTypes RecordWildCards+ default-extensions: AutoDeriveTypeable ConstraintKinds DeriveDataTypeable DeriveFunctor DeriveGeneric FlexibleContexts FlexibleInstances FunctionalDependencies GeneralizedNewtypeDeriving MultiParamTypeClasses OverloadedStrings RankNTypes RecordWildCards TupleSections TypeFamilies TypeOperatorsghc-options: -Wallbuild-depends:base >=4 && <5, containers+ , haskeline+ , lens, megaparsec, mmorph, mtl@@ -37,10 +39,32 @@ libraryexposed-modules:RadicleRadicle.Internal- Radicle.Internal.ChainRadicle.Internal.CoreRadicle.Internal.ParseRadicle.Internal.Pretty+ Radicle.Internal.Subscriber+ Radicle.Internal.Subscriber.Capabilities+ other-modules:+ Paths_radicle+ default-language: Haskell2010++executable repl+ main-is: Repl.hs+ hs-source-dirs:+ exe+ default-extensions: AutoDeriveTypeable ConstraintKinds DeriveDataTypeable DeriveFunctor DeriveGeneric FlexibleContexts FlexibleInstances FunctionalDependencies GeneralizedNewtypeDeriving MultiParamTypeClasses OverloadedStrings RankNTypes RecordWildCards TupleSections TypeFamilies TypeOperators+ ghc-options: -Wall -threaded+ build-depends:+ base >=4 && <5+ , containers+ , haskeline+ , lens+ , megaparsec+ , mmorph+ , mtl+ , prettyprinter+ , radicle+ , textother-modules:Paths_radicledefault-language: Haskell2010@@ -50,14 +74,16 @@ test-suite doctestmain-is: Main.hshs-source-dirs:test/docs- default-extensions: AutoDeriveTypeable DeriveDataTypeable DeriveFunctor DeriveGeneric GeneralizedNewtypeDeriving FlexibleContexts OverloadedStrings TupleSections TypeFamilies TypeOperators RankNTypes RecordWildCards+ default-extensions: AutoDeriveTypeable ConstraintKinds DeriveDataTypeable DeriveFunctor DeriveGeneric FlexibleContexts FlexibleInstances FunctionalDependencies GeneralizedNewtypeDeriving MultiParamTypeClasses OverloadedStrings RankNTypes RecordWildCards TupleSections TypeFamilies TypeOperatorsghc-options: -Wall -threadedbuild-depends:Glob, base >=4 && <5, containers, doctest+ , haskeline, hpack+ , lens, megaparsec, mmorph, mtl@@ -73,12 +99,14 @@ test-suite specmain-is: Main.hshs-source-dirs:test/spec- default-extensions: AutoDeriveTypeable DeriveDataTypeable DeriveFunctor DeriveGeneric GeneralizedNewtypeDeriving FlexibleContexts OverloadedStrings TupleSections TypeFamilies TypeOperators RankNTypes RecordWildCards+ default-extensions: AutoDeriveTypeable ConstraintKinds DeriveDataTypeable DeriveFunctor DeriveGeneric FlexibleContexts FlexibleInstances FunctionalDependencies GeneralizedNewtypeDeriving MultiParamTypeClasses OverloadedStrings RankNTypes RecordWildCards TupleSections TypeFamilies TypeOperatorsghc-options: -Wall -threadedbuild-depends:QuickCheck, base >=4 && <5, containers+ , haskeline+ , lens, megaparsec, mmorph, mtl@@ -93,6 +121,7 @@ test-suite spec, textother-modules:Radicle.Internal.Arbitrary+ Radicle.Internal.TestCapabilitiesRadicle.TestsPaths_radicledefault-language: Haskell2010diff --git a/src/Radicle.hs b/src/Radicle.hsindex 5d900ae..c78aafa 100644--- a/src/Radicle.hs+++ b/src/Radicle.hs@@ -1,6 +1,12 @@--- | radicle - A LISP for blocktrees.+-- | `radicle` - A LISP for blocktrees.----- This is the only module you should need to import.+-- `radicle` is a *reflective* language, meaning evaluation can be modified,+-- thus redefining the language.+--+-- If you just want to use the language, you probably want the executables.+-- If however you want something more sophisticated - e.g., defining new+-- primops - you may need to use this as a library. This is the only module+-- you should need to import.module Radicle(-- * Language@@ -8,25 +14,22 @@ module Radicle-- | The definition of the core language.Value(..), interpret+ , interpretMany, LangError(..), ($$), Ident, fromIdent, makeIdent, Env(..)- , primops-- -- * Chains- , Chain(..)- , genesisChain- , foldChain- , foldChainFromSrc-- -- * Subscribers- , Subscriber(..)- , makeSubscriber- , addSubscriber- , removeSubscribers+ , pureEmptyEnv+ , Lang+ , runLangM+ , runLangT+ , Bindings+ , replBindings+ -- ** Core lenses+ , HasEnv(..)+ , HasPrimops(..)-- * Parsing, parse@@ -39,6 +42,8 @@ module Radicle-- ** Re-exports, PageWidth(..)+ -- * Repl+ , repl) whereimport Data.Text.Prettyprint.Docdiff --git a/src/Radicle/Internal.hs b/src/Radicle/Internal.hsindex 415a09d..d4615d9 100644--- a/src/Radicle/Internal.hs+++ b/src/Radicle/Internal.hs@@ -1,30 +1,19 @@module Radicle.Internal( module X, makeIdent- , parse- , parseTest) where-import Radicle.Internal.Chain as Ximport Radicle.Internal.Core as Ximport Radicle.Internal.Parse as Ximport Radicle.Internal.Pretty as X+import Radicle.Internal.Subscriber as X-import Control.Monad.Except+import Control.Monad.Readerimport Data.Text (Text)import qualified Text.Megaparsec as M-- | Smart constructor for Ident.makeIdent :: Text -> Maybe Ident-makeIdent = M.parseMaybe identP---- | Parse a value, using the String as source name, and calling 'fail' with a--- pretty error in case of a parse error.-parse :: MonadError String m => String -> Text -> m Value-parse file src = case M.parse valueP file src of- Left err -> throwError $ M.parseErrorPretty' src err- Right v -> pure v---- | Like 'parse', but uses "(test)" as the source name-parseTest :: MonadError String m => Text -> m Value-parseTest = parse "(test)"+makeIdent t = case runReader (M.runParserT identP "" t) [] of+ Left _ -> Nothing+ Right v -> pure vdiff --git a/src/Radicle/Internal/Chain.hs b/src/Radicle/Internal/Chain.hsdeleted file mode 100644index 18ea292..0000000--- a/src/Radicle/Internal/Chain.hs+++ /dev/null@@ -1,113 +0,0 @@-{-# LANGUAGE ScopedTypeVariables #-}-module Radicle.Internal.Chain where--import Control.Applicative (Alternative)-import Control.Monad (foldM)-import Control.Monad.Except (ExceptT(..), throwError)-import Control.Monad.Fail (MonadFail)-import Control.Monad.Identity (Identity, MonadFix, MonadPlus)-import Control.Monad.Morph (MFunctor(hoist), MMonad)-import Control.Monad.Reader (MonadReader, ReaderT(..), ask)-import Control.Monad.Trans-import Control.Monad.Writer (WriterT(..), writer)-import Data.Bifunctor (first)-import Data.Proxy (Proxy)-import Data.Semigroup (Semigroup, (<>))-import Data.Text (Text)-import GHC.Generics (Generic)--import Radicle.Internal.Core-import Radicle.Internal.Parse---- | Subscribers receive (evaluated) values from a chain, and can perform--- side-effects.-newtype Subscriber m a = Subscriber { fromSubscriber :: ReaderT Value m a }- deriving ( Generic, Functor, Monad, Applicative, MonadIO, MonadReader Value- , Alternative, MonadPlus, MonadFix, MonadTrans, MonadFail, MFunctor- , MMonad)--instance Semigroup (m a) => Semigroup (Subscriber m a) where- Subscriber a <> Subscriber b = Subscriber . ReaderT $ \v ->- runReaderT a v <> runReaderT b v--instance (Semigroup (m a), Monoid (m a)) => Monoid (Subscriber m a) where- mempty = Subscriber . ReaderT $ const mempty- mappend = (<>)---- | A helper for running subscribers.-runSubscriber :: Subscriber m a -> Value -> m a-runSubscriber = runReaderT . fromSubscriber---- | A helper for making subscribers.-makeSubscriber :: (Value -> m a) -> Subscriber m a-makeSubscriber = Subscriber . ReaderT---- | A blockchain definition.-data Chain m a = Chain- { chainName :: [Text]- -- | The fold function.- , chainStep :: Env -> Value -> Either LangError Value- , chainEnv :: Env- -- | How to update the env, given a new value.- , chainUpdateEnv :: Value -> Env -> Env- -- | 'chainSubscriber' is called with each new Env and with evaluated- -- Value.- , chainSubscriber :: Subscriber m a- } deriving (Functor, Generic)---instance MFunctor Chain where- hoist nat chain =- chain { chainSubscriber = hoist nat $ chainSubscriber chain }---- | A simple chain is one where we can ignore all subscribers.-type SimpleChain a = Chain Proxy a---- | Add a subscriber to a chain. The values are combined with mappend for 'm--- a'.-addSubscriber :: Semigroup (m a) => Chain m a -> Subscriber m a -> Chain m a-addSubscriber chain newCB- = chain { chainSubscriber = chainSubscriber chain <> newCB }---- | Removes all subscribers.-removeSubscribers :: (Semigroup (n b), Monoid (n b)) => Chain m a -> Chain n b-removeSubscribers chain = chain { chainSubscriber = mempty }---- | The default genesis chain.-genesisChain :: Chain Identity Value-genesisChain = Chain- { chainName = []- , chainEnv = mempty- , chainStep = \env val -> runLangM env (eval val)- , chainUpdateEnv = updateEnv- , chainSubscriber = Subscriber ask- }--updateEnv :: Value -> Env -> Env-updateEnv v = case v of- List [Atom (Ident "set!"), Atom a, val] -> setEnv a val- _ -> id----- | Fold a chain. All effects are accumulated with a monoid instance.-foldChain :: forall m a t. (Monoid (m a), Foldable t)- => Chain m a -> t Value -> Either LangError (Chain m a, m a)-foldChain chain vals = runWriterT $ foldM runChainStep chain vals- where- runChainStep :: Chain m a -> Value -> WriterT (m a) (Either LangError) (Chain m a)- runChainStep chain'@Chain{..} val = do- let mEvaled = chainStep chainEnv val- case mEvaled of- Left err -> throwError err- Right evaled ->- let newChain = chain' { chainEnv = chainUpdateEnv evaled chainEnv }- in writer (newChain, runSubscriber chainSubscriber evaled)----- | Fold a chain from a source file. The String argument is the name of the--- source file/block, used for error reporting.-foldChainFromSrc :: Monoid (m a)- => String -> Text -> Chain m a -> Either LangError (Chain m a, m a)-foldChainFromSrc sourceName srcCode chain =- let exprs = first ParseError <$> parseValues sourceName srcCode- in foldChain chain $ ExceptT exprsdiff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex 8aeb961..33958b9 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -1,10 +1,14 @@{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE UndecidableInstances #-}module Radicle.Internal.Core where-import Control.Monad.Except (ExceptT, MonadError, runExceptT,+import Control.Lens (At(..), Index, IxValue, Ixed(..), makeFields,+ makePrisms, (%~), (&), (<&>), (^.), (.=))+import Control.Monad.Except (ExceptT(..), MonadError, runExceptT,throwError)-import Control.Monad.Reader (MonadReader, Reader, ask, asks, local,- runReader)+import Control.Monad.Identity (Identity, runIdentity)+import Control.Monad.Stateimport Data.Bifunctor (first)import Data.Data (Data)import Data.Map (Map)@@ -31,16 +35,6 @@ data LangError =| ParseError (Par.ParseError Char Void)deriving (Eq, Show, Read, Generic)--- | An identifier in the language.------ Not all `Text`s are valid identifiers, so we do not export the constructor.--- Instead, use `makeIdent`.-newtype Ident = Ident { fromIdent :: Text }- deriving (Eq, Show, Read, Ord, Generic, Data)---- Unsafe!-identFromString :: String -> Ident-identFromString = Ident . fromString-- | An expression or value in the language.data Value =@@ -58,6 +52,18 @@ data Value =| Lambda [Ident] Value (Maybe Env)deriving (Eq, Ord, Show, Read, Generic, Data)+-- | An identifier in the language.+--+-- Not all `Text`s are valid identifiers, so we do not export the constructor.+-- Instead, use `makeIdent`.+newtype Ident = Ident { fromIdent :: Text }+ deriving (Eq, Show, Read, Ord, Generic, Data)++-- Unsafe! Only use this if you know the string at compile-time and know it's a+-- valid identifier+identFromString :: String -> Ident+identFromString = 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)@@ -67,36 +73,77 @@ instance IsList Env wherefromList = Env . fromListtoList = GHC.Exts.toList . fromEnv--- | Set the value of an identifier in the Env.-setEnv :: Ident -> Value -> Env -> Env-setEnv i v (Env e) = Env $ Map.insert i v e+type instance Index Env = Ident+type instance IxValue Env = Value++instance Ixed Env+instance At Env where+ at k f (Env m) = f mv <&> \r -> Env $ case r of+ Nothing -> maybe m (const (Map.delete k m)) mv+ Just v' -> Map.insert k v' m+ where mv = Map.lookup k m++-- Primop mappings+type Prims m = Map Ident ([Value] -> LangT (Bindings m) m Value)++-- | Bindings, either from the env or from the primops.+data Bindings m = Bindings+ { _bindingsEnv :: Env+ , _bindingsPrimops :: Prims m+ } deriving (Generic)++-- | The environment in which expressions are evaluated.+newtype LangT r m a = LangT+ { fromLangM :: ExceptT LangError (StateT r m) a }+ deriving ( Functor, Applicative, Monad, MonadError LangError, MonadState r)++instance MonadTrans (LangT r) where lift = LangT . lift . lift--- | The environment in which expressions are evaluated. We use Reader rather--- than State since modifications to the environment (modulo lambdas, which use--- 'local') are factored out.-newtype LangM a = LangM- { fromLangM :: ExceptT LangError (Reader Env) a }- deriving (Functor, Applicative, Monad, MonadError LangError, MonadReader Env)+type Lang m = LangT (Bindings m) m-runLangM :: Env -> LangM a -> Either LangError a-runLangM e l = runReader (runExceptT $ fromLangM l) e+runLangM :: Bindings Identity -> Lang Identity a -> Either LangError a+runLangM e l = runIdentity $ runLangT e l++runLangT :: Monad m => Bindings m -> Lang m a -> m (Either LangError a)+runLangT e l = evalStateT (runExceptT $ fromLangM l) e++withEnv :: Monad m => (Bindings m -> Bindings m) -> Lang m a -> Lang m a+withEnv f a = do+ x <- get+ modify f+ r <- a+ put x+ pure r++-- * Lenses++makeFields ''Bindings+makePrisms ''Value+makePrisms ''LangError+++-- * Functions++-- | A Bindings with an empty Env and only pure primops.+pureEmptyEnv :: Monad m => Bindings m+pureEmptyEnv = Bindings mempty purePrimops-- | Lookup an atom in the environment-lookupAtom :: Ident -> LangM Value-lookupAtom i = ask >>= \(Env env) -> case Map.lookup i env of+lookupAtom :: Monad m => Ident -> Lang m Value+lookupAtom i = get >>= \e -> case e ^. env . at i ofNothing -> throwError $ UnknownIdentifier iJust v -> pure v-- | Lookup a primop.-lookupPrimop :: Ident -> LangM ([Value] -> LangM Value)-lookupPrimop i = case Map.lookup i primops of+lookupPrimop :: Monad m => Ident -> Lang m ([Value] -> Lang m Value)+lookupPrimop i = get >>= \e -> case e ^. primops . at i ofNothing -> throwError $ Impossible "Unknown primop"Just v -> pure v-- | The universal primops. These are available in chain evaluation, and are-- not shadowable via 'define'.-primops :: Map Ident ([Value] -> LangM Value)-primops = Map.fromList $ first identFromString <$>+purePrimops :: Monad m => Prims m+purePrimops = Map.fromList $ first identFromString <$>[ ("eval", \args -> case args of[List (v:vs)] -> eval (Apply v vs)[Apply fn v ] -> eval =<< Apply <$> eval fn <*> traverse eval v@@ -109,6 +156,7 @@ primops = Map.fromList $ first identFromString <$>, ("define", \args -> case args of[Atom name, val] -> doval' <- eval val+ env . at name .= Just val'pure $ List [Atom $ identFromString "set!", Atom name, val'][_, _] -> throwError $ OtherError "define expects atom for first arg"xs -> throwError $ WrongNumberOfArgs "define" 2 (length xs))@@ -132,7 +180,7 @@ primops = Map.fromList $ first identFromString <$>-- * Eval-- | Evaluate a Value.-eval :: Value -> LangM Value+eval :: Monad m => Value -> Lang m Valueeval val = case val ofAtom i -> lookupAtom iList vals -> List <$> traverse eval vals@@ -152,11 +200,11 @@ eval val = case val ofvs' <- traverse eval vslet mappings = GHC.Exts.fromList (zip bnds vs')modEnv = const $ mappings <> closure- local modEnv (eval body)+ withEnv (\e -> e & env %~ modEnv) (eval body)_ -> throwError $ TypeError "Trying to apply a non-function"Primop i -> pure $ Primop ie@(Lambda _ _ (Just _)) -> pure e- Lambda args body Nothing -> asks $ Lambda args body . Just+ Lambda args body Nothing -> gets $ \e -> Lambda args body (Just $ e ^. env)SortedMap mp -> dolet evalSnd (a,b) = (a ,) <$> eval bSortedMap . Map.fromList <$> traverse evalSnd (Map.toList mp)@@ -167,3 +215,6 @@ eval val = case val ofinfixr 1 $$($$) :: Value -> [Value] -> Value($$) = Apply++nil :: Value+nil = List []diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hsindex 919fc8e..2b4c07d 100644--- a/src/Radicle/Internal/Parse.hs+++ b/src/Radicle/Internal/Parse.hs@@ -2,9 +2,14 @@module Radicle.Internal.Parse whereimport Control.Applicative (many, (<|>))+import Control.Lens ((^.))import Control.Monad (void)-import Data.Bifunctor (first)+import Control.Monad.Except+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.List.NonEmpty (NonEmpty((:|)))import qualified Data.Map as Mapimport Data.Text (Text)@@ -12,8 +17,10 @@ import qualified Data.Text as Timport Data.Void (Void)import GHC.Exts (IsString(..))import Text.Megaparsec (ParsecT, State(..), between, choice,- defaultTabWidth, initialPos, manyTill, parse,- runParser', sepBy, sepBy1, try, (<?>))+ defaultTabWidth, initialPos, manyTill,+ runParserT, runParserT', sepBy, sepBy1, try,+ (<?>))+import qualified Text.Megaparsec as Mimport Text.Megaparsec.Char (char, satisfy, space1)import qualified Text.Megaparsec.Char.Lexer as Limport qualified Text.Megaparsec.Error as Par@@ -22,56 +29,58 @@ import Radicle.Internal.Core-- * The parser-type Parser m a = ParsecT Void Text m a+type Parser a = ParsecT Void Text (Reader [Ident]) a-spaceConsumer :: Parser m ()+spaceConsumer :: Parser ()spaceConsumer = L.space space1 lineComment blockCommentwherelineComment = L.skipLineComment ";;"blockComment = L.skipBlockComment "#|" "|#" -- R6RS-symbol :: Text -> Parser m Text+symbol :: Text -> Parser Textsymbol = L.symbol spaceConsumer-parensP :: Parser m a -> Parser m a+parensP :: Parser a -> Parser aparensP = between (symbol "(" >> spaceConsumer) (spaceConsumer >> symbol ")")-primopP :: Parser m Value-primopP = Primop . Ident <$> choice (symbol . fromIdent <$> Map.keys primops)+primopP :: Parser Value+primopP = do+ prims <- ask+ Primop . Ident <$> choice (symbol . fromIdent <$> prims)-stringLiteralP :: Parser m Value+stringLiteralP :: Parser ValuestringLiteralP = String . T.pack <$> (char '"' >> manyTill L.charLiteral (char '"'))-boolLiteralP :: Parser m Value+boolLiteralP :: Parser ValueboolLiteralP = Boolean <$> (char '#' >>(char 't' >> pure True) <|> (char 'f' >> pure False))-identP :: Parser m Ident+identP :: Parser IdentidentP = dol <- satisfy isValidIdentFirstr <- many (satisfy isValidIdentRest)pure . Ident $ fromString (l:r)-atomP :: Parser m Value+atomP :: Parser ValueatomP = Atom <$> identP-applyP :: Monad m => Parser m Value+applyP :: Parser ValueapplyP = dofn:args <- valueP `sepBy1` spaceConsumerpure $ fn $$ args-listP :: Monad m => Parser m Value+listP :: Parser ValuelistP = List <$> (char '\'' >> parensP (valueP `sepBy` spaceConsumer))-sortedMapP :: Monad m => Parser m Value+sortedMapP :: Parser ValuesortedMapP = dovoid $ symbol "sorted-map"SortedMap . Map.fromList <$> pairP `sepBy` spaceConsumerwherepairP = (,) <$> identP <*> valueP-lambdaP :: Monad m => Parser m Value+lambdaP :: Parser ValuelambdaP = dovoid $ symbol "lambda"vars <- parensP $ fmap atomToIdent <$> atomP `sepBy` spaceConsumer@@ -81,7 +90,7 @@ lambdaP = doatomToIdent (Atom i) = iatomToIdent _ = error "impossible"-valueP :: Monad m => Parser m Value+valueP :: Parser ValuevalueP = dospaceConsumerv <- choice@@ -107,19 +116,39 @@ valueP = do---- Examples:----- >>> interpret "test" "((lambda (x) x) #t)"+-- >>> interpret "test" "((lambda (x) x) #t)" pureEmptyEnv-- Right (Boolean True)-interpret :: String -> Text -> Either LangError Value-interpret sourceName expr = do- parsed <- first ParseError $ parse valueP sourceName expr- runLangM mempty $ eval parsed+--+-- >>> interpret "test" "(#t #f)" pureEmptyEnv+-- Left (TypeError "Trying to apply a non-function")+interpret :: Monad m => String -> Text -> Bindings m -> m (Either LangError Value)+interpret sourceName expr re = do+ let primopNames = Map.keys (re ^. primops)+ parsed = runReader (runParserT valueP sourceName expr) primopNames+ case parsed of+ Left e -> pure . Left $ ParseError e+ Right v -> runLangT re $ eval v++-- | Parse and evaluate a Text as multiple expressions.+--+-- Examples:+--+-- >>> runLangM pureEmptyEnv $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"+-- Right (Boolean True)+interpretMany :: Monad m => String -> Text -> Lang m Value+interpretMany sourceName src = do+ primopNames <- gets $ \re -> Map.keys (re ^. primops)+ let parsed = parseValues sourceName src primopNames+ case partitionEithers parsed of+ ([], vs) -> last <$> mapM eval vs+ (e:_, _) -> throwError $ ParseError e-- | Parse a Text as a series of values.--- 'sourceName' is used for error reporting.+-- '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 -> [Either (Par.ParseError Char Void) Value]-parseValues sourceName srcCode = go $ initial+parseValues :: String -> Text -> [Ident] -> [Either (Par.ParseError Char Void) Value]+parseValues sourceName srcCode prims = go $ initialwhereinitial = State{ stateInput = T.strip srcCode@@ -127,9 +156,38 @@ parseValues sourceName srcCode = go $ initial, stateTokensProcessed = 0, stateTabWidth = defaultTabWidth}- go s = let (s', v) = runParser' valueP s+ go s = let (s', v) = runReader (runParserT' valueP s) primsin if T.null (stateInput s') then [v] else v:go s'+-- | Parse a value, using the String as source name, and the identifier list as+-- the primops.+--+-- Examples:+--+-- >>> parse "test" "#t" [] :: Either String Value+-- Right (Boolean True)+--+-- >>> parse "test" "hi" [identFromString "hi"] :: Either String Value+-- Right (Primop (Ident {fromIdent = "hi"}))+--+-- >>> parse "test" "hi" [] :: Either String Value+-- Right (Atom (Ident {fromIdent = "hi"}))+parse :: MonadError String m => String -> Text -> [Ident] -> m Value+parse file src ids = do+ let res = runReader (M.runParserT valueP file src) ids+ case res of+ Left err -> throwError $ M.parseErrorPretty' src err+ Right v -> pure v++-- | Like 'parse', but uses "(test)" as the source name and the default set of+-- primops.+parseTest :: MonadError String m => Text -> m Value+parseTest t = parse "(test)" t (Map.keys $ e ^. primops)+ where+ e :: Bindings (Lang Identity)+ e = pureEmptyEnv++-- ** Valid identifiers-- These are made top-level so construction of arbitrary instances that matches-- parsing is easierdiff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex 17fc57a..7199789 100644--- a/src/Radicle/Internal/Pretty.hs+++ b/src/Radicle/Internal/Pretty.hs@@ -2,8 +2,8 @@module Radicle.Internal.Pretty whereimport qualified Data.Map as Map+import Data.Text (Text)import qualified Data.Text as T-import Data.Text (Text)import Data.Text.Prettyprint.Docimport Data.Text.Prettyprint.Doc.Render.Textdiff --git a/src/Radicle/Internal/Subscriber.hs b/src/Radicle/Internal/Subscriber.hsnew file mode 100644index 0000000..1d54b04--- /dev/null+++ b/src/Radicle/Internal/Subscriber.hs@@ -0,0 +1,73 @@+{-# LANGUAGE ScopedTypeVariables #-}+module Radicle.Internal.Subscriber where++import Control.Lens (at, (&), (<>~), (?~), (^.))+import Control.Monad.Except+import Control.Monad.State (gets)+import Data.Bifunctor (first)+import Data.Either+import qualified Data.Map as Map+import Data.Text (Text)+import System.Console.Haskeline++import Radicle.Internal.Core+import Radicle.Internal.Parse+import Radicle.Internal.Pretty+import Radicle.Internal.Subscriber.Capabilities++type ReplM m = (Stdout m, Stdin m, GetEnv (Lang m), SetEnv (Lang m))++repl :: Text -> IO ()+repl preCode = do+ r <- runInputT defaultSettings+ $ runLangT replBindings+ $ interpretMany "[pre]" preCode+ print r++replBindings :: ReplM m => Bindings m+replBindings = pureEmptyEnv & primops <>~ replPrimops++replPrimops :: forall m. ReplM m => Prims m+replPrimops = Map.fromList $ first identFromString <$>+ [ ("print!", \args -> case args of+ [x] -> do+ v <- eval x+ putStrS (renderPrettyDef v)+ pure v+ xs -> throwError $ WrongNumberOfArgs "print!" 1 (length xs))++ , ("set-env!", \args -> case args of+ [Atom x, v] -> do+ v' <- eval v+ modifyEnvS (\e -> e & at x ?~ v')+ pure nil+ [_, _] -> throwError $ TypeError "Expected atom as first arg"+ xs -> throwError $ WrongNumberOfArgs "set-env!" 2 (length xs))++ , ("get-line!", \args -> case args of+ [] -> do+ ln <- getLineS+ allPrims <- gets (^. primops)+ let p = parseValues "[stdin]" ln (Map.keys allPrims)+ case partitionEithers p of+ ([], results) -> pure $ List results+ (e:_, _) -> throwError $ ParseError e+ xs -> throwError $ WrongNumberOfArgs "get-line!" 0 (length xs))++ , ("subscribe-to!", \args -> case args of+ [x, v] -> do+ x' <- eval x+ v' <- eval v+ case (x', v') of+ (SortedMap m, fn) -> case m ^. at (identFromString "getter") of+ Nothing -> throwError+ $ OtherError "subscribe-to!: Expected 'getter' key"+ Just g -> go+ where+ go = do+ newBlock <- eval g+ _ <- eval (fn $$ [newBlock])+ go+ _ -> throwError $ TypeError "subscribe-to!: Expected sorted-map"+ xs -> throwError $ WrongNumberOfArgs "subscribe-to!" 2 (length xs))+ ]diff --git a/src/Radicle/Internal/Subscriber/Capabilities.hs b/src/Radicle/Internal/Subscriber/Capabilities.hsnew file mode 100644index 0000000..090596d--- /dev/null+++ b/src/Radicle/Internal/Subscriber/Capabilities.hs@@ -0,0 +1,48 @@+-- | This module defines fine-grained monad classes for effects.+--+-- The intent is that any set of primops may wear on their sleaves (i.e.+-- constraints) what effects they do.+module Radicle.Internal.Subscriber.Capabilities where++import Control.Lens ((.=))+import Control.Monad.State (gets)+import Control.Monad.Trans+import Data.Text (Text)+import qualified Data.Text as T+import Data.Text.Prettyprint.Doc (PageWidth)+import System.Console.Haskeline++import Radicle.Internal.Core++class (Monad m) => Stdin m where getLineS :: m Text+instance Stdin m => Stdin (Lang m) where getLineS = lift getLineS+instance (MonadException m, Monad m) => Stdin (InputT m) where+ getLineS = getInputLine "rad> " >>= \x -> case x of+ Nothing -> error "curious about why this would happen"+ Just v -> pure $ T.pack v++class (Monad m) => Stdout m where putStrS :: Text -> m ()+instance Stdout m => Stdout (Lang 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 exitS = lift exitS++class (Monad m) => GetEnv m where getEnvS :: m Env+instance Monad m => GetEnv (Lang m) 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 setEnvS e = env .= e++class (Monad m) => GetSourceName m where getSourceNameS :: m String+class (Monad m) => HasPageWidth m where getPageWidthS :: m PageWidth+class (Monad m) => GetSubs m where getSubsS :: m [(Text, Value -> m ())]+class (Monad m) => SetSubs m where setSubS :: Text -> (Value -> m ()) -> m ()++putStrLnS :: (Stdout m) => Text -> m ()+putStrLnS t = putStrS t >> putStrS "\n"++modifyEnvS :: (GetEnv m, SetEnv m) => (Env -> Env) -> m ()+modifyEnvS f = getEnvS >>= setEnvS . fdiff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hsindex 32e02c7..e7892a1 100644--- a/test/spec/Radicle/Internal/Arbitrary.hs+++ b/test/spec/Radicle/Internal/Arbitrary.hs@@ -1,14 +1,16 @@{-# OPTIONS_GHC -fno-warn-orphans #-}module Radicle.Internal.Arbitrary where-import Data.Bifunctor (first)-import qualified Data.Map as Map-import qualified Data.Text as T+import Control.Monad.Identity (Identity)+import Data.Bifunctor (first)+import qualified Data.Map as Map+import qualified Data.Text as Timport Test.QuickCheckimport Test.QuickCheck.Instances ()import Radicle-import Radicle.Internal.Parse (isValidIdentFirst, isValidIdentRest)+import Radicle.Internal.Core (purePrimops)+import Radicle.Internal.Parse (isValidIdentFirst, isValidIdentRest)instance Arbitrary Env wherearbitrary = Env <$> arbitrary@@ -20,7 +22,7 @@ instance Arbitrary Value where, (3, String <$> arbitrary), (3, Boolean <$> arbitrary), (1, List <$> sizedList)- , (3, Primop <$> elements (Map.keys primops))+ , (3, Primop <$> elements (Map.keys prims)), (1, Apply <$> scale (`div` 2) arbitrary <*> sizedList), (3, SortedMap . Map.fromList <$> sizedList), (1, Lambda <$> sizedList@@ -33,7 +35,8 @@ instance Arbitrary Value wheresizedList = sized $ \n -> dok <- choose (0, n)scale (`div` (k + 1)) $ vectorOf k arbitrary-+ prims :: Map.Map Ident ([Value] -> Lang Identity Value)+ prims = purePrimopsinstance Arbitrary Ident wherearbitrary = ((:) <$> firstL <*> rest) `suchThatMap` (makeIdent . T.pack)diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsnew file mode 100644index 0000000..fd56048--- /dev/null+++ b/test/spec/Radicle/Internal/TestCapabilities.hs@@ -0,0 +1,47 @@+{-# LANGUAGE TemplateHaskell #-}+-- | This module defines instances for the classes in+-- Radicle.Internal.Subscriber.Capabilities that may be used for testing.+module Radicle.Internal.TestCapabilities where++import Control.Lens+import Control.Monad.State+import Data.Text (Text)++import Radicle+import Radicle.Internal.Subscriber.Capabilities++data WorldState = WorldState+ { _worldStateStdin :: [Text]+ , _worldStateStdout :: [Text]+ , _worldStateEnv :: Env+ }++makeFields ''WorldState++type TestLang = Lang (State WorldState)++-- | Run a possibly side-effecting program with the given stdin input lines.+runTestWith+ :: Bindings (State WorldState)+ -> [Text] -- The stdin (errors if it runs out)+ -> TestLang a+ -> (Either LangError a, [Text])+runTestWith bindings inputs action =+ let ws = WorldState+ { _worldStateStdin = inputs+ , _worldStateStdout = []+ , _worldStateEnv = bindings ^. env+ }+ in case runState (runLangT bindings action) ws of+ (val, st) -> (val, reverse $ st ^. stdout)++-- | Like `runTestWith`, but uses the pureEmptyEnv+runTestWith' :: [Text] -> TestLang a -> (Either LangError a, [Text])+runTestWith' = runTestWith pureEmptyEnv+++instance Stdin (State WorldState) where+ getLineS = head <$> (stdin <<%= tail)++instance Stdout (State WorldState) where+ putStrS t = stdout %= (t:)diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex fedabe9..028dd66 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -3,18 +3,18 @@module Radicle.Tests whereimport Data.Data ((:~:)(Refl), Data, cast, eqT, gmapT)-import Data.Semigroup (Semigroup, (<>))+import Data.Functor.Identity (runIdentity)+import Data.Semigroup ((<>))import Data.String.QQ (s)-import Data.Text (Text)import qualified Data.Text as Timport GHC.Exts (fromList, toList)import Test.Tastyimport Test.Tasty.HUnit-import Test.Tasty.QuickCheck (testProperty, counterexample)-import Control.Monad.Morph (generalize, hoist)+import Test.Tasty.QuickCheck (counterexample, testProperty)import Radicle.Internal.Arbitrary ()import Radicle.Internal.Core (identFromString)+import Radicle.Internal.TestCapabilitiesimport Radicle@@ -42,7 +42,7 @@ test_eval =let prog = [s|((lambda (x) x) #t)|]prog `succeedsWith` Boolean True- , testCase "lambda does not have access to future definitions" $ do+ , testCase "lambda does not have access to future definitions (hyper static)" $ dolet prog = [s|(define y "a")(define lam (lambda () y))@@ -88,11 +88,9 @@ test_eval =prog `failsWith` OtherError "define expects atom for first arg"]where- run :: Text -> Either LangError [Value]- run src = fmap snd $ foldChainFromSrc "test" src- $ hoist generalize genesisChain+ run src = runLangM pureEmptyEnv $ interpretMany "(test)" srcfailsWith src err = run src @?= Left err- succeedsWith src val = (last <$> run src) @?= Right val+ succeedsWith src val = run src @?= Right valtest_parser :: [TestTree]test_parser =@@ -124,30 +122,15 @@ test_binding =[s|(((lambda (x) (lambda (x) x)) "inner") "outer")|] ==> String "outer"]where- x ==> y = interpret "test" x @?= Right y--test_subscriber :: [TestTree]-test_subscriber =- [ testCase "have all effects returned in the right order" $ do- let sub = makeSubscriber $ \v -> case v of- Boolean True -> [Boolean True]- Boolean False -> [Boolean False]- _ -> error "should not happen"- ("#t #f", sub) ==> [Boolean True, Boolean False]- ]- where- run :: (Monoid (m Value), Semigroup (m Value))- => Text -> Subscriber m Value -> Either LangError (m Value)- run src subs = fmap snd $ foldChainFromSrc "test" src- $ addSubscriber (removeSubscribers genesisChain) subs- (val, subs) ==> y = run val subs @?= Right y+ x ==> y = runIdentity (interpret "test" x pureEmptyEnv) @?= Right y+test_pretty :: [TestTree]test_pretty =[ testProperty "pretty . parse == identity" $ \val ->let rendered = renderCompactPretty valactual = parseTest rendered- original = everywhere removeEnv val+ original = removeEnv valinfo = case actual ofLeft e -> "parse error in: " <> T.unpack rendered <> "\n"<> e@@ -156,21 +139,39 @@ test_pretty =<> "original: " <> show original <> "\n"in counterexample info $ actual == Right original]- where- everywhere :: Data a => (forall b. Data b => b -> b) -> a -> a- everywhere f x = f (gmapT (everywhere f) x)- -- | Environments are neither printed nor parsed, but are generated by the- -- arbitrary instance.- removeEnv :: forall b. Data b => (b -> b)- removeEnv x = case (cast x, eqT :: Maybe (b :~: Value)) of- (Just (Lambda arg body _), Just Refl) -> Lambda arg body Nothing- _ -> xtest_env :: [TestTree]test_env =- [ testProperty "fromList . toList == identity" $ \(env :: Env) ->- fromList (toList env) == env+ [ testProperty "fromList . toList == identity" $ \(env' :: Env) ->+ fromList (toList env') == env'+ ]++test_repl_primops :: [TestTree]+test_repl_primops =+ [ testProperty "get-line! returns the input line" $ \(v :: Value) ->+ 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]+ where+ run inp prog = fst $ runTestWith replBindings inp+ $ interpretMany "(test)" prog+++-- * Utilsi :: String -> Identi = identFromString++-- | 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+ everywhere :: Data a => (forall b. Data b => b -> b) -> a -> a+ everywhere f x = f (gmapT (everywhere f) x)