A peer-to-peer stack for code collaboration
feat: Short-form lambdas. (#599)
James Haydon8e9b46daf5da
diff --git a/.weeder.yaml b/.weeder.yamlindex cc6a825..b4ce62d 100644--- a/.weeder.yaml+++ b/.weeder.yaml@@ -12,6 +12,7 @@- atom- int- kw+ - vec- parseTest- prettyEither- stackTraceLinesdiff --git a/docs/source/guide/Basics.lrad b/docs/source/guide/Basics.lradindex 832a8fe..3fb5bbe 100644--- a/docs/source/guide/Basics.lrad+++ b/docs/source/guide/Basics.lrad@@ -240,5 +240,43 @@ function, use the `def-rec` form:Note that `def-rec` may only be used to define functions.+For creating one-off anonymous functions quickly, there is a short-form. This is+formed by a `\` character (meant to look like the main stroke of a λ) and then a+valid radicle expression, which will be the return value of the function. To+make a single parameter function use `?` for the argument. To make a+multi-parameter function, use `?1`, `?2`, etc. Here are some examples of+short-form lambdas and the long-form equivalent:++```radicle+;; The identity function.+\?+(fn [x] x)++;; Partial application:+\(foo 0 ?)+(fn [x] (foo 0 x))++;; A function to make singleton vectors:+\[?]+(fn [x] [x])++;; Multiple arguments:+\(string-append ?1 " is the parent of " ?2)+(fn [x y] (string-append x " is the parent of " y))++;; Thunks:+\(put-str! "hello there!")+(fn [] (put-str! "hello there"))+```++Note that:+- Only `?1`, `?2`, ..., `?9` are allowed for positional arguments. If you want+ more that 9 parameters please seek professional help.+- Short-form lambdas cannot be nested.+- You cannot use a mixture of `?` and `?1`, `?2`, etc. inside a short-form+ lambda.+- To avoid hard to detect bugs, atoms starting with a `?` followed by a sequence+ of digits that isn't one of the allowed positional atoms will cause an error.+## Quote and evaldiff --git a/src/Radicle/Internal/Interpret.hs b/src/Radicle/Internal/Interpret.hsindex e020b03..e99d9d7 100644--- a/src/Radicle/Internal/Interpret.hs+++ b/src/Radicle/Internal/Interpret.hs@@ -2,8 +2,6 @@ module Radicle.Internal.Interpret whereimport Protolude-import Text.Megaparsec (eof, runParserT)-import qualified Radicle.Internal.Annotation as Annimport Radicle.Internal.Coreimport Radicle.Internal.Eval@@ -38,7 +36,7 @@ interpretWithState-> Bindings (PrimFns m) -- ^ Bindings to be used-> m (Either (LangError Value) Value, Bindings (PrimFns m))interpretWithState sourceName expr bnds = do- let parsed = runIdentity (runParserT (spaceConsumer *> valueP <* eof) (toS sourceName) expr)+ let parsed = parseValue (toS sourceName) exprcase parsed ofLeft e -> pure (Left (LangError [Ann.thisPos] (ParseError e)), bnds)Right v -> runLang bnds (eval v)diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hsindex dbeede5..b726ce6 100644--- a/src/Radicle/Internal/Parse.hs+++ b/src/Radicle/Internal/Parse.hs@@ -2,8 +2,12 @@ module Radicle.Internal.Parse whereimport Protolude hiding (SrcLoc, try)+import Control.Monad.Fail+import qualified Data.Char as Charimport qualified Data.Map as Mapimport qualified Data.Sequence as Seq+import qualified Data.Set as Set+import qualified Data.Text as Timport GHC.Exts (IsString(..))import Text.Megaparsec( ParsecT@@ -28,7 +32,12 @@ import Radicle.Internal.Identifier-- * The parser-type Parser a = ParsecT Void Text Identity a+data InShortLambda = NotInShortLambda | InShortLambda+ deriving Eq++-- | A parser. In order to detect nested short-lambdas, the parser keeps track+-- of if it has entered a short-lambda.+type Parser a = ParsecT Void Text (Reader InShortLambda) atype VParser = Parser ValuespaceConsumer :: Parser ()@@ -123,6 +132,58 @@ quoteP = doq <- tag $ AtomF (unsafeToIdent "quote")pure $ List [q, val]+data QMark = QMPlain | QMDigit Int+ deriving (Eq, Ord)++shortLam :: VParser+shortLam = do+ _ <- char '\\'+ inShortAlready <- ask+ if inShortAlready == InShortLambda+ then fail "Short-lambdas cannot be nested."+ else do+ expr <- local (const InShortLambda) valueP+ case qMarks expr of+ Nothing -> fail "Invalid ?-atoms in short-lambda: a '?' may only be followed by a single non-zero digit."+ Just qs -> case validQMarks (Set.toList qs) of+ Just args -> tag . ListF $ [Atom (Ident "fn"), Vec (Seq.fromList args), expr]+ Nothing -> fail "Invalid ?-atoms in short-lambda: plain `?` and numbered `?` cannot be used at the same time."+ where+ -- | A short-lambda should either use no ?-atoms at all, only plain ?-atoms,+ -- or only numbered ?-atoms.+ validQMarks :: [QMark] -> Maybe [Value]+ validQMarks qs = case (qs, traverse numbered qs) of+ ([], _) -> Just []+ (_, Just ds) -> Just $ qMarkAtom . QMDigit <$> [1..maximum ds]+ ([QMPlain], _)-> Just [qMarkAtom QMPlain]+ _ -> Nothing++ -- | Get the ?-atoms in an expression (?-atoms are either an @?@, or @?i@+ -- where @i@ in @{1, ..., 9}@.). If there are any atoms which start with a+ -- @?@ followed by digits that are /not/ ?-atoms, then returns Nothing.+ qMarks :: Value -> Maybe (Set QMark)+ qMarks = \case+ Atom (Ident t) -> case T.uncons t of+ Just ('?', rest) | T.all Char.isDigit rest ->+ case T.uncons rest of+ Just (d, rest') | d /= '0' && T.null rest' -> Just (Set.singleton (QMDigit (Char.digitToInt d)))+ Just _ -> Nothing+ Nothing -> Just (Set.singleton QMPlain)+ _ -> Just Set.empty+ List xs -> coll xs+ Vec xs -> coll xs+ Dict m -> Set.union <$> coll (Map.keys m) <*> coll (Map.elems m)+ _ -> pure Set.empty++ coll xs = Set.unions <$> traverse qMarks xs++ qMarkAtom QMPlain = Atom (Ident "?")+ qMarkAtom (QMDigit i) = Atom (Ident ("?" <> show i))++ numbered = \case+ QMPlain -> Nothing+ QMDigit d -> Just d+valueP :: VParservalueP = dov <- choice@@ -135,12 +196,20 @@ valueP = do, listP <?> "list", vecP <?> "vector", dictP <?> "dict"+ , shortLam <?> "short-lambda"]spaceConsumerpure v-- * Utilities+-- | Parses a top-level expression (i.e. assumes not inside a short-lambda).+parseTop :: Parser a -> Text -> Text -> Either (Par.ParseErrorBundle Text Void) a+parseTop p src code = runIdentity $ runReaderT (M.runParserT p (toS src) code) NotInShortLambda++parseValue :: Text -> Text -> Either (Par.ParseErrorBundle Text Void) Value+parseValue = parseTop (spaceConsumer *> valueP <* eof)+-- | Parse a Text as a series of values.---- Note that parsing continues even if one value fails to parse.@@ -149,7 +218,7 @@ parseValues-> Text -- ^ Source code to be parsed-> Either (Par.ParseErrorBundle Text Void) [Value]parseValues sourceName srcCode- = M.parse (spaceConsumer *> many valueP <* eof) (toS sourceName) srcCode+ = parseTop (spaceConsumer *> many valueP <* eof) sourceName srcCode-- | Parse a single value.--@@ -165,14 +234,14 @@ parse :: MonadError Text m-> Text -- ^ Source code to be parsed-> m Valueparse file src = do- let res = runIdentity (M.runParserT (spaceConsumer *> valueP <* eof) (toS file) src)+ let res = parseValue file srccase res ofLeft err -> throwError . toS $ M.errorBundlePretty errRight v -> pure v-- | Smart constructor for Ident.mkIdent :: Text -> Maybe Ident-mkIdent t = case runIdentity (M.runParserT (valueP <* M.eof) "" t) of+mkIdent t = case parseTop (valueP <* M.eof) "" t of-- We use the 'valueP' parser instead of 'identP' so that we don’t-- negative numbers like @-4@.Right (Atom i) -> pure idiff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 3222ff5..760f557 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -44,11 +44,11 @@ test_eval =, testCase "vector syntax creates vectors" $ do"[]" `succeedsWith` Vec Empty- "[1 2]" `succeedsWith` Vec (fromList [int 1, int 2])- "[1 :a [:b 2]]" `succeedsWith` Vec (fromList [int 1, kw "a", Vec (fromList [kw "b", int 2])])+ "[1 2]" `succeedsWith` vec [int 1, int 2]+ "[1 :a [:b 2]]" `succeedsWith` vec [int 1, kw "a", vec [kw "b", int 2]], testCase "vectors evaluate their elements" $- "[(+ 1 2) (* 3 4)]" `succeedsWith` Vec (fromList [int 3, int 12])+ "[(+ 1 2) (* 3 4)]" `succeedsWith` vec [int 3, int 12], testCase "'dict' creates a Dict with given key/vals" $ dolet prog1 = [s|(dict 'why "not")|]@@ -83,13 +83,13 @@ test_eval ="(nth 1 '(0 1 2))" `succeedsWith` int 1, testCase "'take n' takes n elements of a sequence" $ do- "(take 0 [0 1 2])" `succeedsWith` Vec (fromList [])- "(take 2 [0 1 2])" `succeedsWith` Vec (fromList [Number 0, Number 1])+ "(take 0 [0 1 2])" `succeedsWith` vec []+ "(take 2 [0 1 2])" `succeedsWith` vec [Number 0, Number 1]"(take 2 (list 0 1 2))" `succeedsWith` List [Number 0, Number 1], testCase "'drop n' drops n elements of a sequence" $ do- "(drop 0 [0 1 2])" `succeedsWith` Vec (fromList [Number 0, Number 1, Number 2])- "(drop 2 [0 1 2])" `succeedsWith` Vec (fromList [Number 2])+ "(drop 0 [0 1 2])" `succeedsWith` vec [Number 0, Number 1, Number 2]+ "(drop 2 [0 1 2])" `succeedsWith` vec [Number 2]"(drop 2 (list 0 1 2))" `succeedsWith` List [Number 2], testProperty "'eq?' considers equal values equal" $ \(val :: Value) -> do@@ -609,6 +609,38 @@ test_parser =, testCase "parses dicts" $ do"{:foo 3}" ~~> Dict (Map.singleton (Keyword [ident|foo|]) (int 3))+ , testCase "parses short-lambdas" $ do+ "\\0" ~~> lam [] [int 0]+ "\\3/2" ~~> lam [] [Number (3 % 2)]+ "\\:foo" ~~> lam [] [kw "foo"]+ "\\\"foo\"" ~~> lam [] [String "foo"]+ "\\x" ~~> lam [] [atom "x"]+ "\\#t" ~~> lam [] [Boolean True]+ "\\?" ~~> lam ["?"] [atom "?"]+ "\\[]" ~~> lam [] [vec []]+ "\\[? 1]" ~~> lam ["?"] [vec [atom "?", int 1]]+ "\\[?1 ?2]" ~~> lam ["?1", "?2"] [vec [atom "?1", atom "?2"]]+ "\\{}" ~~> lam [] [Dict Map.empty]+ "\\{:a ?}" ~~> lam ["?"] [Dict (fromList [(kw "a", atom "?")])]+ "\\()" ~~> lam [] [List []]+ "\\(foo ? 42)" ~~> lam ["?"] [List [atom "foo", atom "?", int 42]]+ "\\(foo ?1 42 ?2)" ~~> lam ["?1", "?2"] [List [atom "foo", atom "?1", int 42, atom "?2"]]+ "\\(foo ?2 42 ?1)" ~~> lam ["?1", "?2"] [List [atom "foo", atom "?2", int 42, atom "?1"]]+ "\\(fn [x y] (foo x ? y))" ~~> lam ["?"] [lam ["x", "y"] [List [atom "foo", atom "x", atom "?", atom "y"]]]++ , testCase "short-lambdas only accepts ? or a mix of ?i where i in {1,...,9}" $ do+ assertBool "? and ?1" (isLeft $ parseTest "\\[? ?1]")+ assertBool "? and ?2" (isLeft $ parseTest "\\[? ?2]")+ assertBool "?0" (isLeft $ parseTest "\\(foo ?0)")+ assertBool "?42" (isLeft $ parseTest "\\[?42]")++ , testCase "short-lambdas cannot be nested" $ do+ assertBool "directly" (isLeft $ parseTest "\\\\?")+ assertBool "directly" (isLeft $ parseTest "\\\\(foo ?)")+ assertBool "directly" (isLeft $ parseTest "\\\\(foo ?1 ?2)")+ assertBool "indirectly" (isLeft $ parseTest "\\(foo \\(bar ?))")+ assertBool "indirectly" (isLeft $ parseTest "\\(foo \\(bar ?1 ?2))")+, 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}")@@ -620,7 +652,9 @@ test_parser =assertBool "not for -93G" (isNothing (mkIdent "a b"))]where- x ~~> y = parseTest x @?= Right y+ (~~>) :: Text -> Value -> Assertion+ x ~~> y = (untag <$> parseTest x) @?= Right (untag y)+ lam args body = List $ [atom "fn", vec (atom <$> args)] ++ bodytest_binding :: [TestTree]test_binding =@@ -801,8 +835,8 @@ test_from_to_radicle =], testGroup "CmdSpec"- [ Vec (fromList [kw "shell", String "blah blah"]) ~~ ShellCommand "blah blah"- , Vec (fromList [kw "raw", String "blah", Vec $ fromList [String "blah", String "blah"]])+ [ vec [kw "shell", String "blah blah"] ~~ ShellCommand "blah blah"+ , vec [kw "raw", String "blah", vec [String "blah", String "blah"]]~~ RawCommand "blah" ["blah", "blah"]]]@@ -855,6 +889,9 @@ atom = Atom . unsafeToIdentint :: Integer -> Valueint = Number . fromIntegral+vec :: [Value] -> Value+vec = Vec . fromList+-- | Like 'parse', but uses "(test)" as the source name and the default set of-- primops.parseTest :: MonadError Text m => Text -> m Value