Skip to content

A peer-to-peer stack for code collaboration

Make completion respond to all definitions in scope.

Luke Palmer01c575f294e1
diff --git a/.hlint.yaml b/.hlint.yaml
index 09ab05c..95449e8 100644
--- a/.hlint.yaml
+++ b/.hlint.yaml
@@ -27,6 +27,7 @@
- ignore: {name: Redundant do}
- ignore: {name: Use ++}
- ignore: {name: Use &&}
+- ignore: {name: Use <$>}
- ignore: {name: Use fromMaybe}
- ignore: {name: Eta reduce}
- ignore: {name: Use lambda-case}
diff --git a/exe/Doc.hs b/exe/Doc.hs
index 50d336c..df2c848 100644
--- a/exe/Doc.hs
+++ b/exe/Doc.hs
@@ -7,7 +7,7 @@ import Protolude
import qualified Data.Text as T
import Options.Applicative
import Radicle
-import System.Console.Haskeline (defaultSettings, runInputT)
+import qualified Radicle.Internal.Input as Input
import Text.Pandoc
main :: IO ()
@@ -25,7 +25,7 @@ run :: FilePath -> IO ()
run f = do
txt <- readFile f
pand <- runIOorExplode $ readMarkdown def txt
- res <- runInputT defaultSettings $ runLang replBindings $ interpretMany (toS f) $ getCode pand
+ res <- Input.runInputT Nothing $ runLang replBindings $ interpretMany (toS f) $ getCode pand
case res of
(Left err, _) -> die . toS $ "Error: " ++ show err
_ -> pure ()
diff --git a/exe/RadicleExe.hs b/exe/RadicleExe.hs
index fd0d3fc..44caaf4 100644
--- a/exe/RadicleExe.hs
+++ b/exe/RadicleExe.hs
@@ -11,10 +11,10 @@ import Prelude (String)
import Protolude hiding (TypeError, option, sourceFile)
import Radicle
import Servant.Client
-import System.Console.Haskeline (InputT)
import System.Directory (doesFileExist)
import qualified Radicle.Internal.Number as Num
+import qualified Radicle.Internal.Input as Input
import qualified Radicle.Internal.PrimFns as PrimFns
main :: IO ()
@@ -72,10 +72,10 @@ opts = Opts
-- * Primops
-bindings :: HttpClient.Manager -> Bindings (PrimFns (InputT IO))
+bindings :: HttpClient.Manager -> Bindings (PrimFns (Input.InputT IO))
bindings mgr = addPrimFns (replPrimFns <> clientPrimFns mgr) pureEnv
-clientPrimFns :: HttpClient.Manager -> PrimFns (InputT IO)
+clientPrimFns :: HttpClient.Manager -> PrimFns (Input.InputT IO)
clientPrimFns mgr = fromList . PrimFns.allDocs $ [sendPrimop, receivePrimop]
where
sendPrimop =
diff --git a/exe/ReferenceDoc.hs b/exe/ReferenceDoc.hs
index 5603df4..0172608 100644
--- a/exe/ReferenceDoc.hs
+++ b/exe/ReferenceDoc.hs
@@ -11,12 +11,12 @@ import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import qualified GHC.Exts as GhcExts
import Radicle
-import System.Console.Haskeline (defaultSettings, runInputT)
+import qualified Radicle.Internal.Input as Input
import Text.Pandoc
main :: IO ()
main = do
- res_ <- runInputT defaultSettings $
+ res_ <- Input.runInputT Nothing $
interpret
"reference-doc"
"(do (load! \"rad/prelude.rad\") (get-current-env))"
diff --git a/rad/prelude/dict.rad b/rad/prelude/dict.rad
index e0fc3cd..3d03b47 100644
--- a/rad/prelude/dict.rad
+++ b/rad/prelude/dict.rad
@@ -19,12 +19,14 @@
(def keys
"Given a `dict`, returns a vector of its keys."
(fn [d]
- (map head (seq d))))
+ (map (fn [s] (nth 0 s)) (seq d))))
(:test "keys"
[ (keys {:one 1 :two 2}) ==> [:one :two] ]
)
+;; values
+
(def values
"Given a `dict`, returns a vector of its values."
(fn [d]
diff --git a/rad/repl.rad b/rad/repl.rad
index eda4638..9520d77 100644
--- a/rad/repl.rad
+++ b/rad/repl.rad
@@ -2,15 +2,17 @@
;; The Repl
-(def read-line-or-exit! (fn []
- (def line (get-line!))
- (if (eq? line nil)
- (exit!)
- (read line))))
+(def repl (fn []
+ (def-rec repl-rec (fn [st]
+ (def line (get-expression! (keys (lookup :env st))))
+ (def cur-eval (lookup :val (lookup 'eval (lookup :env st))))
+ (if (eq? line nil)
+ nil
+ (catch 'any (do (def ret (cur-eval (read line) st))
+ (print! (head ret))
+ (repl-rec (head (tail ret))))
+ (fn [e] (put-str! (string-append "Exception " (show e)))
+ (repl-rec st))))))
+ (repl-rec (get-current-env))))
-(def repl
- {:name "repl"
- ;; Parse errors are thrown here
- :getter read-line-or-exit!})
-
-(subscribe-to! repl print!)
+(repl)
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 1261749..14ba487 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -541,6 +541,9 @@ instance FromRad t (Annotated t ValueF) where
instance CPA t => FromRad t Rational where
fromRad (Number n) = pure n
fromRad _ = Left "Not a number"
+instance (CPA t) => FromRad t Ident where
+ fromRad (Atom i) = pure i
+ fromRad _ = Left "Expecting identifier"
instance CPA t => FromRad t Scientific where
fromRad = fromRad >=> Num.isSci
instance CPA t => FromRad t Int where
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 3eda050..c04a208 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -9,20 +9,11 @@ import qualified Data.Text as T
import Data.Text.Prettyprint.Doc (pretty)
import Data.Text.Prettyprint.Doc.Render.Terminal (putDoc)
import GHC.Exts (IsList(..))
-import System.Console.Haskeline
- ( CompletionFunc
- , InputT
- , completeWord
- , defaultSettings
- , historyFile
- , runInputT
- , setComplete
- , simpleCompletion
- )
import Radicle.Internal.Core
import Radicle.Internal.Crypto
import Radicle.Internal.Effects.Capabilities
+import qualified Radicle.Internal.Input as Input
import Radicle.Internal.Interpret
import Radicle.Internal.Pretty
import Radicle.Internal.PrimFns
@@ -36,21 +27,19 @@ type ReplM m =
, GetEnv (Lang m) Value
, SetEnv (Lang m) Value )
-instance MonadRandom (InputT IO) where
+instance MonadRandom (Input.InputT IO) where
getRandomBytes = liftIO . getRandomBytes
instance MonadRandom m => MonadRandom (LangT (Bindings (PrimFns m)) m) where
getRandomBytes = lift . getRandomBytes
-instance UUID.MonadUUID (InputT IO) where
+instance UUID.MonadUUID (Input.InputT IO) where
uuid = liftIO UUID.uuid
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 ()
+repl :: Maybe FilePath -> Text -> Text -> Bindings (PrimFns (Input.InputT IO)) -> IO ()
repl histFile preFileName preCode bindings = do
- let settings = setComplete completion
- $ defaultSettings { historyFile = histFile }
- r <- runInputT settings
+ r <- Input.runInputT histFile
$ fmap fst $ runLang bindings
$ void $ interpretMany preFileName preCode
case r of
@@ -58,25 +47,12 @@ repl histFile preFileName preCode bindings = do
Left e -> putDoc $ pretty e
Right () -> pure ()
-completion :: Monad m => CompletionFunc m
-completion = completeWord Nothing ['(', ')', ' ', '\n'] go
- where
- -- Any type for first param will do
- bnds :: Bindings (PrimFns (InputT IO))
- bnds = replBindings
-
- go s = pure $ fmap simpleCompletion
- $ filter (s `isPrefixOf`)
- $ fmap (T.unpack . fromIdent)
- $ (Map.keys . fromEnv $ bindingsEnv bnds)
- <> Map.keys (getPrimFns $ bindingsPrimFns bnds)
-
replBindings :: ReplM m => Bindings (PrimFns m)
replBindings = addPrimFns replPrimFns pureEnv
replPrimFns :: ReplM m => PrimFns m
replPrimFns = fromList $ allDocs $
- [ ("print!"
+ [ ( "print!"
, "Pretty-prints a value."
, \case
[x] -> do
@@ -84,6 +60,13 @@ replPrimFns = fromList $ allDocs $
pure nil
xs -> throwErrorHere $ WrongNumberOfArgs "print!" 1 (length xs))
+ , ( "put-str!"
+ , "Outputs a string verbatim."
+ , oneArg "put-str!" $ \case
+ String str -> putStrS str >> pure nil
+ _ -> throwErrorHere $ TypeError "put-str!: expects a string"
+ )
+
, ( "doc!"
, "Prints the documentation attached to a value and returns `()`. To retrieve\
\ the docstring as a value use `doc` instead."
@@ -123,6 +106,16 @@ replPrimFns = fromList $ allDocs $
xs -> throwErrorHere $ WrongNumberOfArgs "get-line!" 0 (length xs)
)
+ , ( "get-expression!"
+ , "Reads a line of input and returns it as a string. Takes a list of completion \
+ \words."
+ , \case
+ [complV] -> do
+ compl <- hoistEither . first (toLangError . OtherError) $ fromRad complV
+ maybe nil toRad <$> getLineCompletionS (map fromIdent compl)
+ xs -> throwErrorHere $ WrongNumberOfArgs "get-expression!" 1 (length xs)
+ )
+
, ("subscribe-to!"
, "Expects a dict `s` (representing a subscription) and a function `f`. The dict\
\ `s` should have a function `getter` at the key `:getter`. This function is called\
@@ -160,9 +153,10 @@ replPrimFns = fromList $ allDocs $
void $ withEnv (const e) (fn $$ [quote line])
_ -> throwErrorHere $ TypeError "subscribe-to!: Expected dict"
xs -> throwErrorHere $ WrongNumberOfArgs "subscribe-to!" 2 (length xs))
+
, ( "read-file!"
, "Reads the contents of a file and returns it as a string."
- , oneArg "read-file" $ \case
+ , oneArg "read-file!" $ \case
String filename -> readFileS filename >>= \case
Left err -> throwErrorHere . OtherError $ "Error reading file: " <> err
Right text -> pure $ String text
@@ -175,7 +169,7 @@ replPrimFns = fromList $ allDocs $
String filename -> readFileS filename >>= \case
Left err -> throwErrorHere . OtherError $ "Error reading file: " <> err
Right text -> interpretMany ("[load! " <> filename <> "]") text
- _ -> throwErrorHere $ TypeError "load: expects a string"
+ _ -> throwErrorHere $ TypeError "load!: expects a string"
)
, ( "gen-key-pair!"
, "Given an elliptic curve, generates a cryptographic key-pair. Use\
diff --git a/src/Radicle/Internal/Effects/Capabilities.hs b/src/Radicle/Internal/Effects/Capabilities.hs
index ec495f1..d0600e9 100644
--- a/src/Radicle/Internal/Effects/Capabilities.hs
+++ b/src/Radicle/Internal/Effects/Capabilities.hs
@@ -2,13 +2,14 @@
--
-- The intent is that any set of primops may wear on their sleaves (i.e.
-- constraints) what effects they do.
-{-# LANGUAGE CPP #-}
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE TypeApplications #-}
module Radicle.Internal.Effects.Capabilities where
import Protolude
+import qualified Data.Map as Map
import Data.Text.Prettyprint.Doc (PageWidth)
-import System.Console.Haskeline hiding (catch)
import System.IO (isEOF)
#ifdef ghcjs_HOST_OS
import GHCJS.DOM.XMLHttpRequest
@@ -16,19 +17,30 @@ import GHCJS.DOM.XMLHttpRequest
#endif
import Radicle.Internal.Core
+import qualified Radicle.Internal.Input as Input
class (Monad m) => Stdin m where
getLineS :: m (Maybe Text) -- gives Nothing on EOF
+ getLineCompletionS :: [Text] -> m (Maybe Text)
instance {-# OVERLAPPABLE #-} Stdin m => Stdin (Lang m) where
getLineS = lift getLineS
+ getLineCompletionS = lift . getLineCompletionS
instance Stdin IO where
getLineS = do
done <- isEOF
if done
then pure Nothing
else Just <$> getLine
-instance (MonadException m) => Stdin (InputT m) where
- getLineS = (fmap.fmap) toS (getInputLine "rad> ")
+ getLineCompletionS _ = getLineS
+instance (Input.MonadException m) => Stdin (Input.InputT m) where
+ getLineS = Input.getInputLine Input.noCompletions "rad> "
+ getLineCompletionS compl = Input.getInputLine (radicleCompletion compl) "rad> "
+
+
+radicleCompletion :: (Monad m) => [Text] -> Input.Completions m
+radicleCompletion = Input.wordCompletions ['(', ')', ' ', '\n'] . (specials <>)
+ where
+ specials = fromIdent <$> Map.keys (specialForms @Identity)
class (Monad m) => Stdout m where
putStrS :: Text -> m ()
@@ -36,8 +48,8 @@ instance {-# OVERLAPPABLE #-} Stdout m => Stdout (Lang m) where
putStrS = lift . putStrS
instance Stdout IO where
putStrS = putStrLn
-instance (MonadException m, Monad m) => Stdout (InputT m) where
- putStrS = outputStrLn . toS
+instance (Input.MonadException m, Monad m) => Stdout (Input.InputT m) where
+ putStrS = Input.outputStrLn . toS
class (Monad m) => Exit m where
exitS :: m ()
@@ -66,7 +78,7 @@ class (Monad m) => SetSubs m where
class (Monad m) => ReadFile m where
readFileS :: Text -> m (Either Text Text) -- ^ Left error or Right contents
#ifdef ghcjs_HOST_OS
-instance ReadFile (InputT IO) where
+instance ReadFile (Input.InputT IO) where
readFileS = lift . requestFile
where
requestFile :: Text -> IO (Either Text Text)
@@ -79,11 +91,12 @@ instance ReadFile (InputT IO) where
Nothing -> Left "no response from server"
Just v -> Right v
#else
-instance ReadFile (InputT IO) where
- readFileS = lift . readFileS
instance ReadFile IO where
readFileS fname = (Right <$> readFile (toS fname))
`catch` (\(e :: IOException) -> pure (Left (show e)))
+instance ReadFile (Input.InputT IO) where
+ readFileS fname = lift $ (Right <$> readFile (toS fname))
+ `catch` (\(e :: IOException) -> pure (Left (show e)))
#endif
instance {-# OVERLAPPABLE #-} ReadFile m => ReadFile (Lang m) where
readFileS = lift . readFileS
diff --git a/src/Radicle/Internal/Input.hs b/src/Radicle/Internal/Input.hs
new file mode 100644
index 0000000..336fff3
--- /dev/null
+++ b/src/Radicle/Internal/Input.hs
@@ -0,0 +1,61 @@
+-- | Haskeline-style wrapper, since it doesn't *quite* provide the right API
+-- (completion functions cannot be dynamically modified). It will also enable
+-- a nice abstraction barrier for REPL UI features.
+
+module Radicle.Internal.Input
+ ( InputT
+ , Completions
+ , noCompletions
+ , wordCompletions
+ , getInputLine
+ , runInputT
+ , outputStrLn
+
+ , MonadException
+ )
+where
+
+import Protolude
+
+import Control.Monad.Trans (MonadTrans(..))
+import qualified Data.Text as T
+import System.Console.Haskeline (MonadException)
+import qualified System.Console.Haskeline as H
+
+newtype InputT m a = InputT { unInputT :: H.InputT (ReaderT (Completions m) m) a }
+ deriving (Functor, Applicative, Monad)
+
+instance MonadTrans InputT where
+ lift = InputT . lift . lift
+
+instance (MonadIO m) => MonadIO (InputT m) where
+ liftIO = lift . liftIO
+
+newtype Completions m = Completions { getCompletions :: H.CompletionFunc (ReaderT (Completions m) m) }
+
+noCompletions :: (Monad m) => Completions m
+noCompletions = Completions H.noCompletion
+
+wordCompletions :: (Monad m) => [Char] -> [Text] -> Completions m
+wordCompletions whitespace words = Completions $ H.completeWord Nothing whitespace go
+ where
+ go s = pure . fmap H.simpleCompletion
+ . filter (s `isPrefixOf`)
+ $ map T.unpack words
+{-# ANN wordCompletions ("HLint: ignore Use String" :: [Char]) #-}
+
+getInputLine :: (Monad m, MonadException m) => Completions m -> Text -> InputT m (Maybe Text)
+getInputLine compl prompt = InputT $
+ (fmap.fmap) toS $ H.mapInputT (local (const compl)) (H.getInputLine (T.unpack prompt))
+
+runInputT :: (MonadException m) => Maybe FilePath -> InputT m a -> m a
+runInputT histfile = (`runReaderT` noCompletions)
+ . H.runInputT (H.setComplete dynamicCompletion H.defaultSettings { H.historyFile = histfile })
+ . unInputT
+ where
+ dynamicCompletion cx = do
+ compl <- ask
+ getCompletions compl cx
+
+outputStrLn :: (MonadIO m) => Text -> InputT m ()
+outputStrLn = InputT . H.outputStrLn . T.unpack
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index 2a78249..0cf9ef0 100644
--- a/src/Radicle/Internal/PrimFns.hs
+++ b/src/Radicle/Internal/PrimFns.hs
@@ -209,7 +209,7 @@ purePrimFns = fromList $ allDocs $
[Number n, vs] -> case Num.isInt n of
Left _ -> throwErrorHere $ OtherError "nth: first argument was not an integer"
Right i -> do
- xs <- hoistEitherWith (const (toLangError . OtherError $ "nth: first argument must be sequential")) $ fromRad vs
+ xs <- hoistEitherWith (const (toLangError . OtherError $ "nth: second argument must be sequential")) $ fromRad vs
case xs `atMay` i of
Just x -> pure x
Nothing -> throwErrorHere $ OtherError "nth: index out of bounds"
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index 4f10325..ce9494e 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -135,6 +135,7 @@ instance {-# OVERLAPPING #-} Stdin TestLang where
case worldStateStdin ws of
[] -> pure Nothing
h:hs -> lift (put $ ws { worldStateStdin = hs }) >> pure (Just h)
+ getLineCompletionS _ = getLineS
instance {-# OVERLAPPING #-} Stdout TestLang where
putStrS t = lift $