Skip to content

A peer-to-peer stack for code collaboration

feat: New rad repl (#663)

Julian Arniad8cacf784d0
diff --git a/.weeder.yaml b/.weeder.yaml
index 154d207..8ff7b58 100644
--- a/.weeder.yaml
+++ b/.weeder.yaml
@@ -8,7 +8,6 @@
- module:
- name: Radicle.Tests
- identifier:
- - assertReplInteraction
- atom
- int
- kw
diff --git a/bin/rad-repl b/bin/rad-repl
deleted file mode 100755
index afb9e6f..0000000
--- a/bin/rad-repl
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/usr/bin/env radicle
-(load! (find-module-file! "prelude.rad"))
-
-(def help
- "Default help text."
- "Radicle REPL
-
-Type (apropos!) for a list of functions in scope.
-Type (doc! '<name>) for further documentation of <name>.")
-
-(def read-line-or-exit!
- (fn []
- (def line (get-line!))
- (if (eq? line nil)
- (exit! 0)
- (read-many-annotated "[read-line-or-exit!]" line))))
-
-(put-str! help)
-(def repl
- {:name "repl"
- ;; Parse errors are thrown here
- :getter read-line-or-exit!})
-
-(subscribe-to! repl (fn [xs] (map print! xs)))
diff --git a/exe/RadicleExe.hs b/exe/RadicleExe.hs
index 2c47716..c8ce46c 100644
--- a/exe/RadicleExe.hs
+++ b/exe/RadicleExe.hs
@@ -8,32 +8,20 @@ import Options.Applicative
import System.Directory (doesFileExist)
import Radicle
-import Radicle.Internal.Effects (exitCode)
-import Radicle.Internal.Pretty (putPrettyAnsi)
main :: IO ()
main = do
opts' <- execParser allOpts
+ bindings <- createImpureBindings (toS <$> scriptArgs opts')
code <-
if sourceFile opts' == "-"
then do
src <- decodeUtf8With lenientDecode <$> BS.getContents
- let prog = interpretMany "[stdin]" src
- bindings <- createImpureBindings (toS <$> scriptArgs opts')
- (result, _state) <- runLang bindings prog
- case result of
- Left (LangError _ (Exit n)) -> pure (exitCode n)
- Left e -> do putPrettyAnsi e
- pure $ ExitFailure 1
- Right v -> do putPrettyAnsi v
- pure ExitSuccess
+ script "[stdin]" src bindings
else do
- src <- ignoreShebang <$> readSource (sourceFile opts')
- hist <- case histFile opts' of
- Nothing -> getHistoryFile
- Just h -> pure h
- bindings <- createImpureBindings (toS <$> scriptArgs opts')
- repl (Just hist) (toS $ sourceFile opts') src bindings
+ let srcFile = sourceFile opts'
+ src <- readSource srcFile
+ script (toS srcFile) src bindings
exitWith code
where
allOpts = info (opts <**> helper)
@@ -51,18 +39,12 @@ readSource file = do
else die $ "Could not find file: " <> toS file
radDesc :: String
-radDesc
- = "Interprets a radicle program.\n"
- <> "\n"
- <> "This program can also be used as a REPL by providing a file "
- <> "that defines a REPL. An example is the rad/repl.rad file included "
- <> "in the distribution."
+radDesc = "Interprets a radicle program."
-- * CLI Opts
data Opts = Opts
{ sourceFile :: FilePath
- , histFile :: Maybe FilePath
, scriptArgs :: [String]
}
@@ -72,15 +54,4 @@ opts = Opts
( metavar "FILE"
<> help "File to interpret. Use - to read the code from stdin."
)
- <*> optional (strOption
- ( long "histfile"
- <> short 'H'
- <> metavar "FILE"
- <> help
- ( "File used to store the REPL history."
- <> "Defaults to $DIR/radicle/config.rad "
- <> "where $DIR is $XDG_DATA_HOME (%APPDATA% on Windows "
- <> "if that is set, or else ~/.local/share."
- )
- ))
<*> many (strArgument mempty)
diff --git a/exe/RadicleRepl.hs b/exe/RadicleRepl.hs
new file mode 100644
index 0000000..b2907b0
--- /dev/null
+++ b/exe/RadicleRepl.hs
@@ -0,0 +1,53 @@
+module RadicleRepl (main) where
+
+import Prelude (String)
+import Protolude hiding (TypeError, option, sourceFile)
+
+import Options.Applicative
+
+import Radicle
+
+main :: IO ()
+main = do
+ opts' <- execParser allOpts
+ hist <- case histFile opts' of
+ Nothing -> getHistoryFile
+ Just h -> pure h
+ bindings <- createImpureBindings []
+ putStr intro
+ repl (Just hist) "" bindings
+ where
+ allOpts = info (opts <**> helper)
+ ( fullDesc
+ <> progDesc radDesc
+ <> header "The radicle REPL"
+ <> noIntersperse
+ )
+
+
+intro :: Text
+intro = "Radicle REPL\n\
+ \\n\
+ \Type (apropos!) for a list of functions in scope.\n\
+ \Type (doc! '<name>) for further documentation of <name>.\n"
+
+radDesc :: String
+radDesc = "The radicle REPL"
+
+newtype Opts = Opts
+ { histFile :: Maybe FilePath
+ }
+
+opts :: Parser Opts
+opts = Opts
+ <$> optional (strOption
+ ( long "histfile"
+ <> short 'H'
+ <> metavar "FILE"
+ <> help
+ ( "File used to store the REPL history."
+ <> "Defaults to $DIR/radicle/config.rad "
+ <> "where $DIR is $XDG_DATA_HOME (%APPDATA% on Windows "
+ <> "if that is set, or else ~/.local/share."
+ )
+ ))
diff --git a/package.yaml b/package.yaml
index b600c70..79d1a4d 100644
--- a/package.yaml
+++ b/package.yaml
@@ -53,6 +53,7 @@ library:
- http-media
- ipld-cid
- megaparsec
+ - mmorph
- mtl
- multibase
- optparse-applicative
@@ -88,8 +89,6 @@ tests:
- async
- containers
- cryptonite
- - directory
- - filemanip
- interpolate
- megaparsec
- process
@@ -176,6 +175,15 @@ executables:
- warp
ghc-options: -main-is Daemon
+ rad-repl:
+ main: RadicleRepl.hs
+ source-dirs: exe
+ other-modules: []
+ dependencies:
+ - radicle
+ - optparse-applicative
+ ghc-options: -main-is RadicleRepl
+
radicle-doc:
main: Doc.hs
source-dirs: exe/
diff --git a/src/Radicle.hs b/src/Radicle.hs
index 7a82f88..3e70ff6 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -67,6 +67,7 @@ module Radicle
-- * Parsing
, parse
, parseValues
+ , parseREPL
-- * Pretty-printing
, renderPretty
@@ -79,6 +80,9 @@ module Radicle
-- * Repl
, repl
+ -- * Script
+ , script
+
-- * PrimFns
, PrimFns(..)
, purePrimFns
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index a9489d7..7654c0a 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -12,7 +12,9 @@ import System.Console.Haskeline
, InputT
, completeWord
, defaultSettings
+ , getInputLine
, historyFile
+ , outputStrLn
, runInputT
, setComplete
, simpleCompletion
@@ -25,6 +27,7 @@ import Radicle.Internal.Eval
import Radicle.Internal.Identifier (Ident(..), unsafeToIdent)
import Radicle.Internal.Interpret
import Radicle.Internal.Number (isInt)
+import Radicle.Internal.Parse
import Radicle.Internal.Pretty
import Radicle.Internal.PrimFns
import Radicle.Internal.Time as Time
@@ -51,18 +54,37 @@ instance UUID.MonadUUID (InputT IO) where
instance UUID.MonadUUID m => UUID.MonadUUID (LangT (Bindings (PrimFns m)) m) where
uuid = lift UUID.uuid
-repl :: Maybe FilePath -> Text -> Text -> Bindings (PrimFns (InputT IO)) -> IO ExitCode
-repl histFile preFileName preCode bindings = do
- let settings = setComplete completion
- $ defaultSettings { historyFile = histFile }
- r <- runInputT settings
- $ fmap fst $ runLang bindings
- $ void $ interpretMany preFileName preCode
+script :: Text -> Text -> Bindings (PrimFns IO) -> IO ExitCode
+script fileName code bindings = do
+ r <- fmap fst <$> runLang bindings $ interpretMany fileName $ ignoreShebang code
case r of
Left (LangError _ (Exit n)) -> pure (exitCode n)
Left e -> do putPrettyAnsi e
pure $ ExitFailure 1
- Right () -> pure ExitSuccess
+ Right x -> do putPrettyAnsi x
+ pure ExitSuccess
+
+-- TODO: restore error preCode?
+repl :: Maybe FilePath -> Text -> Bindings (PrimFns (InputT IO)) -> IO ()
+repl histFile _ bindings = do
+ let settings = setComplete completion
+ $ defaultSettings { historyFile = histFile }
+ runInputT settings $ loop bindings
+ where
+ loop :: Bindings (PrimFns (InputT IO)) -> InputT IO ()
+ loop st = do
+ ln <- fmap toS <$> getInputLine "rad> "
+ case ln of
+ Nothing -> loop st
+ Just ln' -> do
+ parsed <- parseREPL (fmap toS <$> getInputLine "... ") ln'
+ case parsed of
+ Left e -> outputStrLn e >> loop st
+ Right v -> do
+ (res, newSt) <- runLang st (eval v)
+ case res of
+ Left e' -> putPrettyAnsi e' >> loop st
+ Right v' -> putPrettyAnsi v' >> loop newSt
exitCode :: Int -> ExitCode
exitCode 0 = ExitSuccess
diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hs
index b726ce6..0cbb6c9 100644
--- a/src/Radicle/Internal/Parse.hs
+++ b/src/Radicle/Internal/Parse.hs
@@ -3,6 +3,7 @@ module Radicle.Internal.Parse where
import Protolude hiding (SrcLoc, try)
import Control.Monad.Fail
+import Control.Monad.Morph (generalize, hoist)
import qualified Data.Char as Char
import qualified Data.Map as Map
import qualified Data.Sequence as Seq
@@ -210,6 +211,37 @@ parseTop p src code = runIdentity $ runReaderT (M.runParserT p (toS src) code) N
parseValue :: Text -> Text -> Either (Par.ParseErrorBundle Text Void) Value
parseValue = parseTop (spaceConsumer *> valueP <* eof)
+-- | Attempts to parse a value. If input is still left unconsumed, calls the
+-- provided `m (Maybe Text)` to get more text. This allows for multiline inputs
+-- in the REPL.
+--
+-- Megaparsec doesn't yet have streaming support (see
+-- <https://github.com/mrkkrp/megaparsec/issues/332 this issue>), so we reparse
+-- from scratch if more input is needed, which is somewhat inefficient.
+parseREPL
+ :: Monad m
+ => m (Maybe Text)
+ -> Text
+ -> m (Either [Char] Value)
+parseREPL getter code
+ = runReaderT (go code) NotInShortLambda
+ where
+ isEOFError e = case e of
+ Par.TrivialError _ (Just Par.EndOfInput) _ -> True
+ _ -> False
+ go this = do
+ res <- hoist generalize $ M.runParserT (spaceConsumer *> valueP) "[repl]" this
+ case res of
+ Left errs ->
+ if any isEOFError (Par.bundleErrors errs)
+ then do
+ next <- lift getter
+ case next of
+ Nothing -> pure . Left $ Par.errorBundlePretty errs
+ Just next' -> go $ this <> "\n" <> next'
+ else pure . Left $ Par.errorBundlePretty errs
+ Right v -> pure $ Right v
+
-- | Parse a Text as a series of values.
--
-- Note that parsing continues even if one value fails to parse.
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index f3732c6..8ba5aba 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -3,7 +3,6 @@
module Radicle.Internal.TestCapabilities (
runCodeWithWorld
, runPureCode
- , runCodeWithInput
, runCodeWithFiles
, WorldState(..)
@@ -16,8 +15,6 @@ import qualified Crypto.Random as CryptoRand
import qualified Data.Map.Strict as Map
import qualified Data.Sequence as Seq
import qualified Data.Time as Time
-import System.Directory (getCurrentDirectory)
-import qualified System.FilePath.Find as FP
import Radicle
import Radicle.Internal.Crypto
@@ -47,23 +44,8 @@ defaultWorldState =
, worldStateCurrentTime = Time.UTCTime (Time.ModifiedJulianDay 0) 0
}
-worldStateWithSource :: IO WorldState
-worldStateWithSource = do
- sources <- sourceFiles
- pure $ defaultWorldState { worldStateFiles = sources }
-
type TestLang = Lang (StateT WorldState IO)
--- | Run Radicle code in a REPL environment, with all library files
--- readable, and with the provided stdin lines.
---
--- The second item is the stdout.
-runCodeWithInput :: [Text] -> Text -> IO (Either (LangError Value) Value, [Text])
-runCodeWithInput input code = do
- ws' <- worldStateWithSource
- let ws = ws' { worldStateStdin = input }
- runCodeWithWorld ws code
-
-- | Run Radicle code in a REPL environment with the given files
-- readable.
runCodeWithFiles :: Map Text Text -> Text -> IO (Either (LangError Value) Value)
@@ -84,18 +66,6 @@ runCodeWithWorld ws code = do
(result, ws') <- runStateT (fst <$> runLang bindings prog) ws
pure $ (result, worldStateStdout ws')
--- | Loads the content for all radicle sources in the "./rad" folder.
--- Returns a map from files names to contents.
-sourceFiles :: IO (Map Text Text)
-sourceFiles = do
- dir <- getCurrentDirectory
- absPaths <- FP.find FP.always (FP.extension FP.==? ".rad") dir
- filesWithContent <- forM absPaths $ \absPath -> do
- contents <- readFile absPath
- let path = drop (length dir + 5) absPath
- pure (toS path, contents)
- pure $ Map.fromList filesWithContent
-
instance {-# OVERLAPPING #-} Stdin TestLang where
getLineS = do
ws <- lift get
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index 17cbfec..40c6920 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -774,55 +774,6 @@ test_repl_primops =
let ws = defaultWorldState { worldStateStdin = stdin' }
in fst <$> runCodeWithWorld ws prog
-test_repl :: [TestTree]
-test_repl =
- [ testCase "evaluates correctly" $ do
- let input = [ "((fn [x] x) #t)" ]
- output = [ "#t" ]
- assertReplInteraction input output
-
- , testCase "handles env modifications" $ do
- let input = [ "(def id (fn [x] x))"
- , "(id #t)"
- ]
- output = [ "()"
- , "#t"
- ]
- assertReplInteraction input output
-
- , testCase "handles 'eval' redefinition" $ do
- let input = [ "(def eval (fn [expr env] (list #t env)))"
- , "#f"
- ]
- output = [ "()"
- , "#t"
- ]
- assertReplInteraction input output
-
- , testCase "(def eval base-eval) doesn't change things" $ do
- let input = [ "(def eval base-eval)"
- , "(def id (fn [x] x))"
- , "(id #t)"
- ]
- output = [ "()"
- , "()"
- , "#t"
- ]
- assertReplInteraction input output
-
- , testCase "exceptions are non-fatal" $ do
- let input = [ "(throw 'something \"something happened\")"
- , "#t"
- ]
- assertReplInteraction input ["#t"]
-
- , testCase "load! a non-existent file is a non-fatal exception" $ do
- let input = [ "(load! \"not-a-thing.rad\")"
- , "#t"
- ]
- assertReplInteraction input ["#t"]
- ]
-
test_from_to_radicle :: [TestTree]
test_from_to_radicle =
[ testGroup "()"
@@ -912,18 +863,3 @@ parseTest t = parse "(test)" t
prettyEither :: Either (LangError Value) Value -> T.Text
prettyEither (Left e) = "Error: " <> renderPrettyDef e
prettyEither (Right v) = renderPrettyDef v
-
--- | Run a REPL with the given input lines and expected output.
---
--- We only assert the expected output against the end of the actual
--- output. This means that if @expected@ is @[a, b]@ then we only assert
--- that the last two lines of the actual output equal @[a, b]@.
-assertReplInteraction :: [Text] -> [Text] -> IO ()
-assertReplInteraction input expected = do
- (result, output) <- runCodeWithInput input "(load! (find-module-file! \"repl.rad\"))"
- case result of
- Left err -> assertFailure $ "Error thrown in Repl: " <> toS (renderPrettyDef err)
- Right _ -> pure ()
- -- In addition to the output of the lines tested, tests get
- -- printed, so we take only the last few output lines.
- reverse (take (length expected) output) @?= expected