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.hsindex ac98885..f9a27e8 100644--- a/exe/ReferenceDoc.hs+++ b/exe/ReferenceDoc.hs@@ -99,13 +99,16 @@ lPanic (Right r) _ = rvalueDoc :: 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.hsindex 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 = \caseHandle _ -> THandleProcHandle _ -> TProcHandleLambda{} -> TFunction+ LambdaRec{} -> TFunctionhashable :: (CPA t) => Annotated t ValueF -> Boolhashable = \case@@ -284,6 +291,7 @@ hashable = \caseHandle _ -> FalseProcHandle _ -> FalseLambda{} -> False+ LambdaRec{} -> FalseList xs -> all hashable xsVec xs -> all hashable xsDict 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)whereLambda 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 ValueFtype Value = Annotated Ann.WithPos ValueF@@ -722,10 +735,11 @@ specialForms = Map.fromList $ first Ident <$>val' <- baseEval valcase val' ofLambda 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 epure 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 Valuef $$ vs = case f ofdiff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex 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 VDict 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 . showinstance Pretty Ann.SrcPos wherepretty (Ann.SrcPos pos) = pretty (sourcePosPretty pos)diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 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" $ dolet prog = [s|