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.yamlindex 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.hsindex 50d336c..df2c848 100644--- a/exe/Doc.hs+++ b/exe/Doc.hs@@ -7,7 +7,7 @@ import Protoludeimport qualified Data.Text as Timport Options.Applicativeimport Radicle-import System.Console.Haskeline (defaultSettings, runInputT)+import qualified Radicle.Internal.Input as Inputimport Text.Pandocmain :: IO ()@@ -25,7 +25,7 @@ run :: FilePath -> IO ()run f = dotxt <- readFile fpand <- runIOorExplode $ readMarkdown def txt- res <- runInputT defaultSettings $ runLang replBindings $ interpretMany (toS f) $ getCode pand+ res <- Input.runInputT Nothing $ runLang replBindings $ interpretMany (toS f) $ getCode pandcase res of(Left err, _) -> die . toS $ "Error: " ++ show err_ -> pure ()diff --git a/exe/RadicleExe.hs b/exe/RadicleExe.hsindex 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 Radicleimport Servant.Client-import System.Console.Haskeline (InputT)import System.Directory (doesFileExist)import qualified Radicle.Internal.Number as Num+import qualified Radicle.Internal.Input as Inputimport qualified Radicle.Internal.PrimFns as PrimFnsmain :: 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]wheresendPrimop =diff --git a/exe/ReferenceDoc.hs b/exe/ReferenceDoc.hsindex 5603df4..0172608 100644--- a/exe/ReferenceDoc.hs+++ b/exe/ReferenceDoc.hs@@ -11,12 +11,12 @@ import qualified Data.Map.Strict as Mapimport qualified Data.Text as Timport qualified GHC.Exts as GhcExtsimport Radicle-import System.Console.Haskeline (defaultSettings, runInputT)+import qualified Radicle.Internal.Input as Inputimport Text.Pandocmain :: 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.radindex 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.radindex 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.hsindex 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) whereinstance CPA t => FromRad t Rational wherefromRad (Number n) = pure nfromRad _ = 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 wherefromRad = fromRad >=> Num.isSciinstance CPA t => FromRad t Int wherediff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hsindex 3eda050..c04a208 100644--- a/src/Radicle/Internal/Effects.hs+++ b/src/Radicle/Internal/Effects.hs@@ -9,20 +9,11 @@ import qualified Data.Text as Timport 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.Coreimport Radicle.Internal.Cryptoimport Radicle.Internal.Effects.Capabilities+import qualified Radicle.Internal.Input as Inputimport Radicle.Internal.Interpretimport Radicle.Internal.Prettyimport 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) wheregetRandomBytes = liftIO . getRandomBytesinstance MonadRandom m => MonadRandom (LangT (Bindings (PrimFns m)) m) wheregetRandomBytes = lift . getRandomBytes-instance UUID.MonadUUID (InputT IO) where+instance UUID.MonadUUID (Input.InputT IO) whereuuid = liftIO UUID.uuidinstance UUID.MonadUUID m => UUID.MonadUUID (LangT (Bindings (PrimFns m)) m) whereuuid = 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 preCodecase r of@@ -58,25 +47,12 @@ repl histFile preFileName preCode bindings = doLeft e -> putDoc $ pretty eRight () -> 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 pureEnvreplPrimFns :: ReplM m => PrimFns mreplPrimFns = fromList $ allDocs $- [ ("print!"+ [ ( "print!", "Pretty-prints a value.", \case[x] -> do@@ -84,6 +60,13 @@ replPrimFns = fromList $ allDocs $pure nilxs -> 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!" $ \caseString filename -> readFileS filename >>= \caseLeft err -> throwErrorHere . OtherError $ "Error reading file: " <> errRight text -> pure $ String text@@ -175,7 +169,7 @@ replPrimFns = fromList $ allDocs $String filename -> readFileS filename >>= \caseLeft err -> throwErrorHere . OtherError $ "Error reading file: " <> errRight 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.hsindex 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 whereimport Protolude+import qualified Data.Map as Mapimport Data.Text.Prettyprint.Doc (PageWidth)-import System.Console.Haskeline hiding (catch)import System.IO (isEOF)#ifdef ghcjs_HOST_OSimport GHCJS.DOM.XMLHttpRequest@@ -16,19 +17,30 @@ import GHCJS.DOM.XMLHttpRequest#endifimport Radicle.Internal.Core+import qualified Radicle.Internal.Input as Inputclass (Monad m) => Stdin m wheregetLineS :: m (Maybe Text) -- gives Nothing on EOF+ getLineCompletionS :: [Text] -> m (Maybe Text)instance {-# OVERLAPPABLE #-} Stdin m => Stdin (Lang m) wheregetLineS = lift getLineS+ getLineCompletionS = lift . getLineCompletionSinstance Stdin IO wheregetLineS = dodone <- isEOFif donethen pure Nothingelse 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 whereputStrS :: Text -> m ()@@ -36,8 +48,8 @@ instance {-# OVERLAPPABLE #-} Stdout m => Stdout (Lang m) whereputStrS = lift . putStrSinstance Stdout IO whereputStrS = 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 . toSclass (Monad m) => Exit m whereexitS :: m ()@@ -66,7 +78,7 @@ class (Monad m) => SetSubs m whereclass (Monad m) => ReadFile m wherereadFileS :: Text -> m (Either Text Text) -- ^ Left error or Right contents#ifdef ghcjs_HOST_OS-instance ReadFile (InputT IO) where+instance ReadFile (Input.InputT IO) wherereadFileS = lift . requestFilewhererequestFile :: Text -> IO (Either Text Text)@@ -79,11 +91,12 @@ instance ReadFile (InputT IO) whereNothing -> Left "no response from server"Just v -> Right v#else-instance ReadFile (InputT IO) where- readFileS = lift . readFileSinstance ReadFile IO wherereadFileS 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)))#endifinstance {-# OVERLAPPABLE #-} ReadFile m => ReadFile (Lang m) wherereadFileS = lift . readFileSdiff --git a/src/Radicle/Internal/Input.hs b/src/Radicle/Internal/Input.hsnew file mode 100644index 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.unpackdiff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hsindex 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 ofLeft _ -> 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 vscase xs `atMay` i ofJust x -> pure xNothing -> throwErrorHere $ OtherError "nth: index out of bounds"diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex 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 wherecase worldStateStdin ws of[] -> pure Nothingh:hs -> lift (put $ ws { worldStateStdin = hs }) >> pure (Just h)+ getLineCompletionS _ = getLineSinstance {-# OVERLAPPING #-} Stdout TestLang whereputStrS t = lift $