Skip to content

A peer-to-peer stack for code collaboration

Handle recursive functions at call site

Thomas Scholtes328010aa7199
diff --git a/exe/ReferenceDoc.hs b/exe/ReferenceDoc.hs
index ac98885..f9a27e8 100644
--- a/exe/ReferenceDoc.hs
+++ b/exe/ReferenceDoc.hs
@@ -99,13 +99,16 @@ lPanic (Right r) _ = r
valueDoc :: Text -> Text -> Value -> [Block]
valueDoc name docString value = case value of
- Lambda args _ _ ->
- let callExample = "(" <> T.intercalate " " (name : map fromIdent args) <> ")"
- in [ Header 3 nullAttr [Code nullAttr (toS callExample) ] ]
- <> parseMarkdownBlocks docString
+ Lambda args _ _ -> lambdaDoc args
+ LambdaRec _ args _ _ -> lambdaDoc args
_ ->
[ Header 3 nullAttr [Code nullAttr (toS name) ] ]
<> parseMarkdownBlocks docString
+ where
+ lambdaDoc args =
+ let callExample = "(" <> T.intercalate " " (name : map fromIdent args) <> ")"
+ in [ Header 3 nullAttr [Code nullAttr (toS callExample) ] ]
+ <> parseMarkdownBlocks docString
-- | Generate documentation for primitive functions defined by 'replBindings'
docForPrimFns :: Content -> [Block]
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index f58d5b7..fa48d87 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -252,6 +252,12 @@ data ValueF r =
-- The value of an application of a lambda is always the last value in the
-- body. The only reason to have multiple values is for effects.
| LambdaF [Ident] (NonEmpty r) (Env r)
+ -- | Like 'LambdaF' but indicates a function that can call itself
+ -- recursively.
+ --
+ -- The first argument is the name for recursive calls to the
+ -- function in the body.
+ | LambdaRecF Ident [Ident] (NonEmpty r) (Env r)
deriving (Eq, Ord, Read, Show, Generic, Functor)
instance Serialise r => Serialise (ValueF r)
@@ -271,6 +277,7 @@ valType = \case
Handle _ -> THandle
ProcHandle _ -> TProcHandle
Lambda{} -> TFunction
+ LambdaRec{} -> TFunction
hashable :: (CPA t) => Annotated t ValueF -> Bool
hashable = \case
@@ -284,6 +291,7 @@ hashable = \case
Handle _ -> False
ProcHandle _ -> False
Lambda{} -> False
+ LambdaRec{} -> False
List xs -> all hashable xs
Vec xs -> all hashable xs
Dict kvs -> getAll $ Map.foldMapWithKey (\k v -> All (hashable k && hashable v)) kvs
@@ -296,7 +304,7 @@ dict kvs =
else throwErrorHere NonHashableKey
{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Vec, PrimFn, Dict
- , Ref, Handle, ProcHandle, Lambda #-}
+ , Ref, Handle, ProcHandle, Lambda, LambdaRec #-}
type ValueConC t = (HasCallStack, Ann.Annotation t, Copointed t)
@@ -365,6 +373,11 @@ pattern Lambda vs exps env <- (Ann.match -> LambdaF vs exps env)
where
Lambda vs exps env = Ann.annotate $ LambdaF vs exps env
+pattern LambdaRec :: ValueConC t => Ident -> [Ident] -> NonEmpty (Annotated t ValueF) -> Env (Annotated t ValueF) -> Annotated t ValueF
+pattern LambdaRec self vs exps env <- (Ann.match -> LambdaRecF self vs exps env)
+ where
+ LambdaRec self vs exps env = Ann.annotate $ LambdaRecF self vs exps env
+
type UntaggedValue = Annotated Identity ValueF
type Value = Annotated Ann.WithPos ValueF
@@ -722,10 +735,11 @@ specialForms = Map.fromList $ first Ident <$>
val' <- baseEval val
case val' of
Lambda is b e -> do
- let v = Lambda is b (Env . Map.insert name (Doc.Docd doc_ v) . fromEnv $ e)
- defineAtom name doc_ v
+ defineAtom name doc_ $ LambdaRec name is b e
pure nil
- _ -> throwErrorHere $ OtherError "def-rec can only be used to define functions"
+ LambdaRec{} -> throwErrorHere $
+ OtherError "'def-rec' cannot be used to alias functions. Use 'def' instead"
+ _ -> throwErrorHere $ OtherError "'def-rec' can only be used to define functions"
data ModuleMeta = ModuleMeta
{ name :: Ident
@@ -927,24 +941,34 @@ instance (CPA t) => ToRad t CmdSpec where
-- * Helpers
--- Loc is the source location of the application.
-callFn :: Monad m => Value -> [Value] -> Lang m Value
-callFn f vs = case f of
- Lambda bnds body closure ->
- if length bnds /= length vs
- then throwErrorHere $ WrongNumberOfArgs "lambda" (length bnds)
- (length vs)
- else do
- let mappings = GhcExts.fromList (Doc.noDocs $ zip bnds vs)
- modEnv = mappings <> closure
- NonEmpty.last <$> withEnv (const modEnv)
- (traverse baseEval body)
- PrimFn i -> do
- fn <- lookupPrimop i
- fn vs
- _ -> throwErrorHere $ NonFunctionCalled f
-
--- | Infix evaluation of application (of functions or special forms)
+-- | Call a lambda or primitvie function @f@ with @arguments@. @f@ and
+-- @argumenst@ are not evaluated.
+callFn :: forall m. Monad m => Value -> [Value] -> Lang m Value
+callFn f arguments = case f of
+ Lambda argNames body closure -> do
+ args <- argumentBindings argNames
+ evalManyWithEnv (args <> closure) body
+ LambdaRec self argNames body closure -> do
+ args <- argumentBindings argNames
+ let selfBinding = GhcExts.fromList (Doc.noDocs [(self, f)])
+ evalManyWithEnv (args <> selfBinding <> closure) body
+ PrimFn i -> do
+ fn <- lookupPrimop i
+ fn arguments
+ _ -> throwErrorHere $ NonFunctionCalled f
+ where
+ evalManyWithEnv :: Env Value -> NonEmpty Value -> Lang m Value
+ evalManyWithEnv env exprs =
+ NonEmpty.last <$> withEnv (const env) (traverse baseEval exprs)
+ argumentBindings :: [Ident] -> Lang m (Env Value)
+ argumentBindings names =
+ if length names /= length arguments
+ then throwErrorHere $ WrongNumberOfArgs "lambda" (length names) (length arguments)
+ else pure $ GhcExts.fromList (Doc.noDocs $ zip names arguments)
+
+-- | Process special forms or call function. If @f@ is an atom that
+-- indicates a special form that special form is processed. Otherwise
+-- @f@ and @vs@ are evaluated in 'callFn' is called.
infixr 1 $$
($$) :: Monad m => Value -> [Value] -> Lang m Value
f $$ vs = case f of
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index c7e9415..329d2a5 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -67,16 +67,18 @@ instance forall t. (Copointed t, Ann.Annotation t) => PrettyV (Ann.Annotated t V
Dict mp -> braces . align $
sep [ prettyV k <+> prettyV val
| (k, val) <- Map.toList mp ]
- Lambda ids vals _ ->
+ Lambda ids vals _ -> prettyLambda ids vals
+ LambdaRec _ ids vals _ -> prettyLambda ids vals
+ where
+ -- We print string literals escaped just like Haskell does.
+ escapeStr = T.init . T.tail . show
+ prettyLambda ids vals =
let args :: Ann.Annotated t ValueF = Vec $ Seq.fromList (Atom <$> ids)
in parens $
annotate TAtom "fn" <+>
align (sep [ prettyV args
, sep $ prettyV <$> toList vals
])
- where
- -- We print string literals escaped just like Haskell does.
- escapeStr = T.init . T.tail . show
instance Pretty Ann.SrcPos where
pretty (Ann.SrcPos pos) = pretty (sourcePosPretty pos)
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index fdf70b1..10112db 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -487,9 +487,18 @@ test_eval =
(triangular 10)
|]
runPureCode prog @?= Right (int 55)
+ , testCase "def-rec shadows previous definition" $ do
+ let prog = [s|
+ (def decrement #f)
+ (def-rec decrement
+ (fn [n]
+ (if (eq? n 0) 0 (decrement (- n 1)))))
+ (decrement 10)
+ |]
+ runPureCode prog @?= Right (int 0)
, testCase "def-rec errors when defining a non-function" $
- failsWith "(def-rec x 42)" (OtherError "def-rec can only be used to define functions")
+ failsWith "(def-rec x 42)" (OtherError "'def-rec' can only be used to define functions")
, testCase "stack traces work" $ do
let prog = [s|