Skip to content

A peer-to-peer stack for code collaboration

Dict keys should be hashable. (#217)

James Haydon99135eaa5cbd
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index c5f0306..1261749 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -50,6 +50,7 @@ data LangErrorData r =
-- | Takes the function name, expected number of args, and actual number of
-- args
| WrongNumberOfArgs Text Int Int
+ | NonHashableKey
| OtherError Text
| ParseError (Par.ParseError Char Void)
| ThrownError Ident r
@@ -92,6 +93,7 @@ errorDataToValue e = case e of
, ("expected", Number $ fromIntegral expected)
, ("actual", Number $ fromIntegral actual)]
)
+ NonHashableKey -> makeVal ( "non-hashable-key", [])
OtherError i -> makeVal
( "other-error"
, [("info", String i)]
@@ -148,6 +150,27 @@ data ValueF r =
instance Serialise r => Serialise (ValueF r)
+hashable :: (CPA t) => Annotated t ValueF -> Bool
+hashable = \case
+ Atom _ -> True
+ Boolean _ -> True
+ Number _ -> True
+ String _ -> True
+ Keyword _ -> True
+ PrimFn _ -> False
+ Ref _ -> False
+ Lambda{} -> False
+ List xs -> all hashable xs
+ Vec xs -> all hashable xs
+ Dict kvs -> getAll $ Map.foldMapWithKey (\k v -> All (hashable k && hashable v)) kvs
+
+-- | Smart constructor for dicts which checks that all the keys are hashable.
+dict :: (Monad m) => Map Value Value -> Lang m Value
+dict kvs =
+ if all hashable (Map.keys kvs)
+ then pure $ Dict kvs
+ else throwErrorHere NonHashableKey
+
{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Vec, PrimFn, Dict, Ref, Lambda #-}
type ValueConC t = (HasCallStack, Ann.Annotation t, Copointed t)
@@ -416,7 +439,8 @@ baseEval val = logValPos val $ case val of
Vec xs -> Vec <$> traverse baseEval xs
Dict mp -> do
let evalBoth (a,b) = (,) <$> baseEval a <*> baseEval b
- Dict . Map.fromList <$> traverse evalBoth (Map.toList mp)
+ kvs <- traverse evalBoth (Map.toList mp)
+ dict $ Map.fromList kvs
autoquote -> pure autoquote
specialForms :: forall m. (Monad m) => Map Ident ([Value] -> Lang m Value)
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index 16f72b0..3ebfa57 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -69,6 +69,7 @@ instance Pretty r => Pretty (LangErrorData r) where
WrongNumberOfArgs t x y -> "Wrong number of args in" <+> pretty t
<+> "Expected:" <+> pretty x
<+> "Got:" <+> pretty y
+ NonHashableKey -> "Non-hashable key in dict."
OtherError t -> "Error:" <+> pretty t
ParseError t -> "Parser error:" <+> pretty (parseErrorPretty t)
Exit -> "Exit"
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index 7c624ee..2a78249 100644
--- a/src/Radicle/Internal/PrimFns.hs
+++ b/src/Radicle/Internal/PrimFns.hs
@@ -112,9 +112,10 @@ purePrimFns = fromList $ allDocs $
, pure . List)
, ("dict"
, "Given an even number of arguments, creates a dict where the `2i`-th argument\
- \ is the key for the `2i+1`th argument."
- , (Dict . foldr (uncurry Map.insert) mempty <$>)
- . evenArgs "dict")
+ \ is the key for the `2i+1`th argument. If one of the even indexed arguments\
+ \ is not hashable then an exception is thrown."
+ , evenArgs "dict" >=> dict . Map.fromList
+ )
, ("throw"
, "Throws an exception. The first argument should be an atom used as a label for\
\ the exception, the second can be any value."
@@ -235,7 +236,7 @@ purePrimFns = fromList $ allDocs $
(f, Dict m) -> do
let kvs = Map.toList m
vs <- traverse (\v -> callFn f [v]) (snd <$> kvs)
- pure (Dict (Map.fromList (zip (fst <$> kvs) vs)))
+ pure . Dict . Map.fromList $ zip (fst <$> kvs) vs
_ -> throwErrorHere $ TypeError $ "map-values: second argument must be a dict"
)
, ( "string-length"
@@ -257,10 +258,13 @@ purePrimFns = fromList $ allDocs $
)
, ( "insert"
, "Given `k`, `v` and a dict `d`, returns a dict with the same associations\
- \ as `d` but with `k` associated to `d`. If `d` isn't a dict then an exception\
- \ is thrown."
+ \ as `d` but with `k` associated to `d`. If `d` isn't a dict or if `k` isn't\
+ \ hashable then an exception is thrown."
, \case
- [k, v, Dict m] -> pure . Dict $ Map.insert k v m
+ [k, v, Dict m] ->
+ if hashable k
+ then pure . Dict $ Map.insert k v m
+ else throwErrorHere NonHashableKey
[_, _, _] -> throwErrorHere
$ TypeError "insert: third argument must be a dict"
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index c762ddb..9ac7b57 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -146,6 +146,14 @@ test_eval =
let prog3 = [s|(lookup '(2 3) (insert '(2 3) "b" (dict)))|]
prog3 `succeedsWith` String "b"
+ , testCase "dict keys should be hashable" $ do
+ let f x = x `failsWith` NonHashableKey
+ f "(insert (ref 0) 1 {})"
+ f "{(ref 0) 1}"
+ "(lookup :k {'(fn [x] y) 1 :k :v})" `succeedsWith` Keyword [ident|v|]
+ f "(eval {'(fn [y] y) :a-fun} (get-current-env))"
+ f "(dict (ref 0) 1)"
+
, testProperty "'string-append' concatenates string" $ \ss -> do
let args = T.unwords $ renderPrettyDef . asValue . String <$> ss
prog = "(string-append " <> args <> ")"