A peer-to-peer stack for code collaboration
Better error messages (#243)
James Haydon04ce4d6330f4
diff --git a/exe/RadicleExe.hs b/exe/RadicleExe.hsindex dbb2602..c5a4e67 100644--- a/exe/RadicleExe.hs+++ b/exe/RadicleExe.hs@@ -96,23 +96,22 @@ clientPrimFns mgr = fromList . PrimFns.allDocs $ [sendPrimop, receivePrimop]( "send!", "Given a URL (string) and a value, sends the value `v` to the remote\\ chain located at the URL for evaluation."- , \case- [String url, Vec v] -> do+ , PrimFns.twoArg "send!" $ \case+ (String url, Vec v) -> dores <- liftIO $ runClientM' url mgr (submit $ toList v)case res ofLeft e -> throwErrorHere . OtherError$ "send!: failed:" <> show eRight r -> pure r- [_, Vec _] -> throwErrorHere $ TypeError "send!: first argument should be a string"- [String _, _] -> throwErrorHere $ TypeError "send!: second argument should be a vector"- xs -> throwErrorHere $ WrongNumberOfArgs "send!" 2 (length xs)+ (String _, v) -> throwErrorHere $ TypeError "send!" 1 TVec v+ (v, _) -> throwErrorHere $ TypeError "send!" 0 TString v)receivePrimop =( "receive!", "Given a URL (string) and a integral number `n`, queries the remote chain\\ for the last `n` inputs that have been evaluated."- , \case- [String url, Number n] -> do+ , PrimFns.twoArg "receive!" $ \case+ (String url, Number n) -> docase Num.isInt n ofLeft _ -> throwErrorHere . OtherError$ "receive!: expecting int argument"@@ -121,9 +120,8 @@ clientPrimFns mgr = fromList . PrimFns.allDocs $ [sendPrimop, receivePrimop]Left err -> throwErrorHere . OtherError$ "receive!: request failed:" <> show errRight v' -> pure v'- [String _, _] -> throwErrorHere $ TypeError "receive!: expecting number as second arg"- [_, _] -> throwErrorHere $ TypeError "receive!: expecting string as first arg"- xs -> throwErrorHere $ WrongNumberOfArgs "receive!" 2 (length xs)+ (String _, v) -> throwErrorHere $ TypeError "receive!" 1 TNumber v+ (v, _) -> throwErrorHere $ TypeError "receive!" 0 TString v)-- * Client functionsdiff --git a/src/Radicle.hs b/src/Radicle.hsindex 7d08c83..ac1cdb0 100644--- a/src/Radicle.hs+++ b/src/Radicle.hs@@ -23,6 +23,7 @@ module Radicle-- *** Value, ValueF(..), type Value+ , Type(..), pattern Atom, pattern Keyword, pattern Stringdiff --git a/src/Radicle/Internal.hs b/src/Radicle/Internal.hsindex 014b0dd..3d1ea11 100644--- a/src/Radicle/Internal.hs+++ b/src/Radicle/Internal.hs@@ -20,6 +20,7 @@ import Radicle.Internal.Interpret as Ximport Radicle.Internal.Parse as Ximport Radicle.Internal.Pretty as Ximport Radicle.Internal.PrimFns as X+import Radicle.Internal.Type as Ximport qualified Text.Megaparsec as Mdiff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex d0ed0c6..79db4cc 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -34,6 +34,8 @@ import qualified Radicle.Internal.Doc as Docimport qualified Radicle.Internal.Identifier as Identifierimport qualified Radicle.Internal.Number as Numimport Radicle.Internal.Orphans ()+import Radicle.Internal.Type (Type(..))+import qualified Radicle.Internal.Type as Type-- * Value@@ -51,11 +53,16 @@ data PatternMatchErrorinstance Serialise PatternMatchError--- | An error throw during parsing or evaluating expressions in the language.+-- | An error thrown during parsing or evaluating expressions in the language.data LangErrorData r =UnknownIdentifier Ident| Impossible Text- | TypeError Text+ -- | The special form that was misused, and information on the misuse.+ | SpecialForm Text Text+ | NonFunctionCalled Value+ -- | Takes a function description, a argument position, an expected type and+ -- the value which wasn't of that type.+ | TypeError Text Int Type.Type Value-- | Takes the function name, expected number of args, and actual number of-- args| WrongNumberOfArgs Text Int Int@@ -80,6 +87,9 @@ noStack :: Either (LangError Value) a -> Either (LangErrorData Value) anoStack (Left (LangError _ err)) = Left errnoStack (Right v) = Right v+typeToValue :: Type.Type -> Value+typeToValue = Keyword . Ident . Identifier.kebabCons . drop 1 . show+-- | Convert an error to a radicle value, and the label for it. Used for-- catching exceptions.errorDataToValue@@ -93,10 +103,22 @@ errorDataToValue e = case e of)-- "Now more than ever seems it rich to die"Impossible _ -> throwErrorHere e- TypeError i -> makeVal+ TypeError fname pos ty v -> makeVal( "type-error"- , [("info", String i)]+ , [ ("function", makeA $ Ident fname)+ , ("position", Number (fromIntegral pos))+ , ("expected-type", typeToValue ty)+ , ("actual-type", typeToValue (valType v))+ , ("value", v)+ ])+ NonFunctionCalled v -> makeVal+ ( "non-function-called"+ , [("value", v)])+ SpecialForm form info -> makeVal+ ( "special-form-error"+ , [ ("special-form", makeA $ Ident form)+ , ("info", String info)])WrongNumberOfArgs i expected actual -> makeVal( "wrong-number-of-args", [ ("function", makeA $ Ident i)@@ -165,6 +187,20 @@ data ValueF r =instance Serialise r => Serialise (ValueF r)+valType :: (CPA t) => Annotated t ValueF -> Type.Type+valType = \case+ Atom _ -> TAtom+ Keyword _ -> TKeyword+ String _ -> TString+ Number _ -> TNumber+ Boolean _ -> TBoolean+ List _ -> TList+ Vec _ -> TVec+ PrimFn _ -> TFunction+ Dict _ -> TDict+ Ref _ -> TRef+ Lambda{} -> TFunction+hashable :: (CPA t) => Annotated t ValueF -> Boolhashable = \caseAtom _ -> True@@ -465,11 +501,11 @@ specialForms = Map.fromList $ first Ident <$>args : b : bs ->case args ofVec atoms_ -> do- atoms <- traverse isAtom (toList atoms_) ?? toLangError (TypeError "fn: expecting a list of symbols")+ atoms <- traverse isAtom (toList atoms_) ?? toLangError (SpecialForm "fn" "One of the arguments was not an atom")e <- gets bindingsEnvpure (Lambda atoms (b :| bs) e)- _ -> throwErrorHere $ OtherError "fn: first argument must be a vector of argument symbols, and then at least one form for the body"- xs -> throwErrorHere $ WrongNumberOfArgs "fn" 2 (length xs) -- TODO: technically "at least 2"+ _ -> throwErrorHere $ SpecialForm "fn" "First argument must be a vector of argument atoms"+ _ -> throwErrorHere $ SpecialForm "fn" "Need an argument vector and a body"), ("quote", \case[v] -> pure v@@ -498,7 +534,7 @@ specialForms = Map.fromList $ first Ident <$>if thrownLabel == label || label == Ident "any"then handlerclo $$ [thrownValue]else baseEval form- _ -> throwErrorHere $ TypeError "catch: first argument must be atom"+ _ -> throwErrorHere $ SpecialForm "catch" "first argument must be atom"xs -> throwErrorHere $ WrongNumberOfArgs "catch" 3 (length xs)), ("if", \case[condition, t, f] -> do@@ -689,7 +725,7 @@ callFn f vs = case f ofPrimFn i -> dofn <- lookupPrimop ifn vs- _ -> throwErrorHere . TypeError $ "Trying to call a non-function"+ _ -> throwErrorHere $ NonFunctionCalled f-- | Infix evaluation of application (of functions or special forms)infixr 1 $$diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hsindex 747e116..8b2099e 100644--- a/src/Radicle/Internal/Effects.hs+++ b/src/Radicle/Internal/Effects.hs@@ -27,6 +27,7 @@ import Radicle.Internal.Effects.Capabilitiesimport Radicle.Internal.Interpretimport Radicle.Internal.Prettyimport Radicle.Internal.PrimFns+import Radicle.Internal.Type (Type(..))import qualified Radicle.Internal.UUID as UUIDtype ReplM m =@@ -93,7 +94,7 @@ replPrimFns = fromList $ allDocs $d <- lookupAtomDoc iputStrS $ fromMaybe "No docs." dpure nil- _ -> throwErrorHere $ TypeError "doc!: expects an atom"+ v -> throwErrorHere $ TypeError "doc!" 0 TAtom v), ( "apropos!"@@ -114,7 +115,7 @@ replPrimFns = fromList $ allDocs $[Atom x, v] -> dodefineAtom x Nothing vpure nil- [_, _] -> throwErrorHere $ TypeError "Expected atom as first arg"+ [v, _] -> throwErrorHere $ TypeError "set-env!" 0 TAtom vxs -> throwErrorHere $ WrongNumberOfArgs "set-env!" 2 (length xs)), ( "get-line!"@@ -159,7 +160,7 @@ replPrimFns = fromList $ allDocs $-- function is evaluated in the original-- environment.void $ withEnv (const e) (fn $$ [quote line])- _ -> throwErrorHere $ TypeError "subscribe-to!: Expected dict"+ _ -> throwErrorHere $ TypeError "subscribe-to!" 0 TDict xxs -> throwErrorHere $ WrongNumberOfArgs "subscribe-to!" 2 (length xs)), ( "read-file!", "Reads the contents of a file and returns it as a string."@@ -167,7 +168,7 @@ replPrimFns = fromList $ allDocs $String filename -> readFileS filename >>= \caseLeft err -> throwErrorHere . OtherError $ "Error reading file: " <> errRight text -> pure $ String text- _ -> throwErrorHere $ TypeError "read-file: expects a string"+ v -> throwErrorHere $ TypeError "read-file!" 0 TString v), ( "load!", "Evaluates the contents of a file. Each seperate radicle expression is\@@ -176,7 +177,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"+ v -> throwErrorHere $ TypeError "load!" 0 TString v), ( "gen-key-pair!", "Given an elliptic curve, generates a cryptographic key-pair. Use\@@ -195,11 +196,11 @@ replPrimFns = fromList $ allDocs $, ( "gen-signature!", "Given a private key and a message (a string), generates a cryptographic\\ signature for the message."- , \case- [skv, String msg] -> do+ , twoArg "gen-signature!" $ \case+ (skv, String msg) -> dosk <- hoistEither . first (toLangError . OtherError) $ fromRad skvtoRad <$> signText sk msg- _ -> throwErrorHere $ TypeError "gen-signature!: expects a string."+ (_, v) -> throwErrorHere $ TypeError "gen-signature!" 1 TString v), ( "uuid!", "Generates a random UUID."diff --git a/src/Radicle/Internal/Interpret.hs b/src/Radicle/Internal/Interpret.hsindex b6b483f..a95c8c4 100644--- a/src/Radicle/Internal/Interpret.hs+++ b/src/Radicle/Internal/Interpret.hs@@ -18,8 +18,8 @@ import Radicle.Internal.Parse-- Right (Annotated (Identity (BooleanF True)))---- >>> import Control.Monad.Identity--- >>> noStack . runIdentity $ interpret "test" "(#t #f)" pureEnv--- Left (TypeError "Trying to call a non-function")+-- >>> case noStack . runIdentity $ interpret "test" "(#t #f)" pureEnv of { Left (NonFunctionCalled v) -> Ann.untag v }+-- Annotated (Identity (BooleanF True))interpret:: Monad m=> Text -- ^ Name of source file (for error reporting)diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex 91b8f9d..af2027a 100644--- a/src/Radicle/Internal/Pretty.hs+++ b/src/Radicle/Internal/Pretty.hs@@ -1,7 +1,8 @@{-# OPTIONS_GHC -fno-warn-orphans #-}+module Radicle.Internal.Pretty where-import Protolude hiding (TypeError, (<>))+import Protolude hiding (Type, TypeError, (<>))import Data.Copointed (Copointed(..))import qualified Data.Map as Map@@ -14,6 +15,7 @@ import Text.Megaparsec.Pos (sourcePosPretty)import qualified Radicle.Internal.Annotation as Annimport Radicle.Internal.Core+import Radicle.Internal.Type-- | We can't just pretty print the pointer id since that would break-- referential transparency, so instead we just label refs as '<ref>'@@ -23,6 +25,9 @@ instance Pretty Reference whereinstance Pretty Ident wherepretty (Ident i) = pretty i+instance Pretty Type where+ pretty = pretty . typeToValue+instance (Copointed t, Ann.Annotation t) => Pretty (Ann.Annotated t ValueF) wherepretty v = case v ofAtom i -> pretty i@@ -65,12 +70,20 @@ instance Pretty r => Pretty (LangErrorData r) wherepretty v = case v ofUnknownIdentifier i -> "Unknown identifier:" <+> pretty iImpossible t -> "This cannot be!" <+> pretty t- TypeError t -> "Type error:" <+> pretty t+ TypeError fname i t val -> vsep+ [ "Type error:" <+> pretty fname <+> "expects a value of type"+ <+> pretty t <+> "in the" <+> pretty (pos (i + 1)) <+> "argument."+ , "But got a" <+> pretty (valType val) <> ":"+ , indent 2 $ pretty val ]+ NonFunctionCalled val -> vsep+ [ "Value was invoked as a function, but it has type" <+> pretty (valType val) <> ":"+ , indent 2 $ pretty val ]WrongNumberOfArgs t x y -> "Wrong number of args in" <+> pretty t<+> "Expected:" <+> pretty x<+> "Got:" <+> pretty yNonHashableKey -> "Non-hashable key in dict."OtherError t -> "Error:" <+> pretty t+ SpecialForm f t -> "Error using special form" <+> pretty f <> ":" <+> pretty t <> "."ParseError t -> "Parser error:" <+> pretty (parseErrorPretty t)Exit -> "Exit"ThrownError i val -> "Exception" <+> pretty i <+> pretty val@@ -80,6 +93,12 @@ instance Pretty r => Pretty (LangErrorData r) whereBadBindings p -> "Faulty pattern function. Pattern functions must return\\ `[:just b]` where `b` is a dict of new bindings (from\\ atoms to values), or `:nothing`:" <+> pretty p+ where+ pos :: Int -> Text+ pos 1 = "1st"+ pos 2 = "2nd"+ pos 3 = "3rd"+ pos n = show n <> "th"-- | A fast and compact layout. Primarily intended for testing.diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hsindex 551f0e1..b02f398 100644--- a/src/Radicle/Internal/PrimFns.hs+++ b/src/Radicle/Internal/PrimFns.hs@@ -4,6 +4,7 @@ import Protolude hiding (TypeError)import qualified Data.Aeson as Aesonimport qualified Data.IntMap as IntMap+import Data.List (zip3)import qualified Data.Map as Mapimport Data.Sequence (Seq(..))import qualified Data.Sequence as Seq@@ -18,6 +19,7 @@ import qualified Radicle.Internal.Doc as Docimport qualified Radicle.Internal.Number as Numimport Radicle.Internal.Parseimport Radicle.Internal.Pretty+import Radicle.Internal.Type (Type(..))import qualified Radicle.Internal.UUID as UUID-- | A Bindings with an Env containing only 'eval' and only pure primops.@@ -77,19 +79,19 @@ purePrimFns = fromList $ allDocs $\ elements of the the second argument (a list).", \case[fn, List args] -> callFn fn args- [_, _] -> throwErrorHere $ TypeError "apply: expecting list as second arg"+ [_, v] -> throwErrorHere $ TypeError "apply" 1 TList vxs -> throwErrorHere $ WrongNumberOfArgs "apply" 2 (length xs)), ( "read", "Parses a string into a radicle value. Does not evaluate the value.", oneArg "read" $ \caseString s -> readValue s- _ -> throwErrorHere $ TypeError "read: expects string"+ v -> throwErrorHere $ TypeError "read" 0 TString v), ( "read-many", "Parses a string into a vector of radicle values. Does not evaluate the values.", oneArg "read-many" $ \caseString s -> readValues s- _ -> throwErrorHere $ TypeError "read-many: expects string"+ v -> throwErrorHere $ TypeError "read-many" 0 TString v), ("get-current-env", "Returns the current radicle state."@@ -121,7 +123,7 @@ purePrimFns = fromList $ allDocs $\ the exception, the second can be any value.", \case[Atom label, exc] -> throwErrorHere $ ThrownError label exc- [_, _] -> throwErrorHere $ TypeError "throw: first argument must be atom"+ [v, _] -> throwErrorHere $ TypeError "throw" 0 TAtom vxs -> throwErrorHere $ WrongNumberOfArgs "throw" 2 (length xs)), ( "eq?", "Checks if two values are equal."@@ -134,13 +136,13 @@ purePrimFns = fromList $ allDocs $, "Adds an element to the left side of a vector.", twoArg "add-left" $ \case(x, Vec xs) -> pure $ Vec (x :<| xs)- _ -> throwErrorHere $ TypeError "add-left: second argument must be a vector"+ (_, v) -> throwErrorHere $ TypeError "add-left" 1 TVec v), ( "add-right", "Adds an element to the right side of a vector.", twoArg "add-right" $ \case(x, Vec xs) -> pure $ Vec (xs :|> x)- _ -> throwErrorHere $ TypeError "add-right: second argument must be a vector"+ (_, v) -> throwErrorHere $ TypeError "add-right" 1 TVec v)-- Lists@@ -148,7 +150,7 @@ purePrimFns = fromList $ allDocs $, "Adds an element to the front of a list.", \case[x, List xs] -> pure $ List (x:xs)- [_, _] -> throwErrorHere $ TypeError "cons: second argument must be list"+ [_, v] -> throwErrorHere $ TypeError "cons" 1 TList vxs -> throwErrorHere $ WrongNumberOfArgs "cons" 2 (length xs)), ("head", "Retrieves the first element of a sequence if it exists. Otherwise throws an\@@ -158,7 +160,7 @@ purePrimFns = fromList $ allDocs $List [] -> throwErrorHere $ OtherError "head: empty list"Vec (x Seq.:<| _) -> pure xVec Seq.Empty -> throwErrorHere $ OtherError "head: empty vector"- _ -> throwErrorHere $ TypeError "head: expects sequence argument")+ v -> throwErrorHere $ TypeError "head" 0 TSequence v), ("tail", "Given a non-empty sequence, returns the sequence of all the elements but the\\ first. If the sequence is empty, throws an exception."@@ -167,7 +169,7 @@ purePrimFns = fromList $ allDocs $List [] -> throwErrorHere $ OtherError "tail: empty list"Vec (_ Seq.:<| xs) -> pure $ Vec xsVec Seq.Empty -> throwErrorHere $ OtherError "tail: empty vector"- _ -> throwErrorHere $ TypeError "tail: expects sequence argument")+ v -> throwErrorHere $ TypeError "tail" 0 TSequence v)-- Lists and Vecs, ( "drop"@@ -178,9 +180,9 @@ purePrimFns = fromList $ allDocs $Left _ -> throwErrorHere $ OtherError "drop: first argument must be an int"Right i -> case vs ofList xs -> pure . List $ drop i xs- Vec xs -> pure . Vec $ Seq.drop i xs- _ -> throwErrorHere $ TypeError $ "drop: second argument must be a list of vector"- _ -> throwErrorHere $ TypeError $ "drop: first argument must be a number"+ Vec xs -> pure . Vec $ Seq.drop i xs+ v -> throwErrorHere $ TypeError "drop" 1 TSequence v+ (v, _) -> throwErrorHere $ TypeError "drop" 0 TNumber v), ( "take", "Returns the first `n` items of a sequence, unless the sequence is too short,\@@ -190,9 +192,9 @@ purePrimFns = fromList $ allDocs $Left _ -> throwErrorHere $ OtherError "take: first argument must be an integer"Right i -> case vs ofList xs -> pure . List $ take i xs- Vec xs -> pure . Vec $ Seq.take i xs- _ -> throwErrorHere $ TypeError $ "take: second argument must be a list of vector"- _ -> throwErrorHere $ TypeError $ "take: first argument must be a number"+ Vec xs -> pure . Vec $ Seq.take i xs+ _ -> throwErrorHere $ TypeError "take" 1 TSequence vs+ (v, _) -> throwErrorHere $ TypeError "take" 0 TNumber v), ( "nth", "Given an integral number `n` and `xs`, returns the `n`th element\@@ -207,7 +209,7 @@ purePrimFns = fromList $ allDocs $case xs `atMay` i ofJust x -> pure xNothing -> throwErrorHere $ OtherError "nth: index out of bounds"- [_,_] -> throwErrorHere $ TypeError "nth: expects a integer and a list or vector"+ [v,_] -> throwErrorHere $ TypeError "nth" 0 TNumber vxs -> throwErrorHere $ WrongNumberOfArgs "nth" 2 (length xs)), ( "sort-by"@@ -220,7 +222,7 @@ purePrimFns = fromList $ allDocs $(f, Vec xs) -> do ys <- traverse (\x -> (x,) <$> callFn f [x]) xslet ys' = Seq.sortOn snd yspure (Vec (fst <$> ys'))- _ -> throwErrorHere $ TypeError "sort-by: second argument must be a sequence"+ (_, v) -> throwErrorHere $ TypeError "sort-by" 1 TSequence v), ( "zip", "Takes two sequences and returns a sequence of corresponding pairs. In one\@@ -229,7 +231,9 @@ purePrimFns = fromList $ allDocs $, twoArg "zip" $ \case(Vec xs, Vec ys) -> pure $ Vec (pair <$> Seq.zip xs ys)(List xs, List ys) -> pure $ List (pair <$> zip xs ys)- _ -> throwErrorHere $ TypeError "zip: only works on vectors or lists"+ (List _, v) -> throwErrorHere $ TypeError "zip" 1 TList v+ (Vec _, v) -> throwErrorHere $ TypeError "zip" 1 TList v+ (v, _) -> throwErrorHere $ TypeError "zip" 0 TSequence v)-- Dicts@@ -241,7 +245,7 @@ purePrimFns = fromList $ allDocs $[a, Dict m] -> case Map.lookup a m ofJust v -> pure vNothing -> throwErrorHere $ OtherError $ "lookup: key did not exist: " <> renderCompactPretty a- [_, d] -> throwErrorHere $ TypeError $ "lookup: second argument must be a dict: " <> renderCompactPretty d+ [_, d] -> throwErrorHere $ TypeError "lookup" 1 TDict dxs -> throwErrorHere $ WrongNumberOfArgs "lookup" 2 (length xs)), ( "map-values", "Given a function `f` and a dict `d`, returns a dict with the same keys as `d`\@@ -251,7 +255,7 @@ purePrimFns = fromList $ allDocs $let kvs = Map.toList mvs <- traverse (\v -> callFn f [v]) (snd <$> kvs)pure . Dict . Map.fromList $ zip (fst <$> kvs) vs- _ -> throwErrorHere $ TypeError $ "map-values: second argument must be a dict"+ (_, v) -> throwErrorHere $ TypeError "map-values" 1 TDict v)-- Structures@@ -261,14 +265,18 @@ purePrimFns = fromList $ allDocs $(List xs, List ys) -> pure $ List (xs ++ ys)(Vec xs, Vec ys) -> pure $ Vec (xs Seq.>< ys)(Dict m, Dict n) -> pure $ Dict (n <> m)- _ -> throwErrorHere $ TypeError "<>: only works on vectors or dicts"+ (x, y) -> throwErrorHere $ case x of+ List _ -> TypeError "<>" 1 TList y+ Vec _ -> TypeError "<>" 1 TVec y+ Dict _ -> TypeError "<>" 1 TDict y+ _ -> TypeError "<>" 0 TStructure y), ( "string-length", "Returns the length of a string.", oneArg "string-length" $ \caseString s -> pure . Number . fromIntegral . T.length $ s- _ -> throwErrorHere $ TypeError "string-length: expecting string"+ v -> throwErrorHere $ TypeError "string-length" 0 TString v), ( "string-append", "Concatenates a variable number of string arguments. If one of the arguments\@@ -276,10 +284,10 @@ purePrimFns = fromList $ allDocs $, \args ->let fromStr (String s) = Just sfromStr _ = Nothing- ss = fromStr <$> args- in if all isJust ss- then pure . String . mconcat $ catMaybes ss- else throwErrorHere $ TypeError "string-append: non-string argument"+ ss = zip3 args (fromStr <$> args) [0..]+ in case find (\(_, s_, _) -> isNothing s_) ss of+ Just (v, _, i) -> throwErrorHere $ TypeError "string-append" i TString v+ Nothing -> pure . String . mconcat $ catMaybes $ (\(_,x,_) -> x) <$> ss), ( "insert", "Given `k`, `v` and a dict `d`, returns a dict with the same associations\@@ -290,16 +298,14 @@ purePrimFns = fromList $ allDocs $if hashable kthen pure . Dict $ Map.insert k v melse throwErrorHere NonHashableKey- [_, _, _] -> throwErrorHere-- $ TypeError "insert: third argument must be a dict"+ [_, _, v] -> throwErrorHere $ TypeError "insert" 2 TDict vxs -> throwErrorHere $ WrongNumberOfArgs "insert" 3 (length xs)), ( "delete", "Given `k` and a dict `d`, returns a dict with the same associations as `d` but\\ without the key `k`. If `d` isn't a dict then an exception is thrown.", twoArg "delete" $ \case(k, Dict m) -> pure . Dict $ Map.delete k m- _ -> throwErrorHere $ TypeError "delete: second argument must be a dict"+ (_, v) -> throwErrorHere $ TypeError "delete" 1 TDict v)-- The semantics of + and - in Scheme is a little messed up. (+ 3)-- evaluates to 3, and of (- 3) to -3. That's pretty intuitive.@@ -317,19 +323,22 @@ purePrimFns = fromList $ allDocs $, twoArg "/" $ \case(Number x, Number y) | y /= 0 -> pure $ Number (x / y)(Number _, Number _) -> throwErrorHere $ OtherError "Can't divide by 0"- _ -> throwErrorHere $ TypeError "/: expects two numbers"+ (Number _, v) -> throwErrorHere $ TypeError "/" 1 TNumber v+ (v, _) -> throwErrorHere $ TypeError "/" 0 TNumber v), ( "<", "Checks if a number is strictly less than another.", \case[Number x, Number y] -> pure $ Boolean (x < y)- [_, _] -> throwErrorHere $ TypeError "<: expecting number"+ [Number _, v] -> throwErrorHere $ TypeError "<" 1 TNumber v+ [v, _] -> throwErrorHere $ TypeError "<" 0 TNumber vxs -> throwErrorHere $ WrongNumberOfArgs "<" 2 (length xs)), ( ">", "Checks if a number is strictly greater than another.", \case[Number x, Number y] -> pure $ Boolean (x > y)- [_, _] -> throwErrorHere $ TypeError ">: expecting number"+ [Number _, v] -> throwErrorHere $ TypeError ">" 1 TNumber v+ [_, v] -> throwErrorHere $ TypeError ">" 0 TNumber vxs -> throwErrorHere $ WrongNumberOfArgs ">" 2 (length xs)), ( "integral?", "Checks if a number is an integer."@@ -337,7 +346,7 @@ purePrimFns = fromList $ allDocs $Number n -> case Num.isInteger n ofLeft _ -> pure $ Boolean FalseRight _ -> pure $ Boolean True- _ -> throwErrorHere $ TypeError "integral?: expecting number"+ v -> throwErrorHere $ TypeError "integral?" 0 TNumber v), ( "foldl", "Given a function `f`, an initial value `i` and a sequence (list or vector)\@@ -363,7 +372,7 @@ purePrimFns = fromList $ allDocs $, \case[fn, List ls] -> List <$> traverse (callFn fn) (pure <$> ls)[fn, Vec ls] -> Vec <$> traverse (callFn fn) (pure <$> ls)- [_, _] -> throwErrorHere $ TypeError "map: second argument should be a list or vector"+ [_, v] -> throwErrorHere $ TypeError "map" 1 TSequence vxs -> throwErrorHere $ WrongNumberOfArgs "map" 3 (length xs)), ( "keyword?", isTy "keyword"@@ -395,19 +404,7 @@ purePrimFns = fromList $ allDocs $, "Returns a keyword representing the type of the argument; one of:\\ `:atom`, `:keyword`, `:string`, `:number`, `:boolean`, `:list`,\\ `:vector`, `:function`, `:dict`, `:ref`, `:function`."- , let kw' = pure . Keyword . Ident- in oneArg "type" $ \case- Atom _ -> kw' "atom"- Keyword _ -> kw' "keyword"- String _ -> kw' "string"- Number _ -> kw' "number"- Boolean _ -> kw' "boolean"- List _ -> kw' "list"- Vec _ -> kw' "vector"- PrimFn _ -> kw' "function"- Dict _ -> kw' "dict"- Ref _ -> kw' "ref"- Lambda{} -> kw' "function"+ , oneArg "type" $ pure . typeToValue . valType), ( "string?", isTy "string"@@ -432,8 +429,8 @@ purePrimFns = fromList $ allDocs $[x, List xs] -> pure . Boolean $ elem x xs[x, Vec xs] -> pure . Boolean . isJust $ Seq.elemIndexL x xs[x, Dict m] -> pure . Boolean $ Map.member x m- [_, _] -> throwErrorHere- $ TypeError "member?: second argument must be list, vector or dict"+ [_, v] -> throwErrorHere+ $ TypeError "member?" 1 TStructure vxs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs)), ( "ref", "Creates a ref with the argument as the initial value."@@ -442,7 +439,7 @@ purePrimFns = fromList $ allDocs $, "Returns the current value of a ref.", oneArg "read-ref" $ \caseRef ref -> readRef ref- _ -> throwErrorHere $ TypeError "read-ref: argument must be a ref")+ v -> throwErrorHere $ TypeError "read-ref" 0 TRef v), ( "write-ref", "Given a reference `r` and a value `v`, updates the value stored in `r` to be\\ `v` and returns `v`."@@ -451,8 +448,8 @@ purePrimFns = fromList $ allDocs $st <- getput $ st { bindingsRefs = IntMap.insert x v $ bindingsRefs st }pure v- [_, _] -> throwErrorHere- $ TypeError "write-ref: first argument must be a ref"+ [v, _] -> throwErrorHere+ $ TypeError "write-ref" 0 TRef vxs -> throwErrorHere$ WrongNumberOfArgs "write-ref" 2 (length xs)), ( "show"@@ -468,7 +465,7 @@ purePrimFns = fromList $ allDocs $x@(List _) -> pure xx@(Vec _) -> pure xDict kvs -> pure . Vec . Seq.fromList $ [Vec (Seq.fromList [k, v]) | (k,v) <- Map.toList kvs ]- _ -> throwErrorHere $ TypeError "seq: can only be used on a list, vector or dictionary"+ v -> throwErrorHere $ TypeError "seq" 0 TStructure v), ( "to-json", "Returns a JSON formatted string representing the input value."@@ -504,7 +501,7 @@ purePrimFns = fromList $ allDocs $, "Checks if a string has the format of a UUID.", oneArg "uuid?" $ \caseString t -> pure . Boolean . UUID.isUUID $ t- _ -> throwErrorHere $ TypeError "uuid?: expects a string"+ v -> throwErrorHere $ TypeError "uuid?" 0 TString v), ( "document", "Used to add documentation to variables."@@ -551,15 +548,14 @@ purePrimFns = fromList $ allDocs $-> Text-> Text-> (Text, Text, [Value] -> Lang m Value)- numBinop fn name doc = (name, doc, \case- Number x:x':xs -> foldM go (Number x) (x':xs)- where- go (Number a) (Number b) = pure . Number $ fn a b- go _ _ = throwErrorHere . TypeError- $ name <> ": expecting number"- [Number _] -> throwErrorHere- $ OtherError $ name <> ": expects at least 2 arguments"- _ -> throwErrorHere $ TypeError $ name <> ": expecting number")+ numBinop fn name doc =+ ( name+ , doc+ , twoArg name $ \case+ (Number a, Number b) -> pure . Number $ fn a b+ (Number _, v) -> throwErrorHere $ TypeError name 1 TNumber v+ (v, _) -> throwErrorHere $ TypeError name 0 TNumber v+ )-- * Helpersdiff --git a/src/Radicle/Internal/Type.hs b/src/Radicle/Internal/Type.hsnew file mode 100644index 0000000..d96d5c5--- /dev/null+++ b/src/Radicle/Internal/Type.hs@@ -0,0 +1,22 @@+module Radicle.Internal.Type where++import Protolude hiding (Type)++import Codec.Serialise (Serialise)++data Type+ = TAtom+ | TKeyword+ | TString+ | TNumber+ | TBoolean+ | TList+ | TVec+ | TSequence+ | TFunction+ | TDict+ | TStructure+ | TRef+ deriving (Eq, Show, Read, Generic)++instance Serialise Typediff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex e9b405b..c8934ea 100644--- a/test/spec/Radicle/Internal/TestCapabilities.hs+++ b/test/spec/Radicle/Internal/TestCapabilities.hs@@ -16,7 +16,8 @@ import Radicle.Internal.Core (addBinding)import Radicle.Internal.Cryptoimport Radicle.Internal.Effects.Capabilitiesimport qualified Radicle.Internal.Number as Num-import Radicle.Internal.PrimFns (allDocs)+import Radicle.Internal.PrimFns (allDocs, twoArg)+import Radicle.Internal.Type (Type(..))import qualified Radicle.Internal.UUID as UUIDimport Paths_radicle@@ -104,21 +105,20 @@ clientPrimFns = fromList . allDocs $ [sendPrimop, receivePrimop]sendPrimop =( "send!", "Mocked version of `send!` that stores sent values in a map with chains as keys."- , \case- [String url, Vec v] -> do+ , twoArg "send!" $ \case+ (String url, Vec v) -> dolift . modify $ \s ->s { worldStateRemoteChains= Map.insertWith (flip (Seq.><)) url v $ worldStateRemoteChains s }pure $ List []- [_, Vec _] -> throwErrorHere $ TypeError "send!: first argument should be a string"- [String _, _] -> throwErrorHere $ TypeError "send!: second argument should be a vector"- xs -> throwErrorHere $ WrongNumberOfArgs "send!" 2 (length xs)+ (String _, v) -> throwErrorHere $ TypeError "send!" 1 TVec v+ (v, _) -> throwErrorHere $ TypeError "send!" 0 TString v)receivePrimop =( "receive!", "Mocked version of `receive!` that retrieves values from a map with chains as keys."- , \case- [String url, Number n] -> do+ , twoArg "receive!" $ \case+ (String url, Number n) -> docase Num.isInt n ofLeft _ -> throwErrorHere . OtherError$ "receive!: expecting int argument"@@ -127,9 +127,8 @@ clientPrimFns = fromList . allDocs $ [sendPrimop, receivePrimop]pure . List $ case Map.lookup url chains ofNothing -> []Just res -> toList $ Seq.drop r res- [String _, _] -> throwErrorHere $ TypeError "receive!: expecting number as second arg"- [_, _] -> throwErrorHere $ TypeError "receive!: expecting string as first arg"- xs -> throwErrorHere $ WrongNumberOfArgs "receive!" 2 (length xs)+ (String _, v) -> throwErrorHere $ TypeError "receive!" 1 TNumber v+ (v, _) -> throwErrorHere $ TypeError "receive!" 0 TString v)instance {-# OVERLAPPING #-} Stdin TestLang wherediff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 4d35084..df4936e 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -321,17 +321,17 @@ test_eval ="(type (ref 0))" `hasTy` "ref""(type (fn [x] x))" `hasTy` "function"- , testCase "'+' sums the list of numbers" $ do- let prog1 = [s|(+ 2 (+ 2 3))|]- prog1 `succeedsWith` int 7- let prog2 = [s|(+ -1 -2 -3)|]- prog2 `succeedsWith` int (- 6)-- , testCase "'-' subtracts the list of numbers" $ do- let prog1= [s|(- (+ 2 3) 1)|]+ , testCase "'+' sums two numbers" $ do+ let prog1 = [s|(+ 2 1)|]+ prog1 `succeedsWith` int 3+ let prog2 = [s|(+ -1 -2)|]+ prog2 `succeedsWith` int (- 3)++ , testCase "'-' subtracts two numbers" $ do+ let prog1= [s|(- 5 1)|]prog1 `succeedsWith` int 4- let prog2 = [s|(- -1 -2 -3)|]- prog2 `succeedsWith` int 4+ let prog2 = [s|(- 6 -3)|]+ prog2 `succeedsWith` int 9, testCase "'*' multiplies the list of numbers" $ dolet prog = [s|(* 2 3)|]