A peer-to-peer stack for code collaboration
Separate special forms and primitive functions. (#127)
James Haydond12a5688cdb9
diff --git a/exe/Server/Client.hs b/exe/Server/Client.hsindex 9768977..0c81fd1 100644--- a/exe/Server/Client.hs+++ b/exe/Server/Client.hs@@ -63,18 +63,18 @@ opts = Opts-- * Primops-bindings :: ClientEnv -> Bindings (Primops (InputT IO))-bindings cEnv = e { bindingsPrimops = bindingsPrimops e <> primops cEnv }+bindings :: ClientEnv -> Bindings (PrimFns (InputT IO))+bindings cEnv = e { bindingsPrimFns = bindingsPrimFns e <> primops cEnv }where- e :: Bindings (Primops (InputT IO))+ e :: Bindings (PrimFns (InputT IO))e = pureEnv-primops :: ClientEnv -> Primops (InputT IO)-primops cEnv = Primops (fromList [sendPrimop, receivePrimop]) <> replPrimops+primops :: ClientEnv -> PrimFns (InputT IO)+primops cEnv = PrimFns (fromList [sendPrimop, receivePrimop]) <> replPrimFnswheresendPrimop =( unsafeToIdent "send!"- , evalArgs $ \case+ , \case[String name, v] -> dores <- liftIO $ runClientM (submit $ List $ [String name, v]) cEnvcase res of@@ -86,7 +86,7 @@ primops cEnv = Primops (fromList [sendPrimop, receivePrimop]) <> replPrimops)receivePrimop =( unsafeToIdent "receive!"- , evalArgs $ \case+ , \case[String name, Number n] -> docase floatingOrInteger n ofLeft (_ :: Float) -> throwErrorHere . OtherErrordiff --git a/exe/Server/Server.hs b/exe/Server/Server.hsindex 7332a4e..73aad28 100644--- a/exe/Server/Server.hs+++ b/exe/Server/Server.hs@@ -91,7 +91,7 @@ getSince st name index = dodata Chain = Chain{ chainName :: Text- , chainState :: Bindings (Primops Identity)+ , chainState :: Bindings (PrimFns Identity), chainExprs :: Seq (Value, Value)} deriving (Generic)diff --git a/rad/repl.rad b/rad/repl.radindex 14ff9f2..dc1399c 100644--- a/rad/repl.rad+++ b/rad/repl.rad@@ -13,9 +13,8 @@(def repl- (dict- 'name "repl"- ;; Parse errors are thrown here- 'getter read-line!))+ {:name "repl"+ ;; Parse errors are thrown here+ :getter read-line!})(subscribe-to! repl print!)diff --git a/src/Radicle.hs b/src/Radicle.hsindex cc6b917..fd7f685 100644--- a/src/Radicle.hs+++ b/src/Radicle.hs@@ -30,7 +30,7 @@ module Radicle, pattern Boolean, pattern List, pattern Vec- , pattern Primop+ , pattern PrimFn, pattern Dict, pattern Ref, pattern Lambda@@ -72,13 +72,11 @@ module Radicle-- * Repl, repl- -- * Primops- , Primops(..)- , purePrimops- , replPrimops+ -- * PrimFns+ , PrimFns(..)+ , purePrimFns+ , replPrimFns, ReplM- -- ** Primop helpers- , evalArgs-- * CLI, getConfigdiff --git a/src/Radicle/Internal.hs b/src/Radicle/Internal.hsindex 7fa47f3..aa3ae62 100644--- a/src/Radicle/Internal.hs+++ b/src/Radicle/Internal.hs@@ -15,13 +15,13 @@ import Radicle.Internal.Effects as Ximport Radicle.Internal.Interpret as Ximport Radicle.Internal.Parse as Ximport Radicle.Internal.Pretty as X-import Radicle.Internal.Primops as X+import Radicle.Internal.PrimFns as Ximport qualified Text.Megaparsec as M-- | Smart constructor for Ident.mkIdent :: Text -> Maybe Ident-mkIdent t = case runReader (M.runParserT identP "" t) [] of+mkIdent t = case runIdentity (M.runParserT identP "" t) ofLeft _ -> NothingRight v -> pure vdiff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex ee5f303..3bd0316 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -131,7 +131,7 @@ data ValueF r =| BooleanF Bool| ListF [r]| VecF (Seq.Seq r)- | PrimopF Ident+ | PrimFnF Ident-- | Map from *pure* Values -- annotations shouldn't change lookup semantics.| DictF (Map.Map Value r)| RefF Reference@@ -142,7 +142,7 @@ data ValueF r =| LambdaF [Ident] (NonEmpty r) (Env r)deriving (Eq, Ord, Read, Show, Generic, Functor)-{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Primop, Dict, Ref, Lambda #-}+{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Vec, PrimFn, Dict, Ref, Lambda #-}type ValueConC t = (HasCallStack, Ann.Annotation t, Copointed t)@@ -181,10 +181,10 @@ pattern Vec vs <- (Ann.match -> VecF vs)whereVec = Ann.annotate . VecF-pattern Primop :: ValueConC t => Ident -> Annotated t ValueF-pattern Primop i <- (Ann.match -> PrimopF i)+pattern PrimFn :: ValueConC t => Ident -> Annotated t ValueF+pattern PrimFn i <- (Ann.match -> PrimFnF i)where- Primop = Ann.annotate . PrimopF+ PrimFn = Ann.annotate . PrimFnFpattern Dict :: ValueConC t => Map.Map Value (Annotated t ValueF) -> Annotated t ValueFpattern Dict vs <- (Ann.match -> DictF vs)@@ -291,13 +291,13 @@ instance GhcExts.IsList (Env s) wheretoList = GhcExts.toList . fromEnv-- | Primop mappings. The parameter specifies the monad the primops run in.-newtype Primops m = Primops { getPrimops :: Map Ident ([Value ] -> Lang m Value) }+newtype PrimFns m = PrimFns { getPrimFns :: Map Ident ([Value] -> Lang m Value) }deriving (Semigroup)-- | Bindings, either from the env or from the primops.data Bindings prims = Bindings{ bindingsEnv :: Env Value- , bindingsPrimops :: prims+ , bindingsPrimFns :: prims, bindingsRefs :: IntMap Value, bindingsNextRef :: Int} deriving (Eq, Show, Functor, Generic)@@ -321,19 +321,19 @@ instance MonadTrans (LangT r) where lift = LangT . lift . lift-- | A monad for language operations specialized to have as state the Bindings-- with appropriate underlying monad.-type Lang m = LangT (Bindings (Primops m)) m+type Lang m = LangT (Bindings (PrimFns m)) m-- | Run a `Lang` computation with the provided bindings. Returns the result as-- well as the updated bindings.runLang- :: Bindings (Primops m)+ :: Bindings (PrimFns m)-> Lang m a- -> m (Either (LangError Value) a, Bindings (Primops m))+ -> m (Either (LangError Value) a, Bindings (PrimFns m))runLang e l = runStateT (runExceptT $ fromLangT l) e-- | Like 'local' or 'withState'. Will run an action with a modified environment-- and then restore the original bindings.-withBindings :: Monad m => (Bindings (Primops m) -> Bindings (Primops m)) -> Lang m a -> Lang m a+withBindings :: Monad m => (Bindings (PrimFns m) -> Bindings (PrimFns m)) -> Lang m a -> Lang m awithBindings modifier action = dooldBnds <- getmodify modifier@@ -366,7 +366,7 @@ lookupAtom i = get >>= \e -> case Map.lookup i . fromEnv $ bindingsEnv e of-- | Lookup a primop.lookupPrimop :: Monad m => Ident -> Lang m ([Value] -> Lang m Value)-lookupPrimop i = get >>= \e -> case Map.lookup i $ getPrimops $ bindingsPrimops e of+lookupPrimop i = get >>= \e -> case Map.lookup i $ getPrimFns $ bindingsPrimFns e ofNothing -> throwErrorHere $ Impossible "Unknown primop"Just v -> pure v@@ -380,23 +380,15 @@ eval :: Monad m => Value -> Lang m Valueeval val = doe <- lookupAtom (Ident "eval")st <- gets toRad- logValPos e $ case e of- Primop i -> do- fn <- lookupPrimop i- -- Primops get to decide whether and how their args are- -- evaluated.- res <- fn [quote val, quote st]- updateEnvAndReturn res- l@Lambda{} -> callFn l [val, st] >>= updateEnvAndReturn- _ -> throwErrorHere $ TypeError "Trying to apply a non-function"+ logValPos e $ callFn e [val, st] >>= updateEnvAndReturnwhereupdateEnvAndReturn :: Monad m => Value -> Lang m ValueupdateEnvAndReturn v = case v ofList [val', newSt] -> do- prims <- gets bindingsPrimops+ prims <- gets bindingsPrimFnsnewSt' <- either (throwErrorHere . OtherError) pure(fromRad newSt :: Either Text (Bindings ()))- put $ newSt' { bindingsPrimops = prims }+ put $ newSt' { bindingsPrimFns = prims }pure val'_ -> throwErrorHere $ OtherError "eval: should return list with value and new env"@@ -416,6 +408,73 @@ baseEval val = logValPos val $ case val ofDict . Map.fromList <$> traverse evalBoth (Map.toList mp)autoquote -> pure autoquote+specialForms :: forall m. (Monad m) => Map Ident ([Value] -> Lang m Value)+specialForms = Map.fromList $ first Ident <$>+ [ ( "fn"+ , \case+ args : b : bs ->+ case args of+ Vec atoms_ -> do+ atoms <- traverse isAtom (toList atoms_) ?? toLangError (TypeError "fn: expecting a list of symbols")+ e <- gets bindingsEnv+ pure (Lambda atoms (b :| bs) e)+ _ -> throwErrorHere $ OtherError "fn: first argument must be a vector of argument symbols, and then at least one form for the body"+ xs -> throwErrorHere $ WrongNumberOfArgs "fn" 2 (length xs) -- TODO: technically "at least 2"+ )+ , ("quote", \case+ [v] -> pure v+ xs -> throwErrorHere $ WrongNumberOfArgs "quote" 1 (length xs))+ , ("def", \case+ [Atom name, val] -> do+ val' <- baseEval val+ defineAtom name val'+ pure nil+ [_, _] -> throwErrorHere $ OtherError "def expects atom for first arg"+ xs -> throwErrorHere $ WrongNumberOfArgs "def" 2 (length xs))+ , ( "def-rec"+ , \case+ [Atom name, val] -> do+ val' <- baseEval val+ case val' of+ Lambda is b e -> do+ let v = Lambda is b (Env . Map.insert name v . fromEnv $ e)+ defineAtom name v+ pure nil+ _ -> throwErrorHere $ OtherError "def-rec can only be used to define functions"+ [_, _] -> throwErrorHere $ OtherError "def-rec expects atom for first arg"+ xs -> throwErrorHere $ WrongNumberOfArgs "def-rec" 2 (length xs)+ )+ , ("do", (lastDef nil <$>) . traverse baseEval)+ , ("catch", \case+ [l, form, handler] -> do+ mlabel <- baseEval l+ case mlabel of+ -- TODO reify stack+ Atom label -> baseEval form `catchError` \(LangError _stack e) -> do+ (thrownLabel, thrownValue) <- errorDataToValue e+ if thrownLabel == label || label == Ident "any"+ then handler $$ [thrownValue]+ else baseEval form+ _ -> throwErrorHere $ TypeError "catch: first argument must be atom"+ xs -> throwErrorHere $ WrongNumberOfArgs "catch" 3 (length xs))+ , ("if", \case+ [condition, t, f] -> do+ b <- baseEval condition+ -- I hate this as much as everyone that might ever read Haskell, but+ -- in Lisps a lot of things that one might object to are True...+ if b == Boolean False then baseEval f else baseEval t+ xs -> throwErrorHere $ WrongNumberOfArgs "if" 3 (length xs))+ , ( "cond", (cond =<<) . evenArgs "cond" )+ ]+ where+ cond = \case+ [] -> pure nil+ (c,e):ps -> do+ b <- baseEval c+ if b /= Boolean False+ then baseEval e+ else cond ps+-- * From/ToRadicleclass FromRad a where@@ -505,35 +564,35 @@ callFn f vs = case f ofmodEnv = mappings <> closureNonEmpty.last <$> withEnv (const modEnv)(traverse baseEval body)- Primop i -> throwErrorHere . TypeError- $ "Trying to call a non-function: the primop '" <> show i- <> "' cannot be used as a function."- _ -> throwErrorHere . TypeError $ "Trying to call a non-function."+ PrimFn i -> do+ fn <- lookupPrimop i+ fn vs+ _ -> throwErrorHere . TypeError $ "Trying to call a non-function"--- | Infix evaluation of application (of functions or primops)+-- | Infix evaluation of application (of functions or special forms)infixr 1 $$($$) :: Monad m => Value -> [Value] -> Lang m Value-mfn $$ vs = do- mfn' <- baseEval mfn- case mfn' of- Primop i -> do- fn <- lookupPrimop i- -- Primops get to decide whether and how their args are- -- evaluated.- fn vs- f@Lambda{} -> do- vs' <- traverse baseEval vs- callFn f vs'- _ -> throwErrorHere $ TypeError "Trying to apply a non-function"+f $$ vs = case f of+ Atom i ->+ case Map.lookup i specialForms of+ Just form -> form vs+ Nothing -> fnApp+ _ -> fnApp+ where+ fnApp = do+ f' <- baseEval f+ vs' <- traverse baseEval vs+ callFn f' vs'nil :: Valuenil = List []quote :: Value -> Value-quote v = List [Primop (Ident "quote"), v]+quote v = List [Atom (Ident "quote"), v]+list :: [Value] -> Value-list vs = List (Primop (Ident "list") : vs)+list vs = List (Atom (Ident "list") : vs)kwLookup :: Text -> Map Value Value -> Maybe ValuekwLookup key = Map.lookup (Keyword $ Ident key)@@ -548,6 +607,15 @@ hoistEitherWith :: MonadError e' m => (e -> e') -> Either e a -> m ahoistEitherWith f (Left e) = throwError (f e)hoistEitherWith _ (Right x) = pure x+-- | Some forms/functions expect an even number or arguments.+evenArgs :: MonadError (LangError Value) m => Text -> [b] -> m [(b, b)]+evenArgs name = \case+ [] -> pure []+ [_] -> throwErrorHere . OtherError $ name <> ": expects an even number of arguments"+ x:y:xs -> do+ ps <- evenArgs name xs+ pure ((x,y):ps)+-- * Generic encoding/decoding of Radicle values.toRadG :: forall a. (HasEot a, ToRadG (Eot a)) => a -> Valuediff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hsindex bb6111c..cb2345b 100644--- a/src/Radicle/Internal/Effects.hs+++ b/src/Radicle/Internal/Effects.hs@@ -23,7 +23,7 @@ import Radicle.Internal.Cryptoimport Radicle.Internal.Effects.Capabilitiesimport Radicle.Internal.Interpretimport Radicle.Internal.Pretty-import Radicle.Internal.Primops+import Radicle.Internal.PrimFnstype ReplM m =@@ -35,10 +35,10 @@ type ReplM m =instance MonadRandom (InputT IO) wheregetRandomBytes = liftIO . getRandomBytes-instance MonadRandom m => MonadRandom (LangT (Bindings (Primops m)) m) where+instance MonadRandom m => MonadRandom (LangT (Bindings (PrimFns m)) m) wheregetRandomBytes = lift . getRandomBytes-repl :: Maybe FilePath -> Text -> Text -> Bindings (Primops (InputT IO)) -> IO ()+repl :: Maybe FilePath -> Text -> Text -> Bindings (PrimFns (InputT IO)) -> IO ()repl histFile preFileName preCode bindings = dolet settings = setComplete completion$ defaultSettings { historyFile = histFile }@@ -54,51 +54,51 @@ completion :: Monad m => CompletionFunc mcompletion = completeWord Nothing ['(', ')', ' ', '\n'] gowhere-- Any type for first param will do- bnds :: Bindings (Primops (InputT IO))+ bnds :: Bindings (PrimFns (InputT IO))bnds = replBindingsgo s = pure $ fmap simpleCompletion$ filter (s `isPrefixOf`)$ fmap (T.unpack . fromIdent)$ (Map.keys . fromEnv $ bindingsEnv bnds)- <> Map.keys (getPrimops $ bindingsPrimops bnds)+ <> Map.keys (getPrimFns $ bindingsPrimFns bnds)-replBindings :: forall m. ReplM m => Bindings (Primops m)-replBindings = e { bindingsPrimops = bindingsPrimops e <> replPrimops }+replBindings :: forall m. ReplM m => Bindings (PrimFns m)+replBindings = e { bindingsPrimFns = bindingsPrimFns e <> replPrimFns+ , bindingsEnv = bindingsEnv e <> primFnsEnv pfs }where- e :: Bindings (Primops m)+ e :: Bindings (PrimFns m)e = pureEnv+ pfs :: PrimFns m+ pfs = replPrimFns-replPrimops :: forall m. ReplM m => Primops m-replPrimops = Primops . Map.fromList $ first unsafeToIdent <$>- [ ("print!", \args -> case args of+replPrimFns :: forall m. ReplM m => PrimFns m+replPrimFns = PrimFns . Map.fromList $ first unsafeToIdent <$>+ [ ("print!", \case[x] -> do- v <- eval x- putStrS (renderPrettyDef v)+ putStrS (renderPrettyDef x)pure nilxs -> throwErrorHere $ WrongNumberOfArgs "print!" 1 (length xs))- , ("set-env!", \args -> case args of++ , ("set-env!", \case[Atom x, v] -> do- v' <- eval v- defineAtom x v'+ defineAtom x vpure nil[_, _] -> throwErrorHere $ TypeError "Expected atom as first arg"xs -> throwErrorHere $ WrongNumberOfArgs "set-env!" 2 (length xs))- , ("get-line!", \args -> case args of+ , ("get-line!", \case[] -> String <$> getLineSxs -> throwErrorHere $ WrongNumberOfArgs "get-line!" 0 (length xs))- , ("subscribe-to!", \args -> case args of+ , ("subscribe-to!", \case[x, v] -> do- x' <- eval x- v' <- eval ve <- gets bindingsEnv- case (x', v') of- (Dict m, fn) -> case Map.lookup (Atom $ unsafeToIdent "getter") m of+ case (x, v) of+ (Dict m, fn) -> case Map.lookup (Keyword $ unsafeToIdent "getter") m ofNothing -> throwErrorHere- $ OtherError "subscribe-to!: Expected 'getter' key"+ $ OtherError "subscribe-to!: Expected ':getter' key"Just g -> forever (protect go)whereprotect action = do@@ -123,17 +123,17 @@ replPrimops = Primops . Map.fromList $ first unsafeToIdent <$>_ -> throwErrorHere $ TypeError "subscribe-to!: Expected dict"xs -> throwErrorHere $ WrongNumberOfArgs "subscribe-to!" 2 (length xs)), ( "read-file!"- , evalOneArg "read-file" $ \case+ , oneArg "read-file" $ \caseString filename -> String <$> readFileS filename_ -> throwErrorHere $ TypeError "read-file: expects a string"), ( "load!"- , evalOneArg "load!" $ \case+ , oneArg "load!" $ \caseString filename -> readFileS filename >>= interpretMany "[load!]"_ -> throwErrorHere $ TypeError "load: expects a string"), ( "gen-key-pair!"- , evalArgs $ \case+ , \case[curvev] -> docurve <- hoistEither . first (toLangError . OtherError) $ fromRad curvev(pk, sk) <- generateKeyPair curve@@ -146,7 +146,7 @@ replPrimops = Primops . Map.fromList $ first unsafeToIdent <$>xs -> throwErrorHere $ WrongNumberOfArgs "gen-key-pair!" 0 (length xs)), ( "gen-signature!"- , evalArgs $ \case+ , \case[skv, String msg] -> dosk <- hoistEither . first (toLangError . OtherError) $ fromRad skvtoRad <$> signText sk msgdiff --git a/src/Radicle/Internal/Interpret.hs b/src/Radicle/Internal/Interpret.hsindex d8bd7d2..bb635f5 100644--- a/src/Radicle/Internal/Interpret.hs+++ b/src/Radicle/Internal/Interpret.hs@@ -2,7 +2,6 @@ module Radicle.Internal.Interpret whereimport Protolude-import qualified Data.Map.Strict as Mapimport Text.Megaparsec (eof, runParserT)import qualified Radicle.Internal.Annotation as Ann@@ -14,22 +13,21 @@ import Radicle.Internal.Parse-- Examples:---- >>> import Control.Monad.Identity--- >>> import Radicle.Internal.Primops+-- >>> import Radicle.Internal.PrimFns-- >>> fmap Ann.untag . runIdentity $ interpret "test" "((fn [x] x) #t)" pureEnv-- Right (Annotated (Identity (BooleanF True)))---- >>> import Control.Monad.Identity-- >>> noStack . runIdentity $ interpret "test" "(#t #f)" pureEnv--- Left (TypeError "Trying to apply a non-function")+-- Left (TypeError "Trying to call a non-function")interpret:: Monad m=> Text -- ^ Name of source file (for error reporting)-> Text -- ^ Source code to be interpreted- -> Bindings (Primops m) -- ^ Bindings to be used+ -> Bindings (PrimFns m) -- ^ Bindings to be used-> m (Either (LangError Value) Value)interpret sourceName expr bnds = do- let primopNames = Map.keys (getPrimops $ bindingsPrimops bnds)- parsed = runReader (runParserT (spaceConsumer *> valueP <* eof) (toS sourceName) expr) primopNames+ let parsed = runIdentity (runParserT (spaceConsumer *> valueP <* eof) (toS sourceName) expr)case parsed ofLeft e -> pure . Left $ LangError [Ann.thisPos] (ParseError e)Right v -> fst <$> runLang bnds (eval v)@@ -41,7 +39,7 @@ interpret sourceName expr bnds = do---- Examples:----- >>> import Radicle.Internal.Primops+-- >>> import Radicle.Internal.PrimFns-- >>> fmap (fmap Ann.untag . fst) <$> runLang pureEnv $ interpretMany "test" "(def id (fn [x] x))\n(id #t)"-- Right (Annotated (Identity (BooleanF True)))interpretMany@@ -50,8 +48,7 @@ interpretMany-> Text -- ^ Source code to be interpreted-> Lang m ValueinterpretMany sourceName src = do- primopNames <- gets $ Map.keys . getPrimops . bindingsPrimops- let parsed = parseValues sourceName src primopNames+ let parsed = parseValues sourceName srccase partitionEithers parsed of([], vs) -> does <- mapM eval vsdiff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hsindex 3d3e62b..7533c4f 100644--- a/src/Radicle/Internal/Parse.hs+++ b/src/Radicle/Internal/Parse.hs@@ -33,7 +33,7 @@ import Radicle.Internal.Core-- * The parser-type Parser a = ParsecT Void Text (Reader [Ident]) a+type Parser a = ParsecT Void Text Identity atype VParser = Parser ValuespaceConsumer :: Parser ()@@ -87,11 +87,8 @@ identP = lexeme $ dor <- many (satisfy isValidIdentRest)pure . Ident $ fromString (l:r)-atomOrPrimP :: VParser-atomOrPrimP = do- i <- identP- prims <- ask- tag $ if i `elem` prims then PrimopF i else AtomF i+atomP :: VParser+atomP = tag . AtomF =<< identPkeywordP :: VParserkeywordP = do@@ -118,7 +115,7 @@ dictP = bracesP (tag =<< (DictF . Map.fromList <$> evenItems))quoteP :: VParserquoteP = doval <- char '\'' >> valueP- q <- tag $ PrimopF (unsafeToIdent "quote")+ q <- tag $ AtomF (unsafeToIdent "quote")pure $ List [q, val]valueP :: VParser@@ -128,7 +125,7 @@ valueP = do, boolLiteralP <?> "boolean", keywordP <?> "keyword", try numLiteralP <?> "number"- , atomOrPrimP <?> "identifier"+ , atomP <?> "identifier", quoteP <?> "quote", listP <?> "list", vecP <?> "vector"@@ -145,9 +142,8 @@ valueP = doparseValues:: Text -- ^ Name of source file (for error reporting)-> Text -- ^ Source code to be parsed- -> [Ident] -- ^ Primop identifiers-> [Either (Par.ParseError Char Void) Value]-parseValues sourceName srcCode prims = withoutLeadingSpaces+parseValues sourceName srcCode = withoutLeadingSpaceswhereinitial = State{ stateInput = srcCode@@ -156,30 +152,26 @@ parseValues sourceName srcCode prims = withoutLeadingSpaces, stateTabWidth = defaultTabWidth}withoutLeadingSpaces =- let (s', _) = runReader (runParserT' spaceConsumer initial) prims+ let (s', _) = runIdentity (runParserT' spaceConsumer initial)in if T.null (stateInput s') then [] else go s'- go s = let (s', v) = runReader (runParserT' valueP s) prims+ go s = let (s', v) = runIdentity (runParserT' valueP s)in if T.null (stateInput s') then [v] else v:go s'-- | Parse a single value.---- Examples:----- >>> untag <$> parse "test" "#t" [] :: Either Text UntaggedValue+-- >>> untag <$> parse "test" "#t" :: Either Text UntaggedValue-- Right (Annotated (Identity (BooleanF True)))----- >>> untag <$> parse "test" "hi" [unsafeToIdent "hi"] :: Either Text UntaggedValue--- Right (Annotated (Identity (PrimopF (Ident {fromIdent = "hi"}))))------ >>> untag <$> parse "test" "hi" [] :: Either Text UntaggedValue+-- >>> untag <$> parse "test" "hi" :: Either Text UntaggedValue-- Right (Annotated (Identity (AtomF (Ident {fromIdent = "hi"}))))parse :: MonadError Text m=> Text -- ^ Name of source file (for error reporting)-> Text -- ^ Source code to be parsed- -> [Ident] -- ^ Primop identifiers-> m Value-parse file src ids = do- let res = runReader (M.runParserT (spaceConsumer *> valueP <* eof) (toS file) src) ids+parse file src = do+ let res = runIdentity (M.runParserT (spaceConsumer *> valueP <* eof) (toS file) src)case res ofLeft err -> throwError . toS $ M.parseErrorPretty' src errRight v -> pure vdiff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex c1ba638..b1e5959 100644--- a/src/Radicle/Internal/Pretty.hs+++ b/src/Radicle/Internal/Pretty.hs@@ -40,7 +40,7 @@ instance (Copointed t, Ann.Annotation t) => Pretty (Ann.Annotated t ValueF) wherEmpty -> "[]"v' :<| Empty -> brackets $ pretty v'_ -> brackets . sep $ pretty <$> toList vs- Primop i -> pretty i+ PrimFn i -> pretty iDict mp -> braces . align $sep [ pretty k <+> pretty val| (k, val) <- Map.toList mp ]diff --git a/src/Radicle/Internal/Primops.hs b/src/Radicle/Internal/PrimFns.hssimilarity index 62%rename from src/Radicle/Internal/Primops.hsrename to src/Radicle/Internal/PrimFns.hsindex 7560820..5baf87c 100644--- a/src/Radicle/Internal/Primops.hs+++ b/src/Radicle/Internal/PrimFns.hs@@ -1,9 +1,10 @@-module Radicle.Internal.Primops+module Radicle.Internal.PrimFns( pureEnv- , purePrimops- , evalArgs- , evalOneArg+ , purePrimFns+ , oneArg+ , evenArgs, readValue+ , primFnsEnv) whereimport Protolude hiding (TypeError, toList)@@ -20,35 +21,25 @@ import Radicle.Internal.Parseimport Radicle.Internal.Pretty-- | A Bindings with an Env containing only 'eval' and only pure primops.-pureEnv :: (Monad m) => Bindings (Primops m)-pureEnv = Bindings e purePrimops r 1+pureEnv :: forall m. (Monad m) => Bindings (PrimFns m)+pureEnv = Bindings e purePrimFns r 1where- e = fromList [ (unsafeToIdent "eval", Primop $ unsafeToIdent "base-eval")+ e = fromList [ (unsafeToIdent "eval", PrimFn $ unsafeToIdent "base-eval"), (unsafeToIdent "_doc-ref", Ref $ Reference 0)]+ <> primFnsEnv (purePrimFns :: PrimFns m)r = fromList [ (0, Dict mempty) ]-- | The universal primops. These are available in chain evaluation, and are-- not shadowable via 'define'.-purePrimops :: forall m. (Monad m) => Primops m-purePrimops = Primops $ fromList $ first Ident <$>- [ ( "fn"+purePrimFns :: forall m. (Monad m) => PrimFns m+purePrimFns = PrimFns $ fromList $ first Ident <$>+ [ ( "base-eval", \case- args : b : bs ->- case args of- Vec atoms_ -> do- atoms <- traverse isAtom (toList atoms_) ?? toLangError (TypeError "fn: expecting a list of symbols")- e <- gets bindingsEnv- pure (Lambda atoms (b :| bs) e)- _ -> throwErrorHere $ OtherError "fn: first argument must be a vector of argument symbols, and then at least one form for the body"- xs -> throwErrorHere $ WrongNumberOfArgs "fn" 2 (length xs) -- TODO: technically "at least 2"- )- , ( "base-eval"- , evalArgs $ \case[expr, st] -> case (fromRad st :: Either Text (Bindings ())) ofLeft e -> throwErrorHere $ OtherError eRight st' -> do- prims <- gets bindingsPrimops+ prims <- gets bindingsPrimFnswithBindings (const $ fmap (const prims) st') $ doval <- baseEval exprst'' <- get@@ -57,81 +48,45 @@ purePrimops = Primops $ fromList $ first Ident <$>), ( "pure-env", \case- [] -> pure $ toRad (pureEnv :: Bindings (Primops m))+ [] -> pure $ toRad (pureEnv :: Bindings (PrimFns m))xs -> throwErrorHere $ WrongNumberOfArgs "pure-env" 0 (length xs))- , ("apply", evalArgs $ \case- [fn, List args] -> eval . List $ fn:args+ , ("apply", \case+ [fn, List args] -> callFn fn args[_, _] -> throwErrorHere $ TypeError "apply: expecting list as second arg"xs -> throwErrorHere $ WrongNumberOfArgs "apply" 2 (length xs)), ( "read"- , evalOneArg "read" $ \case+ , oneArg "read" $ \caseString s -> readValue s_ -> throwErrorHere $ TypeError "read: expects string"), ("get-current-env", \case[] -> toRad <$> getxs -> throwErrorHere $ WrongNumberOfArgs "get-current-env" 0 (length xs))- , ("list", evalArgs $ \args -> pure $ List args)- , ("dict", evalArgs $ (Dict . foldr (uncurry Map.insert) mempty <$>)+ , ("list", pure . List)+ , ("dict", (Dict . foldr (uncurry Map.insert) mempty <$>). evenArgs "dict")- , ("quote", \args -> case args of- [v] -> pure v- xs -> throwErrorHere $ WrongNumberOfArgs "quote" 1 (length xs))- , ("def", \args -> case args of- [Atom name, val] -> do- val' <- baseEval val- defineAtom name val'- pure nil- [_, _] -> throwErrorHere $ OtherError "def expects atom for first arg"- xs -> throwErrorHere $ WrongNumberOfArgs "def" 2 (length xs))- , ( "def-rec"- , \case- [Atom name, val] -> do- val' <- baseEval val- case val' of- Lambda is b e -> do- let v = Lambda is b (Env . Map.insert name v . fromEnv $ e)- defineAtom name v- pure nil- _ -> throwErrorHere $ OtherError "def-rec can only be used to define functions"- [_, _] -> throwErrorHere $ OtherError "def-rec expects atom for first arg"- xs -> throwErrorHere $ WrongNumberOfArgs "def-rec" 2 (length xs)- )- , ("do", evalArgs $ pure . lastDef nil)- , ("catch", \args -> case args of- [l, form, handler] -> do- mlabel <- baseEval l- case mlabel of- -- TODO reify stack- Atom label -> baseEval form `catchError` \(LangError _stack e) -> do- (thrownLabel, thrownValue) <- errorDataToValue e- if thrownLabel == label || label == Ident "any"- then handler $$ [thrownValue]- else baseEval form- _ -> throwErrorHere $ TypeError "catch: first argument must be atom"- xs -> throwErrorHere $ WrongNumberOfArgs "catch" 3 (length xs))- , ("throw", evalArgs $ \args -> case args of+ , ("throw", \case[Atom label, exc] -> throwErrorHere $ ThrownError label exc[_, _] -> throwErrorHere $ TypeError "throw: first argument must be atom"xs -> throwErrorHere $ WrongNumberOfArgs "throw" 2 (length xs))- , ("eq?", evalArgs $ \args -> case args of+ , ("eq?", \case[a, b] -> pure $ Boolean (a == b)xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs))- , ("cons", evalArgs $ \args -> case args of+ , ("cons", \case[x, List xs] -> pure $ List (x:xs)[_, _] -> throwErrorHere $ TypeError "cons: second argument must be list"xs -> throwErrorHere $ WrongNumberOfArgs "cons" 2 (length xs))- , ("head", evalOneArg "head" $ \case+ , ("head", oneArg "head" $ \caseList (x:_) -> pure xList [] -> throwErrorHere $ OtherError "head: empty list"_ -> throwErrorHere $ TypeError "head: expects list argument")- , ("tail", evalOneArg "tail" $ \case+ , ("tail", oneArg "tail" $ \caseList (_:xs) -> pure $ List xsList [] -> throwErrorHere $ OtherError "tail: empty list"_ -> throwErrorHere $ TypeError "tail: expects list argument"), ( "nth"- , evalArgs $ \case+ , \case[Number n, vs] -> case floatingOrInteger n ofLeft (_ :: Double) -> throwErrorHere $ OtherError "nth: first argument was not an integer"Right i -> do@@ -142,7 +97,7 @@ purePrimops = Primops $ fromList $ first Ident <$>[_,_] -> throwErrorHere $ TypeError "nth: expects a integer and a list"xs -> throwErrorHere $ WrongNumberOfArgs "nth" 2 (length xs))- , ("lookup", evalArgs $ \args -> case args of+ , ("lookup", \case[a, Dict m] -> pure $ case Map.lookup a m ofJust v -> v-- Probably an exception is better, but that seems cruel@@ -150,14 +105,14 @@ purePrimops = Primops $ fromList $ first Ident <$>Nothing -> nil[_, _] -> throwErrorHere $ TypeError "lookup: second argument must be map"xs -> throwErrorHere $ WrongNumberOfArgs "lookup" 2 (length xs))- , ("string-append", evalArgs $ \args ->+ , ("string-append", \args ->let fromStr (String s) = Just sfromStr _ = Nothingss = fromStr <$> argsin if all isJust ssthen pure . String . mconcat $ catMaybes sselse throwErrorHere $ TypeError "string-append: non-string argument")- , ("insert", evalArgs $ \args -> case args of+ , ("insert", \case[k, v, Dict m] -> pure . Dict $ Map.insert k v m[_, _, _] -> throwErrorHere$ TypeError "insert: third argument must be a dict"@@ -173,81 +128,74 @@ purePrimops = Primops $ fromList $ first Ident <$>, numBinop (+) "+", numBinop (*) "*", numBinop (-) "-"- , ("<", evalArgs $ \args -> case args of+ , ("<", \case[Number x, Number y] -> pure $ Boolean (x < y)[_, _] -> throwErrorHere $ TypeError "<: expecting number"xs -> throwErrorHere $ WrongNumberOfArgs "<" 2 (length xs))- , (">", evalArgs $ \args -> case args of+ , (">", \case[Number x, Number y] -> pure $ Boolean (x > y)[_, _] -> throwErrorHere $ TypeError ">: expecting number"xs -> throwErrorHere $ WrongNumberOfArgs ">" 2 (length xs))- , ("foldl", evalArgs $ \args -> case args of+ , ("foldl", \case[fn, init', List ls] -> foldlM (\b a -> callFn fn [b, a]) init' ls[_, _, _] -> throwErrorHere$ TypeError "foldl: third argument should be a list"xs -> throwErrorHere $ WrongNumberOfArgs "foldl" 3 (length xs))- , ("foldr", evalArgs $ \args -> case args of+ , ("foldr", \case[fn, init', List ls] -> foldrM (\b a -> callFn fn [b, a]) init' ls[_, _, _] -> throwErrorHere$ TypeError "foldr: third argument should be a list"xs -> throwErrorHere $ WrongNumberOfArgs "foldr" 3 (length xs))- , ("map", evalArgs $ \args -> case args of+ , ("map", \case[fn, List ls] -> List <$> traverse (callFn fn) (pure <$> ls)[_, _] -> throwErrorHere $ TypeError "map: second argument should be a list"xs -> throwErrorHere $ WrongNumberOfArgs "map" 3 (length xs))- , ("keyword?", evalOneArg "keyword?" $ \case+ , ("keyword?", oneArg "keyword?" $ \caseKeyword _ -> pure tt_ -> pure ff)- , ("atom?", evalOneArg "atom?" $ \case+ , ("atom?", oneArg "atom?" $ \caseAtom _ -> pure tt_ -> pure ff)- , ("list?", evalOneArg "list?" $ \case+ , ("list?", oneArg "list?" $ \caseList _ -> pure tt_ -> pure ff)- , ("dict?", evalOneArg "dict?" $ \case+ , ("dict?", oneArg "dict?" $ \caseDict _ -> pure tt_ -> pure ff), ( "type", let kw = pure . Keyword . Ident- in evalOneArg "type" $ \case+ in oneArg "type" $ \caseAtom _ -> kw "atom"Keyword _ -> kw "keyword"String _ -> kw "string"Number _ -> kw "number"Boolean _ -> kw "boolean"List _ -> kw "list"- Primop _ -> kw "primop"+ Vec _ -> kw "vector"+ PrimFn _ -> kw "function"Dict _ -> kw "dict"Ref _ -> kw "ref"Lambda{} -> kw "function")- , ("string?", evalOneArg "string?" $ \case+ , ("string?", oneArg "string?" $ \caseString _ -> pure tt_ -> pure ff)- , ("boolean?", evalOneArg "boolean?" $ \case+ , ("boolean?", oneArg "boolean?" $ \caseBoolean _ -> pure tt_ -> pure ff)- , ("number?", evalOneArg "number?" $ \case+ , ("number?", oneArg "number?" $ \caseNumber _ -> pure tt_ -> pure ff)- , ("member?", evalArgs $ \args -> case args of+ , ("member?", \case[x, List xs] -> pure . Boolean $ elem x xs[_, _] -> throwErrorHere$ TypeError "member?: second argument must be list"xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs))- , ("if", \args -> case args of- [condition, t, f] -> do- b <- baseEval condition- -- I hate this as much as everyone that might ever read Haskell, but- -- in Lisps a lot of things that one might object to are True...- if b == ff then baseEval f else baseEval t- xs -> throwErrorHere $ WrongNumberOfArgs "if" 3 (length xs))- , ( "cond", (cond =<<) . evenArgs "cond" )- , ("ref", evalOneArg "ref" newRef)- , ("read-ref", evalOneArg "read-ref" $ \case+ , ("ref", oneArg "ref" newRef)+ , ("read-ref", oneArg "read-ref" $ \caseRef ref -> readRef ref_ -> throwErrorHere $ TypeError "read-ref: argument must be a ref")- , ("write-ref", evalArgs $ \args -> case args of+ , ("write-ref", \case[Ref (Reference x), v] -> dost <- getput $ st { bindingsRefs = IntMap.insert x v $ bindingsRefs st }@@ -256,9 +204,9 @@ purePrimops = Primops $ fromList $ first Ident <$>$ TypeError "write-ref: first argument must be a ref"xs -> throwErrorHere$ WrongNumberOfArgs "write-ref" 2 (length xs))- , ("show", evalOneArg "show" (pure . String . renderPrettyDef))+ , ("show", oneArg "show" (pure . String . renderPrettyDef)), ( "seq"- , evalOneArg "seq" $+ , oneArg "seq" $\casex@(List _) -> pure xx@(Vec _) -> pure x@@ -266,16 +214,16 @@ purePrimops = Primops $ fromList $ first Ident <$>_ -> throwErrorHere $ TypeError "seq: can only be used on a list, vector or dictionary"), ( "to-json"- , evalOneArg "to-json" $ \v -> String . toS . Aeson.encode <$>+ , oneArg "to-json" $ \v -> String . toS . Aeson.encode <$>maybeJson v ?? toLangError (OtherError "Could not serialise value to JSON")), ( "default-ecc-curve",- evalArgs $ \case+ \case[] -> pure $ toRad defaultCurvexs -> throwErrorHere $ WrongNumberOfArgs "default-ecc-curve" 0 (length xs)), ( "verify-signature"- , evalArgs $ \case+ , \case[keyv, sigv, String msg] -> dokey <- hoistEither . first (toLangError . OtherError) $ fromRad keyvsig <- hoistEither . first (toLangError . OtherError) $ fromRad sigv@@ -286,29 +234,13 @@ purePrimops = Primops $ fromList $ first Ident <$>]where- cond = \case- [] -> pure nil- (c,e):ps -> do- b <- baseEval c- if b /= ff- then baseEval e- else cond ps-- -- | Some forms/functions expect an even number or arguments.- evenArgs name = \case- [] -> pure []- [_] -> throwErrorHere . OtherError $ name <> ": expects an even number of arguments"- x:y:xs -> do- ps <- evenArgs name xs- pure ((x,y):ps)-tt = Boolean Trueff = Boolean FalsenumBinop :: (Scientific -> Scientific -> Scientific)-> Text-> (Text, [Value] -> Lang m Value)- numBinop fn name = (name, evalArgs $ \args -> case args of+ numBinop fn name = (name, \caseNumber x:x':xs -> foldM go (Number x) (x':xs)wherego (Number a) (Number b) = pure . Number $ fn a b@@ -320,23 +252,21 @@ purePrimops = Primops $ fromList $ first Ident <$>-- * Helpers--- | Many primops evaluate their arguments just as normal functions do.-evalArgs :: Monad m => ([Value] -> Lang m Value) -> [Value] -> Lang m Value-evalArgs f args = traverse baseEval args >>= f---- Many primops evaluate a single argument.-evalOneArg :: Monad m => Text -> (Value -> Lang m Value) -> [Value] -> Lang m Value-evalOneArg fname f = evalArgs $ \case+-- Many primFns have a single argument.+oneArg :: Monad m => Text -> (Value -> Lang m Value) -> [Value] -> Lang m Value+oneArg fname f = \case[x] -> f xxs -> throwErrorHere $ WrongNumberOfArgs fname 1 (length xs)readValue- :: (MonadError (LangError Value) m, MonadState (Bindings (Primops n)) m)+ :: (MonadError (LangError Value) m)=> Text-> m ValuereadValue s = do- allPrims <- gets (getPrimops . bindingsPrimops)- let p = parse "[read-primop]" s (Map.keys allPrims)+ let p = parse "[read-primop]" scase p ofRight v -> pure vLeft e -> throwErrorHere $ ThrownError (Ident "parse-error") (String e)++primFnsEnv :: PrimFns m -> Env Value+primFnsEnv pfs = Env (Map.fromList [ (pf, PrimFn pf) | pf <- Map.keys (getPrimFns pfs)])diff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hsindex 169a135..675f151 100644--- a/test/spec/Radicle/Internal/Arbitrary.hs+++ b/test/spec/Radicle/Internal/Arbitrary.hs@@ -11,7 +11,7 @@ import Test.QuickCheck.Instances ()import Radicleimport Radicle.Internal.Parse (isValidIdentFirst, isValidIdentRest)-import Radicle.Internal.Primops (purePrimops)+import Radicle.Internal.PrimFns (purePrimFns)instance Arbitrary r => Arbitrary (Env r) wherearbitrary = Env <$> arbitrary@@ -29,7 +29,7 @@ instance Arbitrary Value where, (3, Boolean <$> arbitrary), (3, Number <$> arbitrary), (1, List <$> sizedList)- , (6, Primop <$> elements (Map.keys $ getPrimops prims))+ , (6, PrimFn <$> elements (Map.keys $ getPrimFns prims)), (1, Lambda <$> sizedList<*> scale (`div` 3) arbitrary<*> scale (`div` 3) arbitrary)@@ -40,9 +40,9 @@ instance Arbitrary Value wheresizedList = sized $ \n -> dok <- choose (0, n)scale (`div` (k + 1)) $ vectorOf k arbitrary- prims :: Primops Identity- prims = purePrimops- isPrimop x = x `elem` Map.keys (getPrimops prims)+ prims :: PrimFns Identity+ prims = purePrimFns+ isPrimop x = x `elem` Map.keys (getPrimFns prims)isNum x = isJust (readMaybe (toS $ fromIdent x) :: Maybe Scientific)instance Arbitrary Ident wherediff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex f182384..acbf077 100644--- a/test/spec/Radicle/Internal/TestCapabilities.hs+++ b/test/spec/Radicle/Internal/TestCapabilities.hs@@ -27,7 +27,7 @@ type TestLang = Lang (State WorldState)-- | Run a possibly side-effecting program with the given stdin input lines.runTestWithFiles- :: Bindings (Primops (State WorldState))+ :: Bindings (PrimFns (State WorldState))-> [Text] -- The stdin (errors if it runs out)-> Map Text Text -- The files-> Text -- The program@@ -45,7 +45,7 @@ runTestWithFiles bindings inputs files action =-- | Run a possibly side-effecting program with the given stdin input lines.runTestWith- :: Bindings (Primops (State WorldState))+ :: Bindings (PrimFns (State WorldState))-> [Text] -- The stdin (errors if it runs out)-> Text -- The program-> (Either (LangError Value) Value, [Text])@@ -60,7 +60,7 @@ runTestWith' = runTestWith pureEnv-- | Run a test without stdin/stdoutrunTest- :: Bindings (Primops (State WorldState))+ :: Bindings (PrimFns (State WorldState))-> Text-> Either (LangError Value) ValuerunTest bnds prog = fst $ runTestWith bnds [] progdiff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 6aa55db..86db288 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -280,7 +280,7 @@ test_eval ="(type 'a)" `hasTy` "atom""(type 1)" `hasTy` "number""(type #t)" `hasTy` "boolean"- "(type list?)" `hasTy` "primop"+ "(type list?)" `hasTy` "function""(type (list 1 2 3))" `hasTy` "list""(type (dict 1 2))" `hasTy` "dict""(type (ref 0))" `hasTy` "ref"@@ -419,7 +419,7 @@ test_eval =runTest' "(show #t)" @?= Right (String "#t")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 [ident|base-eval|])+ runTest' "eval" @?= Right (PrimFn [ident|base-eval|])runTest' "(show (dict 'a 1))" @?= Right (String "{a 1.0}")runTest' "(show (fn [x] x))" @?= Right (String "(fn [x] x)")@@ -486,10 +486,6 @@ test_parser ="#t" ~~> Boolean True"#f" ~~> Boolean False- , testCase "parses primops" $ do- "boolean?" ~~> Primop [ident|boolean?|]- "base-eval" ~~> Primop [ident|base-eval|]-, testCase "parses keywords" $ do":foo" ~~> kw "foo"":what?crazy!" ~~> kw "what?crazy!"@@ -636,8 +632,8 @@ test_repl =(_, result) <- runInRepl inputresult @==> output- , testCase "(def eval (quote base-eval)) doesn't change things" $ do- let input = [ "(def eval (quote base-eval))"+ , testCase "(def eval base-eval) doesn't change things" $ do+ let input = [ "(def eval base-eval)", "(def id (fn [x] x))", "(id #t)"]@@ -716,10 +712,7 @@ atom = Atom . unsafeToIdent-- -- | Like 'parse', but uses "(test)" as the source name and the default set of-- -- primops.parseTest :: MonadError Text m => Text -> m Value-parseTest t = parse "(test)" t (Map.keys . getPrimops $ bindingsPrimops e)- where- e :: Bindings (Primops (Lang Identity))- e = pureEnv+parseTest t = parse "(test)" tprettyEither :: Either (LangError Value) Value -> T.TextprettyEither (Left e) = "Error: " <> renderPrettyDef e