A peer-to-peer stack for code collaboration
Add Number and more primops.
Julian K. Arni268b11af74fb
diff --git a/package.yaml b/package.yamlindex 88e9c7c..f64f604 100644--- a/package.yaml+++ b/package.yaml@@ -16,6 +16,7 @@ dependencies:- mmorph- mtl- prettyprinter+- scientific- syb- text@@ -36,6 +37,8 @@ tests:- radicle- QuickCheck- quickcheck-instances+ - interpolate+ - safe- string-qq- tasty- tasty-discoverdiff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex 86399eb..36ba175 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -1,5 +1,4 @@{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE TemplateHaskell #-}{-# LANGUAGE UndecidableInstances #-}module Radicle.Internal.Core where@@ -11,6 +10,7 @@ import Data.Data ((:~:)(Refl), Data, cast, eqT)import Data.Generics (everywhereM)import Data.Map (Map)import qualified Data.Map as Map+import Data.Scientific (Scientific)import Data.Semigroup (Semigroup, (<>))import Data.Text (Text)import Data.Void (Void)@@ -39,6 +39,7 @@ data Value =-- | A regular (hyperstatic) variable.Atom Ident| String Text+ | Number Scientific| Boolean Bool| List [Value]| Primop Ident@@ -135,8 +136,8 @@ defineAtom i v = modify $ addBinding i v-- | The universal primops. These are available in chain evaluation, and are-- not shadowable via 'define'.-purePrimops :: Monad m => Primops m-purePrimops = Map.fromList $ first toIdent <$>+purePrimops :: forall m. Monad m => Primops m+purePrimops = Map.fromList $ first Ident <$>[ ("base-eval", \args -> case args of[x] -> baseEval xxs -> throwError $ WrongNumberOfArgs "base-eval" 1 (length xs))@@ -150,14 +151,82 @@ purePrimops = Map.fromList $ first toIdent <$>pure nil[_, _] -> throwError $ OtherError "define expects atom for first arg"xs -> throwError $ WrongNumberOfArgs "define" 2 (length xs))- , ("string?", \args -> case args of+ , ("eq?", evalArgs $ \args -> case args of+ [a, b] -> fmap Boolean $ (==) <$> eval a <*> eval b+ xs -> throwError $ WrongNumberOfArgs "eq?" 2 (length xs))+ , ("cons", evalArgs $ \args -> case args of+ [x, List xs] -> pure $ List (x:xs)+ [_, _] -> 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 []] -> 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 []] -> throwError $ OtherError "cdr: empty list"+ [_] -> throwError $ TypeError "cdr: expects list argument"+ xs -> throwError $ WrongNumberOfArgs "cdr" 1 (length xs))+ , ("lookup", \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+ [Atom _, _] -> throwError+ $ TypeError "lookup: second argument must be map"+ [_, SortedMap _] -> throwError+ $ TypeError "lookup: first argument must be atom"+ xs -> throwError $ WrongNumberOfArgs "lookup" 2 (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 -+ -- it is *not* correct to say that it's a foldl (-) 0. Instead, it+ -- special-cases on one-argument application. (Similarly with * and /.)+ --+ -- In order to avoid this sort of thing, we don't allow +,*,- and / to be+ -- applied to a single argument.+ , numBinop (+) "+"+ , numBinop (*) "*"+ , numBinop (-) "-"+ , ("<", evalArgs $ \args -> case args of+ [Number x, Number y] -> return $ Boolean (x < y)+ [_, _] -> throwError $ TypeError "<: expecting number"+ xs -> throwError $ WrongNumberOfArgs "<" 2 (length xs))+ , (">", evalArgs $ \args -> case args of+ [Number x, Number y] -> return $ Boolean (x > y)+ [_, _] -> throwError $ TypeError ">: expecting number"+ xs -> throwError $ WrongNumberOfArgs ">" 2 (length xs))+ , ("foldl", evalArgs $ \args -> case args of+ [fn, init', List ls] -> eval $ foldl (\b a -> (fn $$) [b,a]) init' ls+ [_, _, _] -> throwError $ TypeError "foldl: third argument should be a list"+ xs -> throwError $ WrongNumberOfArgs "foldl" 3 (length xs))+ , ("foldr", evalArgs $ \args -> case args of+ [fn, init', List ls] -> eval $ foldr (\b a -> (fn $$) [b,a]) init' ls+ [_, _, _] -> throwError $ TypeError "foldr: third argument should be a list"+ 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))+ , ("string?", evalArgs $ \args -> case args of[String _] -> pure $ Boolean True[_] -> pure $ Boolean Falsexs -> throwError $ WrongNumberOfArgs "string?" 1 (length xs))- , ("boolean?", \args -> case args of+ , ("boolean?", evalArgs $ \args -> case args of[Boolean _] -> pure $ Boolean True[_] -> pure $ Boolean Falsexs -> throwError $ WrongNumberOfArgs "boolean?" 1 (length xs))+ , ("number?", evalArgs $ \args -> case args of+ [Number _] -> pure $ Boolean True+ [_] -> pure $ Boolean False+ xs -> throwError $ WrongNumberOfArgs "number?" 1 (length xs))+ , ("member?", evalArgs $ \args -> case args of+ [x, List xs] -> fmap Boolean $ elem <$> eval x <*> traverse eval xs+ [_, _] -> throwError+ $ TypeError "member?: second argument must be list"+ xs -> throwError $ WrongNumberOfArgs "eq?" 2 (length xs)), ("if", \args -> case args of[cond, t, f] -> dob <- eval cond@@ -166,7 +235,7 @@ purePrimops = Map.fromList $ first toIdent <$>if b == Boolean False then eval f else eval txs -> throwError $ WrongNumberOfArgs "if" 3 (length xs)), ("deref-all", \args -> do- let derefOne :: forall m b. (Monad m, Data b) => (b -> Lang m b)+ let derefOne :: forall b. (Data b) => (b -> Lang m b)derefOne x = case (cast x, eqT :: Maybe (b :~: Value)) of(Just (Ref i), Just Refl) -> lookupAtom i_ -> pure x@@ -174,6 +243,23 @@ purePrimops = Map.fromList $ first toIdent <$>[x] -> eval x >>= everywhereM derefOnexs -> throwError $ WrongNumberOfArgs "deref-all" 1 (length xs))]+ where+ -- Many primops evaluate their arguments just as normal functions do.+ evalArgs :: ([Value] -> Lang m Value) -> ([Value] -> Lang m Value)+ evalArgs f args = traverse eval args >>= f++ numBinop :: (Scientific -> Scientific -> Scientific)+ -> Text+ -> (Text, ([Value] -> Lang m Value))+ numBinop fn name = (name, evalArgs $ \args -> case args of+ Number x:x':xs -> foldM go (Number x) (x':xs)+ where+ go (Number a) (Number b) = return . Number $ fn a b+ go _ _ = throwError . TypeError+ $ name <> ": expecting number"+ [Number _] -> throwError+ $ OtherError $ name <> ": expects at least 2 arguments"+ _ -> throwError $ TypeError $ name <> ": expecting number")-- * Eval@@ -202,6 +288,7 @@ baseEval val = case val ofRef i -> pure $ Ref iList vals -> List <$> traverse baseEval valsString s -> pure $ String s+ Number n -> pure $ Number nBoolean b -> pure $ Boolean bApply mfn vs -> domfn' <- baseEval mfndiff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hsindex 5673c7b..3689ef9 100644--- a/src/Radicle/Internal/Parse.hs+++ b/src/Radicle/Internal/Parse.hs@@ -16,9 +16,9 @@ import qualified Data.Text as Timport Data.Void (Void)import GHC.Exts (IsString(..))import Text.Megaparsec (ParsecT, State(..), between, choice,- defaultTabWidth, initialPos, manyTill,- runParserT, runParserT', sepBy, sepBy1,- (<?>), eof)+ defaultTabWidth, eof, initialPos, manyTill,+ runParserT, runParserT', sepBy, sepBy1, try,+ (<?>))import qualified Text.Megaparsec as Mimport Text.Megaparsec.Char (char, satisfy, space1)import qualified Text.Megaparsec.Char.Lexer as L@@ -54,6 +54,13 @@ boolLiteralP :: Parser ValueboolLiteralP = lexeme $ Boolean <$> (char '#' >>(char 't' >> pure True) <|> (char 'f' >> pure False))+numLiteralP :: Parser Value+numLiteralP = Number <$> signed L.scientific+ where+ -- We don't allow spaces between the sign and digits so that we can remain+ -- consistent with the general Scheme of things.+ signed p = M.option id ((id <$ char '+') <|> (negate <$ char '-')) <*> p+identP :: Parser IdentidentP = lexeme $ dol <- satisfy isValidIdentFirst@@ -98,6 +105,7 @@ valueP = dov <- choice[ stringLiteralP <?> "string", boolLiteralP <?> "boolean"+ , try numLiteralP <?> "number", atomOrPrimP <?> "identifier", listP <?> "list", parensP appLike <?> "application"@@ -192,7 +200,8 @@ parseTest t = parse "(test)" t (Map.keys $ bindingsPrimops e)-- ** Valid identifiers-- These are made top-level so construction of arbitrary instances that matches--- parsing is easier+-- parsing is easier. Note that additionally an identifier must not be a valid+-- number (in parsing numbers are parsed first).-- | A predicate which returns true if the character is valid as the first-- character of an identifier.diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex 3dde914..d0a0511 100644--- a/src/Radicle/Internal/Pretty.hs+++ b/src/Radicle/Internal/Pretty.hs@@ -17,6 +17,7 @@ instance Pretty Value whereAtom i -> pretty iRef i -> parens $ "ref" <+> pretty iString t -> "\"" <> pretty (escapeStr t) <> "\""+ Number n -> pretty $ show nBoolean True -> "#t"Boolean False -> "#f"List vs -> "'" <> (parens . sep $ pretty <$> vs)diff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hsindex 0409592..0d0a29c 100644--- a/test/spec/Radicle/Internal/Arbitrary.hs+++ b/test/spec/Radicle/Internal/Arbitrary.hs@@ -1,16 +1,19 @@{-# OPTIONS_GHC -fno-warn-orphans #-}module Radicle.Internal.Arbitrary where-import Control.Monad.Identity (Identity)-import Data.Bifunctor (first)-import qualified Data.Map as Map-import qualified Data.Text as T+import Control.Monad.Identity (Identity)+import Data.Bifunctor (first)+import qualified Data.Map as Map+import Data.Maybe (isJust)+import Data.Scientific (Scientific)+import qualified Data.Text as T+import Safe (readMay)import Test.QuickCheckimport Test.QuickCheck.Instances ()import Radicle-import Radicle.Internal.Core (purePrimops)-import Radicle.Internal.Parse (isValidIdentFirst, isValidIdentRest)+import Radicle.Internal.Core (purePrimops)+import Radicle.Internal.Parse (isValidIdentFirst, isValidIdentRest)instance Arbitrary Env wherearbitrary = Env <$> arbitrary@@ -18,10 +21,11 @@ instance Arbitrary Env whereinstance Arbitrary Value wherearbitrary = sized gowhere- freqs = [ (3, Atom <$> arbitrary)+ freqs = [ (3, Atom <$> (arbitrary `suchThat` (\x -> not (isPrimop x || isNum x)))), (3, Ref <$> arbitrary), (3, String <$> arbitrary), (3, Boolean <$> arbitrary)+ , (3, Number <$> arbitrary), (1, List <$> sizedList), (3, Primop <$> elements (Map.keys prims)), (1, Apply <$> scale (`div` 2) arbitrary <*> sizedList)@@ -38,6 +42,10 @@ instance Arbitrary Value wherescale (`div` (k + 1)) $ vectorOf k arbitraryprims :: Map.Map Ident ([Value] -> Lang Identity Value)prims = purePrimops+ isPrimop x = x `elem` Map.keys prims+ isNum x = isJust (readMay (T.unpack $ fromIdent x) :: Maybe Scientific)++ shrink x = genericShrink xinstance Arbitrary Ident wherearbitrary = ((:) <$> firstL <*> rest) `suchThatMap` (mkIdent . T.pack)diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 061d350..a3daaff 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -3,16 +3,18 @@module Radicle.Tests whereimport Data.Data ((:~:)(Refl), Data, cast, eqT)+import Data.Either (isLeft)import Data.Functor.Identity (runIdentity)import Data.Generics (everywhere)import Data.Semigroup ((<>))+import Data.String.Interpolate (i)import Data.String.QQ (s)import qualified Data.Text as Timport qualified Data.Text.IO as Timport GHC.Exts (fromList, toList)import Test.Tastyimport Test.Tasty.HUnit-import Test.Tasty.QuickCheck (counterexample, testProperty)+import Test.Tasty.QuickCheck (counterexample, testProperty, (==>))import Radicle.Internal.Arbitrary ()import Radicle.Internal.Core (toIdent)@@ -37,6 +39,60 @@ test_eval =let prog = [s|(sorted-map why "not")|]prog `succeedsWith` SortedMap (fromList [(toIdent "why", String "not")])+ , testCase "'cons' conses an element" $ do+ let prog = [s|(cons #t '(#f))|]+ prog `succeedsWith` List [Boolean True, Boolean False]++ , testCase "'car' returns the first element of a list" $ do+ let prog = [s|(car '(#t #f))|]+ prog `succeedsWith` Boolean True++ , testCase "'cdr' returns the tail of a list" $ do+ let prog = [s|(cdr '(#t #f #t))|]+ prog `succeedsWith` List [Boolean False, Boolean True]++ , testProperty "'eq?' considers equal values equal" $ \val -> do+ let prog = [i|(eq? #{renderPrettyDef val} #{renderPrettyDef val})|]+ res = runIdentity $ runLang pureEnv+ $ interpretMany "(test)" $ T.pack prog+ -- Either evaluation failed or their equal.+ counterexample prog $ isLeft res || res == Right (Boolean True)++ , testProperty "'eq?' considers different values different"+ $ \(v1, v2) ->+ v1 /= v2 ==> do+ -- We quote the values to prevent errors from being thrown+ let prog = [i|(eq? (quote #{renderPrettyDef v1})+ (quote #{renderPrettyDef v2}))|]+ res = runIdentity $ runLang pureEnv+ $ interpretMany "(test)" $ T.pack prog+ -- Either evaluation failed or their equal.+ counterexample prog $ isLeft res || res == Right (Boolean False)++ , testCase "'member?' returns true if list contains element" $ do+ let prog = [s|(member? #t '(#f #t))|]+ prog `succeedsWith` Boolean True++ , testCase "'member?' returns false if list does not contain element" $ do+ let prog = [s|(member? "hi" '(#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"))|]+ prog `succeedsWith` String "a"++ , testCase "'foldl' foldls the list" $ do+ let prog = [s|(foldl - 0 '(1 2 3))|]+ prog `succeedsWith` Number (-6)++ , testCase "'foldr' foldrs the list" $ do+ let prog = [s|(foldr - 0 '(1 2 3))|]+ prog `succeedsWith` Number 2++ , testCase "'map' maps over the list" $ do+ let prog = [s|(map (lambda (x) (+ x 1)) '(1 2))|]+ prog `succeedsWith` List [Number 2, Number 3]+, testCase "'eval' evaluates the list" $ dolet prog = [s|(eval (quote #t))|]prog `succeedsWith` Boolean True@@ -82,10 +138,42 @@ test_eval =let prog = [s|(boolean? #t)|]prog `succeedsWith` Boolean True- , testCase "'boolean?' is true for non-booleans" $ do+ , testCase "'boolean?' is false for non-booleans" $ dolet prog = [s|(boolean? "hi")|]prog `succeedsWith` Boolean False+ , testCase "'number?' is true for numbers" $ do+ let prog = [s|(number? 200)|]+ prog `succeedsWith` Boolean True++ , testCase "'number?' is false for non-numbers" $ do+ let prog = [s|(number? #t)|]+ prog `succeedsWith` Boolean False++ , testCase "'+' sums the list of numbers" $ do+ let prog = [s|(+ 2 (+ 2 3))|]+ prog `succeedsWith` Number 7++ , testCase "'-' subtracts the list of numbers" $ do+ let prog2 = [s|(- (+ 2 3) 1)|]+ prog2 `succeedsWith` Number 4++ , testCase "'*' multiplies the list of numbers" $ do+ let prog = [s|(* 2 3)|]+ prog `succeedsWith` Number 6++ , testProperty "'>' works" $ \(x, y) -> do+ let prog = [i|(> #{renderPrettyDef $ Number x} #{renderPrettyDef $ Number y})|]+ res = runIdentity $ runLang pureEnv+ $ interpretMany "(test)" $ T.pack prog+ counterexample prog $ res == Right (Boolean (x > y))++ , testProperty "'<' works" $ \(x, y) -> do+ let prog = [i|(< #{renderPrettyDef $ Number x} #{renderPrettyDef $ Number y})|]+ res = runIdentity $ runLang pureEnv+ $ interpretMany "(test)" $ T.pack prog+ counterexample prog $ res == Right (Boolean (x < y))+, testCase "'define' fails when first arg is not an atom" $ dolet prog = [s|(define "hi" "there")|]prog `failsWith` OtherError "define expects atom for first arg"@@ -106,37 +194,52 @@ test_eval =test_parser :: [TestTree]test_parser =[ testCase "parses strings" $ do- "\"hi\"" ==> String "hi"+ "\"hi\"" ~~> String "hi", testCase "parses booleans" $ do- "#t" ==> Boolean True- "#f" ==> Boolean False+ "#t" ~~> Boolean True+ "#f" ~~> Boolean False, testCase "parses primops" $ do- "boolean?" ==> Primop (toIdent "boolean?")- "base-eval" ==> Primop (toIdent "base-eval")+ "boolean?" ~~> Primop (toIdent "boolean?")+ "base-eval" ~~> Primop (toIdent "base-eval")++ , testCase "parses identifiers" $ do+ "++" ~~> Atom (toIdent "++")+ "what?crazy!" ~~> Atom (toIdent "what?crazy!")++ , testCase "parses identifiers that have a primop as prefix" $ do+ "evaluate" ~~> Atom (toIdent "evaluate")++ , testCase "parses function application" $ do+ "(++)" ~~> (Atom (toIdent "++") $$ [])+ "(++ \"merge\" \"d\")" ~~> (Atom (toIdent "++") $$ [String "merge", String "d"])++ , testCase "parses number" $ do+ "0.15" ~~> Number 0.15+ "2000" ~~> Number 2000, testCase "parses identifiers" $ do- "++" ==> Atom (toIdent "++")- "what?crazy!" ==> Atom (toIdent "what?crazy!")+ "++" ~~> Atom (toIdent "++")+ "what?crazy!" ~~> Atom (toIdent "what?crazy!"), testCase "parses identifiers that have a primop as prefix" $ do- "evaluate" ==> Atom (toIdent "evaluate")+ "evaluate" ~~> Atom (toIdent "evaluate"), testCase "parses function application" $ do- "(++)" ==> (Atom (toIdent "++") $$ [])- "(++ \"merge\" \"d\")" ==> (Atom (toIdent "++") $$ [String "merge", String "d"])+ "(++)" ~~> (Atom (toIdent "++") $$ [])+ "(++ \"merge\" \"d\")" ~~> (Atom (toIdent "++") $$ [String "merge", String "d"])]where- x ==> y = parseTest x @?= Right y+ x ~~> y = parseTest x @?= Right ytest_binding :: [TestTree]test_binding =[ testCase "handles shadowing correctly" $ do- [s|(((lambda (x) (lambda (x) x)) "inner") "outer")|] ==> String "outer"+ [s|(((lambda (x) (lambda (x) x)) "inner") "outer")|] ~~> String "outer"]where- x ==> y = runIdentity (interpret "test" x pureEnv) @?= Right y+ x ~~> y = runIdentity (interpret "test" x pureEnv) @?= Right ytest_pretty :: [TestTree]