A peer-to-peer stack for code collaboration
Add unsafeToIdent, Identifier pattern, and ident QQ. (#105)
Julian Arni3192902bb70b
diff --git a/exe/Server/Client.hs b/exe/Server/Client.hsindex 159ab48..9768977 100644--- a/exe/Server/Client.hs+++ b/exe/Server/Client.hs@@ -73,7 +73,7 @@ primops :: ClientEnv -> Primops (InputT IO)primops cEnv = Primops (fromList [sendPrimop, receivePrimop]) <> replPrimopswheresendPrimop =- ( Ident "send!"+ ( unsafeToIdent "send!", evalArgs $ \case[String name, v] -> dores <- liftIO $ runClientM (submit $ List $ [String name, v]) cEnv@@ -85,7 +85,7 @@ primops cEnv = Primops (fromList [sendPrimop, receivePrimop]) <> replPrimopsxs -> throwErrorHere $ WrongNumberOfArgs "send!" 2 (length xs))receivePrimop =- ( Ident "receive!"+ ( unsafeToIdent "receive!", evalArgs $ \case[String name, Number n] -> docase floatingOrInteger n of@@ -104,7 +104,7 @@ primops cEnv = Primops (fromList [sendPrimop, receivePrimop]) <> replPrimops-- * HelpersidentV :: Text -> Value-identV = Keyword . Ident+identV = Keyword . unsafeToIdent-- * Client functionsdiff --git a/package.yaml b/package.yamlindex 6d282b3..08462a5 100644--- a/package.yaml+++ b/package.yaml@@ -24,6 +24,7 @@ dependencies:- recursion-schemes- scientific- serialise+- template-haskell- text- unordered-containers- cryptonitediff --git a/src/Radicle.hs b/src/Radicle.hsindex 6942982..cc6b917 100644--- a/src/Radicle.hs+++ b/src/Radicle.hs@@ -39,9 +39,13 @@ module Radicle, LangError(..), LangErrorData(..), throwErrorHere- , Ident(..), Reference(..)+ , Ident+ , ident, mkIdent+ , unsafeToIdent+ , fromIdent+ , pattern Identifier, Env(..), pureEnv, Langdiff --git a/src/Radicle/Internal.hs b/src/Radicle/Internal.hsindex 979d5fc..7fa47f3 100644--- a/src/Radicle/Internal.hs+++ b/src/Radicle/Internal.hs@@ -1,10 +1,14 @@+{-# LANGUAGE TemplateHaskell #-}module Radicle.Internal( module X, mkIdent+ , ident) where+import Prelude (error)import Protolude+import Language.Haskell.TH.Quoteimport Radicle.Internal.CLI as Ximport Radicle.Internal.Core as Ximport Radicle.Internal.Effects as X@@ -20,3 +24,14 @@ mkIdent :: Text -> Maybe IdentmkIdent t = case runReader (M.runParserT identP "" t) [] ofLeft _ -> NothingRight v -> pure v++-- | A quasiquoter that checks that an identifier is valid at compile-time.+ident :: QuasiQuoter+ident = QuasiQuoter+ { quoteExp = \s -> [| case mkIdent s of+ Nothing -> error $ "Not a valid identifier: " <> s+ Just i -> i |]+ , quoteType = error "ident only works for expressions"+ , quotePat = error "ident only works for expressions"+ , quoteDec = error "ident only works for expressions"+ }diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex cd69f46..f83a1bc 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -221,7 +221,7 @@ instance A.FromJSON Value whereA.String s -> pure $ String sA.Array ls -> List . toList <$> traverse parseJSON lsA.Bool b -> pure $ Boolean b- A.Null -> pure $ Keyword (toIdent "null")+ A.Null -> pure $ Keyword (Ident "null")A.Object hm -> dolet kvs = HashMap.toList hmvs <- traverse parseJSON (snd <$> kvs)@@ -267,10 +267,15 @@ maybeJson = \casenewtype Ident = Ident { fromIdent :: Text }deriving (Eq, Show, Read, Ord, Generic, Data, Serialise)+pattern Identifier :: Text -> Ident+pattern Identifier t <- Ident t++-- | Convert a text to an identifier.+---- Unsafe! Only use this if you know the string at compile-time and know it's a--- valid identifier-toIdent :: Text -> Ident-toIdent = Ident+-- valid identifier. Otherwise, use 'mkIdent'.+unsafeToIdent :: Text -> Ident+unsafeToIdent = Ident-- | The environment, which keeps all known bindings.newtype Env s = Env { fromEnv :: Map Ident s }@@ -369,7 +374,7 @@ defineAtom i v = modify $ addBinding i v-- | The buck-passing eval. Uses whatever 'eval' is in scope.eval :: Monad m => Value -> Lang m Valueeval val = do- e <- lookupAtom (toIdent "eval")+ e <- lookupAtom (Ident "eval")st <- gets toRadlogValPos e $ case e ofPrimop i -> dodiff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hsindex 7bef43f..bb6111c 100644--- a/src/Radicle/Internal/Effects.hs+++ b/src/Radicle/Internal/Effects.hs@@ -70,7 +70,7 @@ replBindings = e { bindingsPrimops = bindingsPrimops e <> replPrimops }e = pureEnvreplPrimops :: forall m. ReplM m => Primops m-replPrimops = Primops . Map.fromList $ first toIdent <$>+replPrimops = Primops . Map.fromList $ first unsafeToIdent <$>[ ("print!", \args -> case args of[x] -> dov <- eval x@@ -96,7 +96,7 @@ replPrimops = Primops . Map.fromList $ first toIdent <$>v' <- eval ve <- gets bindingsEnvcase (x', v') of- (Dict m, fn) -> case Map.lookup (Atom $ toIdent "getter") m of+ (Dict m, fn) -> case Map.lookup (Atom $ unsafeToIdent "getter") m ofNothing -> throwErrorHere$ OtherError "subscribe-to!: Expected 'getter' key"Just g -> forever (protect go)diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hsindex 6c90e76..3d3e62b 100644--- a/src/Radicle/Internal/Parse.hs+++ b/src/Radicle/Internal/Parse.hs@@ -118,7 +118,7 @@ dictP = bracesP (tag =<< (DictF . Map.fromList <$> evenItems))quoteP :: VParserquoteP = doval <- char '\'' >> valueP- q <- tag $ PrimopF (toIdent "quote")+ q <- tag $ PrimopF (unsafeToIdent "quote")pure $ List [q, val]valueP :: VParser@@ -168,7 +168,7 @@ parseValues sourceName srcCode prims = withoutLeadingSpaces-- >>> untag <$> parse "test" "#t" [] :: Either Text UntaggedValue-- Right (Annotated (Identity (BooleanF True)))----- >>> untag <$> parse "test" "hi" [toIdent "hi"] :: Either Text UntaggedValue+-- >>> untag <$> parse "test" "hi" [unsafeToIdent "hi"] :: Either Text UntaggedValue-- Right (Annotated (Identity (PrimopF (Ident {fromIdent = "hi"}))))---- >>> untag <$> parse "test" "hi" [] :: Either Text UntaggedValuediff --git a/src/Radicle/Internal/Primops.hs b/src/Radicle/Internal/Primops.hsindex 4dc923e..8dfa8a0 100644--- a/src/Radicle/Internal/Primops.hs+++ b/src/Radicle/Internal/Primops.hs@@ -23,8 +23,8 @@ import Radicle.Internal.PrettypureEnv :: (Monad m) => Bindings (Primops m)pureEnv = Bindings e purePrimops r 1where- e = fromList [ (toIdent "eval", Primop $ toIdent "base-eval")- , (toIdent "_doc-ref", Ref $ Reference 0)+ e = fromList [ (unsafeToIdent "eval", Primop $ unsafeToIdent "base-eval")+ , (unsafeToIdent "_doc-ref", Ref $ Reference 0)]r = fromList [ (0, Dict mempty) ]diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 2500bf9..755643e 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -21,17 +21,17 @@ import qualified Text.Megaparsec.Pos as Parimport Radicleimport qualified Radicle.Internal.Annotation as Annimport Radicle.Internal.Arbitrary ()-import Radicle.Internal.Core (asValue, noStack, toIdent)+import Radicle.Internal.Core (asValue, noStack)import Radicle.Internal.Foo (Foo)import Radicle.Internal.TestCapabilitiestest_eval :: [TestTree]test_eval =[ testCase "Fails for undefined atoms" $- [s|blah|] `failsWith` UnknownIdentifier (toIdent "blah")+ [s|blah|] `failsWith` UnknownIdentifier [ident|blah|], testCase "Keywords eval to themselves" $- [s|:blah|] `succeedsWith` Keyword (toIdent "blah")+ [s|:blah|] `succeedsWith` Keyword [ident|blah|], testCase "Succeeds for defined atoms" $ dolet prog = [s|@@ -50,7 +50,7 @@ test_eval =, testCase "'dict' creates a Dict with given key/vals" $ dolet prog1 = [s|(dict 'why "not")|]- prog1 `succeedsWith` Dict (fromList [(Atom $ toIdent "why", String "not")])+ prog1 `succeedsWith` Dict (fromList [(Atom $ [ident|why|], String "not")])let prog2 = [s|(dict 3 1)|]prog2 `succeedsWith` Dict (fromList [(Number 3, Number 1)])@@ -274,7 +274,7 @@ test_eval ="(dict? :foo)" `succeedsWith` Boolean False, testCase "'type' returns the type, as a keyword" $ do- let hasTy prog ty = prog `succeedsWith` Keyword (Ident ty)+ let hasTy prog ty = prog `succeedsWith` kw ty"(type :keyword)" `hasTy` "keyword""(type \"string\")" `hasTy` "string""(type 'a)" `hasTy` "atom"@@ -419,12 +419,12 @@ test_eval =runTest' "(show #t)" @?= Right (String "#t")runTest' "(show #f)" @?= Right (String "#f")runTest' "(show (list 'a 1 \"foo\" (list 'b ''x 2 \"bar\")))" @?= Right (String "(a 1.0 \"foo\" (b (quote x) 2.0 \"bar\"))")- runTest' "eval" @?= Right (Primop (toIdent "base-eval"))+ runTest' "eval" @?= Right (Primop [ident|base-eval|])runTest' "(show (dict 'a 1))" @?= Right (String "{a 1.0}")runTest' "(show (lambda (x) x))" @?= Right (String "(lambda (x) x)"), testCase "'read' works" $- runTest' "(read \"(:hello 42)\")" @?= Right (List [Keyword (toIdent "hello"), Number 42])+ runTest' "(read \"(:hello 42)\")" @?= Right (List [Keyword [ident|hello|], Number 42]), testCase "'to-json' works" $ dorunTest' "(to-json (dict \"foo\" #t))" @?= Right (String "{\"foo\":true}")@@ -452,7 +452,7 @@ test_eval =(outer)|]case runTest' prog of- Left (LangError stack (UnknownIdentifier (Ident "notdefined"))) ->+ Left (LangError stack (UnknownIdentifier (Identifier "notdefined"))) ->assertEqual "correct line numbers" [3,2,1,1] (stackTraceLines stack)r -> assertFailure $ "Didn't fail the way we expected: " ++ show r@@ -463,7 +463,7 @@ test_eval =(callit inner)|]case runTest' prog of- Left (LangError stack (UnknownIdentifier (Ident "notdefined"))) ->+ Left (LangError stack (UnknownIdentifier (Identifier "notdefined"))) ->assertEqual "correct line numbers" [3,1,2,2] (stackTraceLines stack)r -> assertFailure $ "Didn't fail the way we expected: " ++ show r]@@ -487,8 +487,8 @@ test_parser ="#f" ~~> Boolean False, testCase "parses primops" $ do- "boolean?" ~~> Primop (toIdent "boolean?")- "base-eval" ~~> Primop (toIdent "base-eval")+ "boolean?" ~~> Primop [ident|boolean?|]+ "base-eval" ~~> Primop [ident|base-eval|], testCase "parses keywords" $ do":foo" ~~> kw "foo"@@ -498,29 +498,29 @@ test_parser =":456" ~~> kw "456", testCase "parses identifiers" $ do- "++" ~~> Atom (toIdent "++")- "what?crazy!" ~~> Atom (toIdent "what?crazy!")+ "++" ~~> Atom [ident|++|]+ "what?crazy!" ~~> Atom [ident|what?crazy!|], testCase "parses identifiers that have a primop as prefix" $ do- "evaluate" ~~> Atom (toIdent "evaluate")+ "evaluate" ~~> Atom [ident|evaluate|], testCase "parses function application" $ do- "(++)" ~~> List [Atom (toIdent "++")]- "(++ \"merge\" \"d\")" ~~> List [Atom (toIdent "++"), String "merge", String "d"]+ "(++)" ~~> List [Atom [ident|++|]]+ "(++ \"merge\" \"d\")" ~~> List [Atom [ident|++|], String "merge", String "d"], testCase "parses numbers" $ do"0.15" ~~> Number 0.15"2000" ~~> Number 2000, testCase "parses identifiers" $ do- "++" ~~> Atom (toIdent "++")- "what?crazy!" ~~> Atom (toIdent "what?crazy!")+ "++" ~~> Atom [ident|++|]+ "what?crazy!" ~~> Atom [ident|what?crazy!|], testCase "parses identifiers that have a primop as prefix" $ do- "evaluate" ~~> Atom (toIdent "evaluate")+ "evaluate" ~~> Atom [ident|evaluate|], testCase "parses dicts" $ do- "{:foo 3}" ~~> Dict (Map.singleton (Keyword (toIdent "foo")) (Number 3))+ "{:foo 3}" ~~> Dict (Map.singleton (Keyword [ident|foo|]) (Number 3)), testCase "a dict litteral with an odd number of forms is a syntax error" $assertBool "succesfully parsed a dict with 3 forms" (isLeft $ parseTest "{:foo 3 4}")@@ -708,10 +708,10 @@ test_source_files = testGroup "Radicle source file tests" <$> do-- * Utilskw :: Text -> Value-kw = Keyword . toIdent+kw = Keyword . unsafeToIdentatom :: Text -> Value-atom = Atom . toIdent+atom = Atom . unsafeToIdent-- -- | Like 'parse', but uses "(test)" as the source name and the default set of-- -- primops.