Skip to content

A peer-to-peer stack for code collaboration

Sundry improvements.

Julian K. Arnibce6098db142
diff --git a/.hlint.yaml b/.hlint.yaml
index f518ff6..0232ca0 100644
--- a/.hlint.yaml
+++ b/.hlint.yaml
@@ -24,6 +24,7 @@
- ignore: {name: Use String, within: [Radicle.Internal.Parse]}
+- ignore: {name: Redundant do}
- ignore: {name: Use ++}
- ignore: {name: Use &&}
- ignore: {name: Eta reduce}
diff --git a/repl/prelude.rad b/repl/prelude.rad
new file mode 100644
index 0000000..3911bf3
--- /dev/null
+++ b/repl/prelude.rad
@@ -0,0 +1,64 @@
+(define should-be
+ (lambda (name x y)
+ (if (eq? x y)
+ (print! (cons "test" (cons name (list "succeeded"))))
+ (print! (cons "test" (cons name (list "failed")))))))
+
+;; empty?
+(define empty? (lambda (ls) (eq? ls (list))))
+(should-be "empty" (empty? (list 2)) #f)
+
+;; y-combinator
+(define Y
+ (lambda (h)
+ ((lambda (x) (x x))
+ (lambda (g)
+ (h (lambda (arg) ((g g) arg)))))))
+(define Y2
+ (lambda (h)
+ ((lambda (x) (x x))
+ (lambda (g)
+ (h (lambda (arg1 arg2) ((g g) arg1 arg2)))))))
+
+((lambda ()
+ (define fac (Y (lambda (f) (lambda (x) (if (< x 2) 1 (* x (f (- x 1))))))))
+ (should-be "fac" (fac 10) 3628800)))
+
+;; reverse
+(define reverse (lambda (ls)
+ (define go (Y2 (lambda (go)
+ (lambda (acc new)
+ (if (empty? new)
+ acc
+ (go (cons (car new) acc) (cdr new)))))))
+ (go (list) ls)))
+
+(should-be "reverse" (reverse (list 1 2 3)) (list 3 2 1))
+
+;; range
+(define range (Y2 (lambda (range) (lambda (from to)
+ (if (eq? from to)
+ (list to)
+ (cons from (range (+ 1 from) to)))))))
+
+(should-be "range" (range 1 5) (list 1 2 3 4 5))
+
+;; filter
+(define filter (Y2 (lambda (filter) (lambda (cond ls)
+ (if (empty? ls)
+ ls
+ (if (cond (car ls))
+ (cons (car ls) (filter cond (cdr ls)))
+ (filter cond (cdr ls))))))))
+
+(should-be "filter"
+ (filter (lambda (x) (< x 10)) (list 3 10 11))
+ (list 3))
+
+;; The Repl
+
+(define repl
+ (sorted-map name "repl" getter (quote (get-line!))))
+
+(subscribe-to! repl
+ (lambda (x) (print! x)))
diff --git a/src/Radicle.hs b/src/Radicle.hs
index 405c2a4..8c24c4e 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -41,6 +41,7 @@ module Radicle
, renderCompactPretty
-- ** Re-exports
, PageWidth(..)
+ , Pretty
-- * Repl
, repl
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index d4973d6..c4623c2 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -11,6 +11,7 @@ import Data.Generics (everywhereM)
import Data.List (foldl')
import Data.Map (Map)
import qualified Data.Map as Map
+import qualified Data.List.NonEmpty as NonEmpty
import Data.Scientific (Scientific)
import Data.Semigroup (Semigroup, (<>))
import Data.Text (Text)
@@ -49,11 +50,12 @@ data Value =
| SortedMap (Map.Map Ident Value)
-- | A variable that must be looked up at the *call-site*.
| Ref Ident
- -- | Since there are no side-effects, there is no point having a list of
- -- values for the body of a lambda.
+ -- | Takes the arguments/parameters, a body, and possibly a closure.
--
- -- Takes the arguments/parameters, a body, and possibly a closure.
- | Lambda [Ident] Value (Maybe Env)
+ -- The value of an application of a lambda is always the last value in the
+ -- body. The only reason to have multiple values is thus only for (local)
+ -- "define"s.
+ | Lambda [Ident] (NonEmpty.NonEmpty Value) (Maybe Env)
deriving (Eq, Ord, Show, Read, Generic, Data)
-- | An identifier in the language.
@@ -146,6 +148,22 @@ purePrimops = Map.fromList $ first Ident <$>
, ("quote", \args -> case args of
[v] -> pure v
xs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs))
+ , ("quasiquote", \args -> case args of
+ [x] -> do
+ let unquote :: forall b. (Data b) => (b -> Lang m b)
+ unquote e = case (cast e, eqT :: Maybe (b :~: Value)) of
+ (Just (Apply (Primop p) [y]), Just Refl) ->
+ if p == toIdent "unquote"
+ then eval y
+ else pure e
+ _ -> pure e
+ app <- everywhereM unquote x
+ pure $ case app of
+ Apply f vs -> List (f:vs)
+ _ -> app
+ {-[x] -> throwError $ OtherError $ T.pack $ show x-}
+ xs -> throwError $ WrongNumberOfArgs "quasiquote" 1 (length xs))
+ , ("unquote", \_ -> throwError $ OtherError "unquote: must be in quasiquote")
, ("define", \args -> case args of
[Atom name, val] -> do
val' <- eval val
@@ -161,26 +179,33 @@ purePrimops = Map.fromList $ first Ident <$>
[_, _] -> throwError $ TypeError "cons: second argument must be list"
xs -> throwError $ WrongNumberOfArgs "cons" 2 (length xs))
, ("car", evalArgs $ \args -> case args of
- [List (x:_)] -> eval x
+ [List (x:_)] -> pure x
[List []] -> throwError $ OtherError "car: empty list"
[_] -> throwError $ TypeError "car: expects list argument"
xs -> throwError $ WrongNumberOfArgs "car" 1 (length xs))
, ("cdr", evalArgs $ \args -> case args of
- [List (_:xs)] -> eval $ List xs
+ [List (_:xs)] -> pure $ List xs
[List []] -> throwError $ OtherError "cdr: empty list"
[_] -> throwError $ TypeError "cdr: expects list argument"
xs -> throwError $ WrongNumberOfArgs "cdr" 1 (length xs))
- , ("lookup", \args -> case args of
+ , ("lookup", evalArgs $ \args -> case args of
[Atom a, SortedMap m] -> case Map.lookup a m of
- Just v -> eval v
- -- Probably an exception is better, but that seems cruel when you
- -- have no exception handling facilities.
- Nothing -> pure nil
+ Just v -> eval v
+ -- Probably an exception is better, but that seems cruel
+ -- when you have no exception handling facilities.
+ Nothing -> pure nil
[Atom _, _] -> throwError
- $ TypeError "lookup: second argument must be map"
+ $ TypeError "lookup: second argument must be map"
[_, SortedMap _] -> throwError
$ TypeError "lookup: first argument must be atom"
xs -> throwError $ WrongNumberOfArgs "lookup" 2 (length xs))
+ , ("insert", evalArgs $ \args -> case args of
+ [Atom k, v, SortedMap m] -> pure . SortedMap $ Map.insert k v m
+ [Atom _, _, _] -> throwError
+ $ TypeError "insert: third argument must be map"
+ [_, _, _] -> throwError
+ $ TypeError "insert: first argument must be an atom"
+ xs -> throwError $ WrongNumberOfArgs "insert" 3 (length xs))
-- The semantics of + and - in Scheme is a little messed up. (+ 3)
-- evaluates to 3, and of (- 3) to -3. That's pretty intuitive.
-- But while (+ 3 2 1) evaluates to 6, (- 3 2 1) evaluates to 0. So with -
@@ -210,8 +235,8 @@ purePrimops = Map.fromList $ first Ident <$>
xs -> throwError $ WrongNumberOfArgs "foldr" 3 (length xs))
, ("map", \args -> case args of
[fn, List ls] -> List <$> traverse eval [fn $$ [l] | l <- ls]
- [_, _, _] -> throwError $ TypeError "foldr: third argument should be a list"
- xs -> throwError $ WrongNumberOfArgs "foldr" 3 (length xs))
+ [_, _, _] -> throwError $ TypeError "map: third argument should be a list"
+ xs -> throwError $ WrongNumberOfArgs "map" 3 (length xs))
, ("string?", evalArgs $ \args -> case args of
[String _] -> pure $ Boolean True
[_] -> pure $ Boolean False
@@ -280,7 +305,8 @@ eval val = do
Lambda [bnd] body (Just closure) -> do
let mappings = fromList [(bnd, val)]
modEnv = mappings <> closure
- withEnv (\e' -> e' { bindingsEnv = modEnv}) (eval body)
+ NonEmpty.last <$> withEnv (\e' -> e' { bindingsEnv = modEnv})
+ (traverse eval body)
_ -> throwError $ TypeError "Trying to apply a non-function"
-- | The built-in, original, eval.
@@ -300,13 +326,20 @@ baseEval val = case val of
-- Primops get to decide whether and how their args are
-- evaluated.
fn vs
- Lambda _ _ Nothing -> throwError $ Impossible
- "lambda should already have an env"
+ -- This happens if a quoted lambda is explicitly evaled. We then
+ -- give it the current environment
+ Lambda bnds body Nothing -> do
+ vs' <- traverse baseEval vs
+ let mappings = fromList (zip bnds vs')
+ NonEmpty.last <$> withEnv
+ (\e -> e { bindingsEnv = mappings <> bindingsEnv e })
+ (traverse baseEval body)
Lambda bnds body (Just closure) -> do
vs' <- traverse baseEval vs
let mappings = fromList (zip bnds vs')
modEnv = mappings <> closure
- withEnv (\e -> e { bindingsEnv = modEnv }) (baseEval body)
+ NonEmpty.last <$> withEnv (\e -> e { bindingsEnv = modEnv })
+ (traverse baseEval body)
_ -> throwError $ TypeError "Trying to apply a non-function"
Primop i -> pure $ Primop i
e@(Lambda _ _ (Just _)) -> pure e
diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hs
index 3689ef9..ba63b37 100644
--- a/src/Radicle/Internal/Parse.hs
+++ b/src/Radicle/Internal/Parse.hs
@@ -9,7 +9,7 @@ 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 Data.List.NonEmpty (NonEmpty((:|)), fromList)
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T
@@ -17,8 +17,8 @@ import Data.Void (Void)
import GHC.Exts (IsString(..))
import Text.Megaparsec (ParsecT, State(..), between, choice,
defaultTabWidth, eof, initialPos, manyTill,
- runParserT, runParserT', sepBy, sepBy1, try,
- (<?>))
+ runParserT, runParserT', sepBy, sepBy1, some,
+ try, (<?>))
import qualified Text.Megaparsec as M
import Text.Megaparsec.Char (char, satisfy, space1)
import qualified Text.Megaparsec.Char.Lexer as L
@@ -78,8 +78,11 @@ applyP = do
fn:args <- valueP `sepBy1` spaceConsumer
pure $ fn $$ args
+quoteP :: Parser Value
+quoteP = Apply (Primop $ toIdent "quote") . pure <$> (char '\'' >> valueP)
+
listP :: Parser Value
-listP = List <$> (char '\'' >> parensP (valueP `sepBy` spaceConsumer))
+listP = List <$> (symbol "list" >> (valueP `sepBy` spaceConsumer))
sortedMapP :: Parser Value
sortedMapP = do
@@ -92,7 +95,7 @@ lambdaP :: Parser Value
lambdaP = do
void $ symbol "lambda"
vars <- parensP $ identP `sepBy` spaceConsumer
- body <- valueP
+ body <- fromList <$> some valueP
pure $ Lambda vars body Nothing
refP :: Parser Value
@@ -107,7 +110,7 @@ valueP = do
, boolLiteralP <?> "boolean"
, try numLiteralP <?> "number"
, atomOrPrimP <?> "identifier"
- , listP <?> "list"
+ , quoteP <?> "quote"
, parensP appLike <?> "application"
]
spaceConsumer
@@ -117,6 +120,7 @@ valueP = do
[ lambdaP <?> "lambda"
, sortedMapP <?> "sorted-map"
, refP <?> "ref"
+ , listP <?> "list"
, applyP <?> "application"
]
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index ef83bd5..5bcd36b 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -1,6 +1,7 @@
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Radicle.Internal.Pretty where
+import Data.List.NonEmpty (toList)
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T
@@ -21,15 +22,15 @@ instance Pretty Value where
Number n -> pretty $ show n
Boolean True -> "#t"
Boolean False -> "#f"
- List vs -> "'" <> (parens . sep $ pretty <$> vs)
+ List vs -> parens $ sep ("list" : (pretty <$> vs))
Primop i -> pretty i
Apply fn vs -> parens $ pretty fn <+> sep (pretty <$> vs)
SortedMap mp -> parens $
"sorted-map" <+> sep [ pretty k <+> pretty val
| (k, val) <- Map.toList mp ]
- Lambda ids val _ -> parens $
+ Lambda ids vals _ -> parens $
"lambda" <+> parens (sep $ pretty <$> ids)
- <+> pretty val
+ <+> sep (pretty <$> toList vals)
where
escapeStr = T.replace "\"" "\\\"" . T.replace "\\" "\\\\"
@@ -51,8 +52,8 @@ instance Pretty LangError where
-- Examples:
--
-- >>> renderCompactPretty (List [String "hi", String "there"])
--- "'(\"hi\"\n\"there\")"
-renderCompactPretty :: Value -> Text
+-- "(list\n\"hi\"\n\"there\")"
+renderCompactPretty :: Pretty v => v -> Text
renderCompactPretty = renderStrict . layoutCompact . pretty
-- | Render prettily into text, with specified width.
@@ -60,11 +61,11 @@ renderCompactPretty = renderStrict . layoutCompact . pretty
-- Examples:
--
-- >>> renderPretty Unbounded (List [String "hi", String "there"])
--- "'(\"hi\" \"there\")"
+-- "(list \"hi\" \"there\")"
--
-- >>> renderPretty (AvailablePerLine 6 0.5) (List [String "hi", String "there"])
--- "'(\"hi\"\n\"there\")"
-renderPretty :: PageWidth -> Value -> Text
+-- "(list\n\"hi\"\n\"there\")"
+renderPretty :: Pretty v => PageWidth -> v -> Text
renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
-- | 'renderPretty', but with default layout options (80 chars, 1.0 ribbon)
@@ -72,6 +73,6 @@ renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
-- Examples:
--
-- >>> renderPrettyDef (List [String "hi", String "there"])
--- "'(\"hi\" \"there\")"
-renderPrettyDef :: Value -> Text
+-- "(list \"hi\" \"there\")"
+renderPrettyDef :: Pretty v => v -> Text
renderPrettyDef = renderStrict . layoutSmart defaultLayoutOptions . pretty
diff --git a/src/Radicle/Internal/Subscriber.hs b/src/Radicle/Internal/Subscriber.hs
index 6538c79..23c0094 100644
--- a/src/Radicle/Internal/Subscriber.hs
+++ b/src/Radicle/Internal/Subscriber.hs
@@ -47,7 +47,7 @@ completion = completeWord Nothing ['(', ')', ' ', '\n'] go
$ filter (s `isPrefixOf`)
$ fmap (T.unpack . fromIdent)
$ (Map.keys . fromEnv $ bindingsEnv bnds)
- <> (Map.keys $ bindingsPrimops bnds)
+ <> Map.keys (bindingsPrimops bnds)
replBindings :: forall m. ReplM m => Bindings m
replBindings = e { bindingsPrimops = bindingsPrimops e <> replPrimops }
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index 8ebf5cd..6ecf849 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -16,12 +16,12 @@ import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck (counterexample, testProperty, (==>))
+import Radicle
import Radicle.Internal.Arbitrary ()
import Radicle.Internal.Core (toIdent)
import Radicle.Internal.TestCapabilities
-import Radicle
-import Paths_radicle -- generated by cabal via 'data-files'
+import Paths_radicle
test_eval :: [TestTree]
test_eval =
@@ -40,18 +40,18 @@ test_eval =
prog `succeedsWith` SortedMap (fromList [(toIdent "why", String "not")])
, testCase "'cons' conses an element" $ do
- let prog = [s|(cons #t '(#f))|]
+ let prog = [s|(cons #t (list #f))|]
prog `succeedsWith` List [Boolean True, Boolean False]
, testCase "'car' returns the first element of a list" $ do
- let prog = [s|(car '(#t #f))|]
+ let prog = [s|(car (list #t #f))|]
prog `succeedsWith` Boolean True
, testCase "'cdr' returns the tail of a list" $ do
- let prog = [s|(cdr '(#t #f #t))|]
+ let prog = [s|(cdr (list #t #f #t))|]
prog `succeedsWith` List [Boolean False, Boolean True]
- , testProperty "'eq?' considers equal values equal" $ \val -> do
+ , testProperty "'eq?' considers equal values equal" $ \(val :: Value) -> do
let prog = [i|(eq? #{renderPrettyDef val} #{renderPrettyDef val})|]
res = runIdentity $ runLang pureEnv
$ interpretMany "(test)" $ T.pack prog
@@ -59,7 +59,7 @@ test_eval =
counterexample prog $ isLeft res || res == Right (Boolean True)
, testProperty "'eq?' considers different values different"
- $ \(v1, v2) ->
+ $ \(v1 :: Value, v2 :: Value) ->
v1 /= v2 ==> do
-- We quote the values to prevent errors from being thrown
let prog = [i|(eq? (quote #{renderPrettyDef v1})
@@ -70,27 +70,35 @@ test_eval =
counterexample prog $ isLeft res || res == Right (Boolean False)
, testCase "'member?' returns true if list contains element" $ do
- let prog = [s|(member? #t '(#f #t))|]
+ let prog = [s|(member? #t (list #f #t))|]
prog `succeedsWith` Boolean True
, testCase "'member?' returns false if list does not contain element" $ do
- let prog = [s|(member? "hi" '(#f #t))|]
+ let prog = [s|(member? "hi" (list #f #t))|]
prog `succeedsWith` Boolean False
, testCase "'lookup' returns value of key in map" $ do
- let prog = [s|(lookup key1 (sorted-map key1 "a" key2 "b"))|]
+ let prog = [s|(lookup 'key1 (sorted-map key1 "a" key2 "b"))|]
prog `succeedsWith` String "a"
+ , testCase "'insert' updates the value of key in map" $ do
+ let prog = [s|(lookup 'key1 (insert 'key1 "b" (sorted-map key1 "a" key2 "b")))|]
+ prog `succeedsWith` String "b"
+
+ , testCase "'insert' insert the value of key in map" $ do
+ let prog = [s|(lookup 'key1 (insert 'key1 "b" (sorted-map)))|]
+ prog `succeedsWith` String "b"
+
, testCase "'foldl' foldls the list" $ do
- let prog = [s|(foldl - 0 '(1 2 3))|]
+ let prog = [s|(foldl - 0 (list 1 2 3))|]
prog `succeedsWith` Number (-6)
, testCase "'foldr' foldrs the list" $ do
- let prog = [s|(foldr - 0 '(1 2 3))|]
+ let prog = [s|(foldr - 0 (list 1 2 3))|]
prog `succeedsWith` Number 2
, testCase "'map' maps over the list" $ do
- let prog = [s|(map (lambda (x) (+ x 1)) '(1 2))|]
+ let prog = [s|(map (lambda (x) (+ x 1)) (list 1 2))|]
prog `succeedsWith` List [Number 2, Number 3]
, testCase "'eval' evaluates the list" $ do
@@ -110,6 +118,14 @@ test_eval =
|]
prog `succeedsWith` String "a"
+ , testCase "lambdas allow local definitions" $ do
+ let prog = [s|
+ ((lambda ()
+ (define y 3)
+ y))
+ |]
+ prog `succeedsWith` Number 3
+
, testCase "'if' works with three arguments and true cond" $ do
let prog = [s|(if #t "a" "b")|]
prog `succeedsWith` String "a"
@@ -178,6 +194,21 @@ test_eval =
$ interpretMany "(test)" $ T.pack prog
counterexample prog $ res == Right (Boolean (x < y))
+ , testProperty "quasiquote . unquote == id" $ \(v :: Value) -> do
+ -- Parse errors will differ, so we ignore them.
+ let equalModuloParseErr x y = case (x, y) of
+ (Left (ParseError _) , Left (ParseError _)) -> True
+ _ -> x == y
+ prog1 = [i|(quasiquote (unquote #{renderPrettyDef v}))|]
+ prog2 = [i|#{renderPrettyDef v}|]
+ run' = runIdentity . runLang pureEnv
+ . interpretMany "(test)" . T.pack
+ l = run' prog1
+ r = run' prog2
+ info = "Left:\n" <> prettyEither l <>
+ "\nRight:\n" <> prettyEither r
+ counterexample (T.unpack info) $ l `equalModuloParseErr` r
+
, testCase "'define' fails when first arg is not an atom" $ do
let prog = [s|(define "hi" "there")|]
prog `failsWith` OtherError "define expects atom for first arg"
@@ -299,7 +330,7 @@ test_repl :: [TestTree]
test_repl =
[ testCase "evaluates correctly" $ do
let input = [ "((lambda (x) x) #t)" ]
- output = [ "'(#t)" ]
+ output = [ "(list #t)" ]
(_, result) <- runInRepl input
result @?= output
@@ -307,8 +338,8 @@ test_repl =
let input = [ "(define id (lambda (x) x))"
, "(id #t)"
]
- output = [ "'('())"
- , "'(#t)"
+ output = [ "(list (list))"
+ , "(list #t)"
]
(_, result) <- runInRepl input
result @?= output
@@ -317,7 +348,7 @@ test_repl =
let input = [ "(define eval (lambda (x) #t))"
, "#f"
]
- output = [ "'('())"
+ output = [ "(list (list))"
, "#t"
]
(_, result) <- runInRepl input
@@ -328,9 +359,9 @@ test_repl =
, "(define id (lambda (x) x))"
, "(id #t)"
]
- output = [ "'('())"
- , "'('())"
- , "'(#t)"
+ output = [ "(list (list))"
+ , "(list (list))"
+ , "(list #t)"
]
(_, result) <- runInRepl input
result @?= output
@@ -351,3 +382,8 @@ removeEnv = everywhere go
go x = case (cast x, eqT :: Maybe (b :~: Value)) of
(Just (Lambda arg body _), Just Refl) -> Lambda arg body Nothing
_ -> x
+
+prettyEither :: Either LangError Value -> T.Text
+prettyEither (Left e) = "Error: " <> renderPrettyDef e
+prettyEither (Right v) = renderPrettyDef v
+