3 Commits
Author SHA1 Message Date
msyds 35e1b0cbe2 stupid
build / build (push) Failing after 1m24s
2026-08-30 10:31:46 -06:00
msyds 64641bb258 2026-08-30 05:39:13 -06:00
msyds 57b1cc830d wip: call/cc = capture/cc × invoke/cc 2026-08-30 03:33:51 -06:00
27 changed files with 449 additions and 925 deletions
-3
View File
@@ -9,9 +9,6 @@
. (progn (defun apply-cabal-fmt-h () . (progn (defun apply-cabal-fmt-h ()
(haskell-mode-buffer-apply-command "cabal-fmt")) (haskell-mode-buffer-apply-command "cabal-fmt"))
(add-hook 'before-save-hook #'apply-cabal-fmt-h nil t))))) (add-hook 'before-save-hook #'apply-cabal-fmt-h nil t)))))
(scheme-mode
. ((eval . (dolist (s '(kappa κ prim))
(put s 'scheme-indent-function 1)))))
(nil (nil
. ((eval . ((eval
. (progn (defun display-ansi () . (progn (defun display-ansi ()
-31
View File
@@ -132,34 +132,3 @@ multiple ~env-ref~ calls could probably be replaced with a primitive that loads
$code) $code)
1)))) 1))))
#+end_src #+end_src
** example
#+begin_src scheme
(λ (n m ktail)
(letrec ((f (λ (x ktail-0) (+ x n ktail-0)))
(g (λ (y ktail-1) (+ y g ktail-1))))
(prim (cons f g) ktail)))
#+end_src
#+begin_src scheme
(λ (n m ktail)
(letrec ((f-code (λ (x ktail-0)
(prim (env-get 2)
(κ (n)
(+ x n ktail-0)))))
(g-code (λ (y ktail-1)
(prim (env-get 3)
(κ (m)
(+ y m ktail-1))))))
(letrec ((with-closure-code
(κ (f g)
(prim (get-env 0)
(κ (ktail)
(prim cons f g ktail))))))
(prim (make-shared-closure (with-closure-code)
ktail)
(κ (with-closure)
(prim (make-shared-closure (f-code g-code) n m)
with-closure))))))
#+end_src
-2
View File
@@ -1,2 +0,0 @@
(let ((p (cons 123 456)))
(cons (cdr p) (car p)))
-2
View File
@@ -1,2 +0,0 @@
ret > ExitSuccess
out > 123
-1
View File
@@ -1 +0,0 @@
123
+3 -7
View File
@@ -58,16 +58,14 @@ library
-- cabal-fmt: expand src -- cabal-fmt: expand src
exposed-modules: exposed-modules:
Gyehoek.CPS.Close Gyehoek.CPS.Close
Gyehoek.CPS.Contify
Gyehoek.CPS.Convert Gyehoek.CPS.Convert
Gyehoek.CPS.Eval Gyehoek.CPS.Eval
Gyehoek.CPS.Hoist
Gyehoek.CPS.Stackify Gyehoek.CPS.Stackify
Gyehoek.CPS.Syntax Gyehoek.CPS.Syntax
Gyehoek.Driver Gyehoek.Driver
Gyehoek.Language
Gyehoek.GenSym Gyehoek.GenSym
Gyehoek.Jalmot Gyehoek.Jalmot
Gyehoek.Language
Gyehoek.Lift1 Gyehoek.Lift1
Gyehoek.Options Gyehoek.Options
Gyehoek.Prelude Gyehoek.Prelude
@@ -102,7 +100,6 @@ library
, hashable , hashable
, invertible-grammar , invertible-grammar
, lens , lens
, lucid
, megaparsec , megaparsec
, mtl , mtl
, optparse-applicative , optparse-applicative
@@ -110,7 +107,6 @@ library
, pretty-simple , pretty-simple
, prettyprinter , prettyprinter
, prettyprinter-ansi-terminal , prettyprinter-ansi-terminal
, prettyprinter-lucid
, process , process
, recursion-schemes , recursion-schemes
, scientific , scientific
@@ -121,7 +117,8 @@ library
, typed-process , typed-process
, unordered-containers , unordered-containers
, vector , vector
, tardis , lucid
, prettyprinter-lucid
hs-source-dirs: src hs-source-dirs: src
default-language: GHC2024 default-language: GHC2024
@@ -174,7 +171,6 @@ test-suite doctest
build-depends: build-depends:
, base , base
, gyehoek , gyehoek
default-extensions: CPP default-extensions: CPP
main-is: doctest.hs main-is: doctest.hs
+20 -37
View File
@@ -7,49 +7,32 @@ import Gyehoek.CPS.Syntax
import Data.List (nub) import Data.List (nub)
import Gyehoek.GenSym import Gyehoek.GenSym
import Gyehoek.Prelude import Gyehoek.Prelude
import Debug.Pretty.Simple
import Gyehoek.Sexp qualified as S
import Data.HashSet.Lens
import Data.Traversable
genCodeName :: GenSym :> es => Name -> Eff es Name close :: GenSym :> es => Exp -> Eff es Exp
genCodeName f = gensym' @Name $ f ^. _Wrapped' . to (<> "-code") close = transformM \case
ExpLetRec [(f, AbsLambda lam@(MkLambda bs kb m))] e -> do
bindEnv :: List Name -> Exp -> Exp f_code <- gensym' @Name $ f ^. _Wrapped' . to (<> "-code")
bindEnv frees m = [cps| -- it would probably be most sane to generate a symbol for `env`,
(prim (get-env) (κ #{frees} #{m})) -- but we're reusing the lambda binding so we don't have to
|] -- explicitly substitute recursive calls.
let frees = nub $ free' lam
close1 :: forall es. GenSym :> es => Exp -> Eff es Exp let m' = ifoldr
close1 = \case (\n x q ->
lr@(ExpLetRec bs e) -> do let p = if x == f then PrimEnv @Val else PrimEnvRef n
let boundNames = bs ^.. each . _1 in [cps|
let boundNames' = setOf each boundNames (prim #{p}
let frees = bs (κ (#{x}) #{q}))
& foldMapOf |])
(each . _2) m frees
(freeWithBound' boundNames')
& nub
env_cont_l <- gensym' @Name "env-cont"
e_l <- gensym' @Name "letrec-body-cont"
bs' <- for bs \(f,ab) -> do
f_code_l <- genCodeName f
pure ( f_code_l
, ab & absBody %~ bindEnv (boundNames ++ frees)
)
let codes = bs' ^.. each . _1 . to MkLabel
pure [cps| pure [cps|
(letrec #{bs'} (letrec ((#{f_code} (λ (##{bs} #{kb})
(prim (make-shared-closure #{codes} #{frees}) #{m'})))
(κ #{boundNames} (prim (make-closure #{f_code} ##{frees})
#{e}))) (κ (#{f}) #{e})))
|] |]
e -> pure e e -> pure e
close :: forall es. GenSym :> es => Exp -> Eff es Exp
close = transformM close1
closeProgram :: GenSym :> es => Program -> Eff es Program closeProgram :: GenSym :> es => Program -> Eff es Program
closeProgram = traverseOf (#body . #body) close closeProgram = traverseOf (#body . #body) close
-67
View File
@@ -1,67 +0,0 @@
{-# LANGUAGE ApplicativeDo #-}
module Gyehoek.CPS.Contify
( contifyProgram
) where
import Control.Monad.Tardis
import Gyehoek.CPS.Syntax
import Gyehoek.Prelude
import qualified Data.HashSet as HS
import Control.Lens.Unsound (adjoin)
import Debug.Pretty.Simple
import qualified Data.HashMap.Strict as H
import Control.Monad.Writer.Lazy
import Control.Monad.Trans.Tardis (liftTardisT)
-- | ain't no way...
-- type T = WriterT (HashSet Name) (Tardis (HashSet Name) (HashSet Name))
type T = TardisT (HashSet Name) (HashSet Name) (Writer (HashSet Name))
evalT :: T a -> a
-- evalT = (`evalTardis` (mempty,mempty)) . fmap fst . runWriterT
evalT = fst . runWriter . (`evalTardisT` (mempty,mempty))
runT :: T a -> (a, HashSet Name)
-- runT = (`evalTardis` (mempty,mempty)) . runWriterT
runT = runWriter . (`evalTardisT` (mempty,mempty))
-- | inline function if it hasn't been used in the past, and won't
-- be used in the future.
tryInline :: Name -> Kappa -> T Kexp
tryInline kname kap = do
modifyBackwards (HS.insert kname)
p <- getsPast (HS.member kname)
modifyForwards (HS.insert kname)
q <- getsFuture (HS.member kname)
let c = p || q
liftTardisT . tell $ if c then HS.singleton kname else mempty
pure $ if c
then KexpVar kname
else KexpKappa kap
getKap :: HashMap Name Abs -> Name -> Maybe Kappa
getKap g kname = g ^? ix kname . #AbsKappa
contify :: HashMap Name Abs -> Exp -> T Exp
contify g = transformM \case
ExpApply f xs (KexpVar kname) | Just kap <- getKap g kname
-> ExpApply f xs <$> tryInline kname kap
ExpPrim p (KexpVar kname) | Just kap <- getKap g kname
-> ExpPrim p <$> tryInline kname kap
e -> pure e
contifyProgram :: HoistedProgram -> Eff es HoistedProgram
contifyProgram p = do
let g = p.bindings
let (p',contifiedVars) =
runT $
traverseOf
(adjoin
(#bindings . each . body)
(#body . body))
(contify g)
p
pTraceShowM contifiedVars
-- pure $ p' & #bindings %~ H.filterWithKey \k _ -> HS.member k contifiedVars
pure p'
+25 -22
View File
@@ -46,18 +46,29 @@ convert (Scm.ExpLit l) k = k . one . ValImm $ case l of
LitBool b -> ImmBool b LitBool b -> ImmBool b
_ -> _ _ -> _
-- special case: call/cc is desugared during cps-conversion...
-- convert (Scm.ExpPrim (PrimCallCC withcc)) k = do
-- convert1 withcc \withcc' -> do
-- cc_l <- gensym' @Name "cc"
-- r1_l <- gensym' @Name "r"
-- r2_l <- gensym' @Name "r"
-- ccish_l <- gensym' @Name "ccish"
-- reified_cc_l <- gensym' @Name "reified-cc"
-- m <- k [ValVar r1_l]
-- pure [cps|
-- (letrec ((#{cc_l} (κ (#{r1_l})
-- #{m})))
-- (prim (capture/cc)
-- (κ (#{reified_cc_l})
-- (#{withcc'} #{reified_cc_l} #{cc_l}))))
-- |]
-- ...while all other prims are left as-is for later stages to
-- handle..
convert (Scm.ExpPrim p) k = convert (Scm.ExpPrim p) k =
telescope (convert1 @es) p \p' -> do telescope (convert1 @es) p \p' -> do
r_l <- gensym' "r" r <- gensym' "r"
-- k_l <- gensym' @Name "prim-k" ExpPrim p' . MkKappa [r] <$> k [ValVar r]
m <- k [ValVar r_l]
pure [cps|
(prim #{p'} (κ (#{r_l}) #{m}))
|]
-- pure [cps|
-- (letrec ((#{k_l} (κ (#{r_l}) #{m})))
-- (prim #{p'} #{k_l}))
-- |]
convert (Scm.ExpLambda xs e) k = do convert (Scm.ExpLambda xs e) k = do
f <- gensym' "lambda-body" f <- gensym' "lambda-body"
@@ -70,25 +81,17 @@ convert (Scm.ExpLambda xs e) k = do
convert (Scm.ExpApply f xs) k = convert (Scm.ExpApply f xs) k =
telescope (convert1 @es) (f:|xs) \(f':|xs') -> do telescope (convert1 @es) (f:|xs) \(f':|xs') -> do
r <- gensym' @Name "r" r <- gensym' "r"
x <- gensym' "x" x <- gensym' "x"
m <- k [ValVar x] m <- k [ValVar x]
pure $ ExpLetRec [(r, AbsKappa' [x] m)] $ pure $ ExpLetRec [(r, AbsKappa' [x] m)] $
ExpApply f' xs' (KexpVar r) ExpApply f' xs' r
convert (Scm.ExpBegin xs) k = telescope (convert @es) xs (k . NE.last) convert (Scm.ExpBegin xs) k = telescope (convert @es) xs (k . NE.last)
convert (Scm.ExpIf c t f) k = convert (Scm.ExpIf c t f) k =
convert1 c \c' -> do convert1 c \c' ->
t_l <- gensym' @Name "truthy-cont" ExpIf c' <$> convert t k <*> convert f k
f_l <- gensym' @Name "falsey-cont"
t' <- convert t k
f' <- convert f k
pure [cps|
(letrec ((#{t_l} (κ () #{t'}))
(#{f_l} (κ () #{f'})))
(if #{c'} #{t_l} #{f_l}))
|]
-- let-bindings are desugared into continuation calls whose parameters -- let-bindings are desugared into continuation calls whose parameters
-- are the left-hand sides and whose arguments are the right-hand -- are the left-hand sides and whose arguments are the right-hand
+72 -232
View File
@@ -1,259 +1,99 @@
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedLists #-}
module Gyehoek.CPS.Eval module Gyehoek.CPS.Eval
( evalProgram ( evalProgram
, module Gyehoek.CPS.Syntax , module Gyehoek.CPS.Syntax
, evalExp , evalExp
, eGrammar
) where ) where
import Gyehoek.CPS.Syntax hiding (Hob(..), Obj(..), cont) import Gyehoek.CPS.Syntax
import Gyehoek.Sexp qualified as S import Control.Lens
import Control.Lens hiding (assign)
import Data.Maybe (fromMaybe) import Data.Maybe (fromMaybe)
import Text.Show.Functions () import Text.Show.Functions ()
import qualified Data.HashMap.Strict as H import qualified Data.HashMap.Strict as H
import Gyehoek.Prelude hiding (assign) import Gyehoek.Prelude
import Debug.Pretty.Simple import Debug.Pretty.Simple
import Gyehoek.Jalmot
import Control.Monad.Cont
import Gyehoek.Sexp qualified as S
import GHC.Generics (Generically(..))
import Gyehoek.Sexp ((:-)(..))
import Data.List (nub, mapAccumR, compareLength)
import Data.HashSet.Lens (setOf)
import Data.IntMap.Strict (IntMap)
import Data.IntMap.Strict qualified as IM
import Data.Monoid
import Control.Monad.State
import Data.Traversable (for)
import Data.Foldable (traverse_)
newtype Loc = MkLoc { getLoc :: Int } data Env = MkEnv
deriving stock (Generic, Data) { vars :: HashMap Name Obj
deriving newtype (Show, Eq, Ord, Enum) , labels :: HashMap Name (Env, Abs)
data Store = MkStore
{ nextLoc :: Loc
, heap :: IntMap E
} }
deriving stock (Show, Generic)
type instance Index Store = Loc
type instance IxValue Store = E
instance Ixed Store where ix (MkLoc j) = #heap . ix j
instance At Store where at (MkLoc j) = #heap . at j
emptyStore :: Store
emptyStore = MkStore
{ nextLoc = MkLoc 0
, heap = mempty
}
newtype Env = MkEnv { getEnv :: HashMap Name Loc }
deriving stock (Show, Generic, Data)
deriving newtype (Semigroup, Monoid)
emptyEnv :: Env
emptyEnv = mempty
type instance Index Env = Name
type instance IxValue Env = Loc
instance Ixed Env where ix j = #getEnv . ix j
instance At Env where at j = #getEnv . at j
update :: Loc -> E -> Store -> Store
update (MkLoc loc) v = #heap %~ IM.alter f loc
where
f (Just _) = Just v
f Nothing = error "segfault lol"
updates :: Foldable f => f (Loc, E) -> Store -> Store
updates = alaf Endo foldMap (uncurry update)
fetch :: Loc -> M r E
fetch (MkLoc loc) = gets (^?! #heap . ix loc)
new :: M r Loc
new = state \st -> (st.nextLoc, st & #nextLoc %~ succ)
new' :: E -> M r Loc
new' e = state \st ->
( st.nextLoc
, st & #nextLoc %~ succ & at st.nextLoc ?~ e
)
defines :: Traversable t => t (Name, E) -> M Answer Env
defines = alaf Ap foldMap \(name,e) -> do
l <- new' e
pure $ bind name l
var :: HasCallStack => Env -> Name -> M Answer Loc
var g x = case g ^. at x of
Just l -> pure l
Nothing -> wrong [i|unbound variable #{x}|]
type CmdCont = Store -> Answer
type ExpCont = List E -> CmdCont
type M r = ContT r (State Store)
data Answer
= AnswerValues (List E)
| AnswerError AJalmot
deriving (Show, Generic) deriving (Show, Generic)
data Mutability eval :: Env -> Exp -> List Obj
= Mut
| NoMut
deriving (Show, Generic, Data, Eq)
wrong :: Text -> M Answer a eval g (Halt xs) = evalVal g <$> xs
wrong s = ContT \_ -> pure . AnswerError . EvalError $ s
bind :: Name -> Loc -> Env eval g (ExpContinue k xs) =
bind k = MkEnv . H.singleton k case g ^. #labels . at k' of
Just (h, AbsKappa' bs m) -> eval h' m
extends :: Foldable f => f (Name, Loc) -> Env -> Env where
extends xs g = g <> foldMap (uncurry bind) xs h' = h & #vars <>~ envOfBinds bs (evalVal g <$> xs)
_ -> error [i|not a kappa: #{k}|]
assign :: Loc -> E -> M Answer ()
assign l e = do
use (at l) >>= \case
Just _ -> at l ?= e
Nothing -> wrong [i|#{e} #{l} |]
-- | The denotation of an expressed value.
data E
= ESymbol Text
| ECharacter Char
| EInt Int
| EBool Bool
| EUndefined
| EUnspecified
| ENull
| EPair Loc Loc Mutability
| EVec (List Loc) Mutability
| EString (List Loc) Mutability
| EProcedure Procedure
deriving stock (Show, Generic)
type Procedure = List E -> DynPoints -> M Answer (List E)
eGrammar :: Store -> S.DatumGrammar E
eGrammar st = S.partialOsi (const . Left $ mempty) go
where where
gofetch x = go $ st ^?! ix x k' = case evalVal g k of
go = \case ObjImm (ImmLabel x) -> x
ESymbol s -> S.Symbol s x -> error [i|expected label, got #{x}|]
ECharacter c -> S.Character c
EInt n -> S.Number (fromIntegral n)
EBool b -> S.Boolean b
EUndefined -> S.Unreadable "#<undefined>"
EUnspecified -> S.Unreadable "#<unspecified>"
ENull -> S.List []
EPair car cdr _mut -> S.DotList [gofetch car] (gofetch cdr)
EVec xs _mut -> S.Vector . fmap gofetch $ xs
EString xs _mut -> S.String _
data DynPoints = MkDynPoints eval g (ExpApply f xs ktail) =
deriving (Generic, Data) case g ^?! #labels . at f' of
Just (h,AbsLambda' bs kb m) -> eval h' m
where h' = h & #vars <>~ envOfBinds bs (evalVal g <$> xs)
& #labels . at kb .~ (g ^. #labels . at ktail)
evalVal :: Env -> Val -> M Answer E Nothing -> error [i|undefined label: #{f}|]
evalVal g (ValVar x) = var g x >>= fetch
evalVal g (ValImm imm) = pure case imm of
ImmLabel l -> error [i|#{l}|]
ImmInt n -> EInt n
ImmBool b -> EBool b
ImmUndefined -> EUndefined
evalKexp :: Env -> Kexp -> M Answer E
evalKexp g (KexpVar x) = var g x >>= fetch
evalKexp g (KexpKappa kap) = evalAbs g (AbsKappa kap)
evalAbs :: Env -> Abs -> M Answer E
evalAbs g (MkAbs formals ktail e) = pure . EProcedure $ \xs dps ->
let
formals' = formals ++ foldMap (:[]) ktail
lformals = length formals'
lxs = length xs
in if lformals /= lxs
then wrong [i| #{lformals} #{lxs} .|]
else do
ls <- xs & traverse new'
let g' = g & extends (zip formals' ls)
eval g' dps e
eval :: Env -> DynPoints -> Exp -> M Answer (List E)
eval g dps (ExpJump f xs ktail) = do
f' <- evalVal g f
xs' <- traverse (evalVal g) xs
ktail' <- traverse (evalKexp g) (ktail ^.. _Just)
case f' of
EProcedure p -> p (xs' ++ ktail') dps
_ -> wrong "bad procedure"
eval g dps (ExpLetRec bs e) = do
ls <- for bs . const $ new' EUndefined
let g' = g & extends (zip (bs ^.. each . _1) ls)
bs' <- forOf (each . _2) bs (evalAbs g')
traverse_ (uncurry assign) $ zip ls (bs' ^.. each . _2)
eval g' dps e
eval g dps (ExpPrim p k) = do
p' <- evalPrim g =<< traverse (evalVal g) p
evalKexp g k >>= \case
EProcedure fp -> fp p' dps
_ -> wrong [i|prim(#{p}) |]
eval g dps e = error [i|unimplemented #{e}|]
evalPrim :: Env -> Prim E -> M Answer (List E)
evalPrim g = \case
PrimAdd x y -> arith2 (+) x y
PrimMul x y -> arith2 (*) x y
PrimSub x y -> arith2 (-) x y
PrimDiv x y -> arith2 div x y
PrimValues xs -> pure xs
p -> wrong [i|prim(#{p}) |]
where where
arith2 f (EInt x) (EInt y) = pure [EInt $ f x y] f' = case evalVal g f of
arith2 f x y = wrong [i| : #{x}, #{y}|] ObjImm (ImmLabel x) -> x
x -> error [i|expected label, got #{x}|]
eval g (ExpLetRec [(b, ab)] e) = eval g' e
where g' = g & #labels . at b ?~ ab
evalExp :: Jalmot :> es => Exp -> Eff es _ eval g (ExpPrim p (MkKappa bs e)) = case evalVal g <$> p of
evalExp e = _ PrimAdd x y -> arithBinop (+) x y
PrimMul x y -> arithBinop (*) x y
evalProgram :: Jalmot :> es => Program -> Eff es (List S.Datum) PrimSub x y -> arithBinop (-) x y
evalProgram (MkProgram lam) = case run (pure . AnswerValues) of PrimDiv x y -> arithBinop div x y
(AnswerError jm, _) -> throwError jm PrimMakeClosure x env -> ret [ObjHob (HobClosure lbl env) ]
(AnswerValues vs, st) -> traverse (S.toDatum $ eGrammar st) vs where
lbl = case x of
ObjImm (ImmLabel l) -> l
_ -> error [i|expected label, got #{x}|]
_ -> error [i|unhandled prim: #{p}|]
where where
run f = (`runState` emptyStore) . (`runContT` f) $ do ret rs = eval
g <- setup (g & #vars <>~ envOfBinds bs rs)
eval g MkDynPoints (ExpLetRec e
[("_start",AbsLambda lam)] arithBinop f (ObjImm (ImmInt x)) (ObjImm (ImmInt y)) =
(ExpApply (ValVar "_start") [] (KexpVar "halt"))) ret [ObjImm . ImmInt $ f x y]
arithBinop _ x y = error [i|bad arith: #{x}, #{y}|]
eval _ e = error [i|unimplemented case: #{e}|]
setup :: M Answer Env envOfBinds bs xs = foldMap (uncurry H.singleton) (zip bs xs)
setup = defines @List
[ ("halt", EProcedure prim_halt)
]
prim_halt :: Procedure evalVal :: Env -> Val -> Obj
prim_halt xs _dps = ContT \_ -> pure $ AnswerValues xs evalVal g = \case
ValVar x -> fromMaybe (error [i|unbound: #{x}|]) $ g ^?! #vars . at x
ValImm x -> ObjImm x
emptyEnv :: Env
emptyEnv = MkEnv
{ vars = mempty
-- a kinda silly hack to make sure `halt` is handled correctly when
-- it appears as the tail continuation of an application. the
-- special case of `eval` responsible for `halt` only covers terms
-- of the form `(continue $halt xs …)`; other terms such as
-- `($some-fn xs $halt)` just see an undefined label `$halt`.
, labels = H.singleton "halt" $
AbsKappa' ["h0"] $ Halt [ValVar "h0"]
}
evalExp :: Exp -> List Obj
evalExp = eval emptyEnv
evalProgram :: Program -> List Obj
evalProgram (MkProgram lam) = eval emptyEnv [cps|
(letrec ((start #{lam}))
(start halt))
|]
-24
View File
@@ -1,24 +0,0 @@
module Gyehoek.CPS.Hoist
( hoistProgram
) where
import Gyehoek.CPS.Syntax
import Gyehoek.Prelude
import qualified Data.HashMap.Strict as H
import Effectful.Writer.Static.Local
import Data.Foldable
type Hoist = Writer (HashMap Label Abs)
hoist :: Hoist :> es => Exp -> Eff es Exp
hoist = transformM \case
ExpLetRec bs m -> do
traverse_ (\(k,v) -> tell $ H.singleton (MkLabel k) v) bs
pure m
e -> pure e
hoistProgram :: Program -> Eff es HoistedProgram
hoistProgram p = do
(body,bindings) <- runWriter $ traverseOf #body hoist p.body
pure $ MkHoistedProgram {body,bindings}
+148 -114
View File
@@ -12,14 +12,24 @@ import Gyehoek.GenSym
import Effectful.Writer.Static.Shared import Effectful.Writer.Static.Shared
import Data.Foldable import Data.Foldable
import qualified Data.HashMap.Strict as H import qualified Data.HashMap.Strict as H
import Data.List (elemIndex, nub, intersect) import Data.List (elemIndex, nub)
import Data.Text qualified as T import Data.Text qualified as T
import Gyehoek.Prelude import Gyehoek.Prelude
import Debug.Pretty.Simple import Debug.Pretty.Simple
import qualified Gyehoek.Sexp as S import qualified Gyehoek.Sexp as S
import Data.Monoid
type Stackify = Writer Stk.Program
runStackify :: Eff (Stackify : es) a -> Eff es (a, Stk.Program)
runStackify = runWriter
live :: Free a => Env -> a -> List Name
-- TODO: free' should return an OSet lol
live g e = nub (free' e) & filter \x ->
x `elem` g.bound
-- && not (x `elem` g.contStack)
data BlockBuilder data BlockBuilder
= Code (List Stk.Instr) BlockBuilder = Code (List Stk.Instr) BlockBuilder
| Tail Stk.Tail | Tail Stk.Tail
@@ -30,137 +40,161 @@ buildBlock = go [] where
go acc (Code xs bb) = go (acc ++ xs) bb go acc (Code xs bb) = go (acc ++ xs) bb
go acc (Tail t) = Stk.MkBlock acc t go acc (Tail t) = Stk.MkBlock acc t
emitRoutine :: Stackify :> es => Stk.Routine -> Eff es ()
emitRoutine rt = tell [rt]
stackify
:: (GenSym :> es, Stackify :> es)
=> Env -> Exp -> Eff es BlockBuilder
stackify g (ExpLetRec [(f, AbsKappa kap)] e) = do
kap' <- stackifyKappa g kap
emitRoutine . Stk.MkRoutine (MkLabel f) . buildBlock $ kap'
stackify g e
stackify g (ExpLetRec [(f, AbsLambda lam)] e) = do
lam' <- stackifyLambda g (MkLabel f) lam
emitRoutine lam'
stackify g e
stackify g (ExpIf c t f) = do
let c' = stackifyVal g c
t' <- buildBlock <$> stackify g t
f' <- buildBlock <$> stackify g f
pure . Tail $ Stk.If c' t' f'
stackify g (ExpApply f xs ktail) = do
pure $
Code [ Stk.Push $ stackifyVal g (ValVar ktail)
, Stk.Push $ stackifyVal g f
] $
Code (pushArgs g xs) $
Tail (Stk.Call (length xs))
stackify g e@(ExpContinue k xs)
| isn't (#_ValVar . only g.tail) k = pure $
Code [ Stk.Push (stackifyVal g k) ] $
Code (pushArgs g xs) $
Tail $ Stk.TailCall (length xs)
| otherwise = pure $
Code (pushArgs g xs) $
Tail (Stk.Return (length xs))
stackify g (ExpPrim (PrimCallCC withcc) cc) = do
cc' <- stackifyKappa g cc
cc_l <- gensym' @Label "cc"
emitRoutine . Stk.MkRoutine cc_l . buildBlock $ cc'
pure $
Code [ Stk.Push $ stackifyVal g withcc
, Stk.Push $ stackifyVal g (ValLabel cc_l)
] $
Tail Stk.CallCC
stackify g (ExpPrim p kap) = do
kap' <- stackifyKappa g kap
pure $ Code [ Stk.Prim (stackifyVal g <$> p) ] kap'
stackify _ e = error [i|unimplemented exp: #{e}|]
loadArgs :: List Name -> List Stk.Instr
loadArgs = imapOf itraversed \n x -> Stk.Load (MkReg x) n
pushArgs :: Env -> List Val -> List Stk.Instr
pushArgs g args = [ Stk.Push $ stackifyVal g x | x <- reverse args ]
-- affine -- affine
_ValName :: Traversal' Val Name _ValName :: Traversal' Val Name
_ValName = failing #_ValVar (#_ValImm . #_ImmLabel . #_MkLabel) _ValName = failing #_ValVar (#_ValImm . #_ImmLabel . #_MkLabel)
stackify stackifyKappa
:: forall es. (GenSym :> es) :: (Stackify :> es, GenSym :> es)
=> Env -> Exp -> Eff es BlockBuilder => Env -> Kappa
-> Eff es BlockBuilder
stackifyKappa g (MkKappa xs m) = do
let g' = g & #bound <>:~ xs
Code (loadArgs g'.bound)
<$> stackify g' m
stackify _ (ExpContinue (ValVar k) xs) = stackifyLambda
Code [ ] _ :: (Stackify :> es, GenSym :> es)
=> Env -> Label -> Lambda
-> Eff es Stk.Routine
stackifyLambda g name (MkLambda xs k m) = do
m' <- stackify (g & #bound .~ xs & #tail .~ k) m
pure $
Stk.MkRoutine name . buildBlock $
Code (loadArgs xs) $
Code [Stk.Load (MkReg k) (length xs + 1)] m'
stackify _ (ExpPrim p k) = _ stackifyVal :: Env -> Val -> Stk.Val
stackifyVal g = \case
ValImm imm -> Stk.ValImm imm
ValVar v -> case regOf g v of
Just r -> Stk.ValReg r
Nothing -> Stk.ValLabel (MkLabel v)
v -> error [i|unimplemented val: #{v}|]
stackify _ e = error [i|unimplemented exp: #{e}|] regOf :: Env -> Name -> Maybe Reg
regOf g x
stackifyAbs :: (GenSym :> es) => Env -> Label -> Abs -> Eff es Stk.Routine | x `elem` g.bound || x == g.tail = Just . MkReg $ x
| otherwise = Nothing
stackifyAbs g lbl (MkAbs xs mtail e) =
Stk.MkRoutine lbl . buildBlock . preamble <$> stackify g e
where
preamble = Code (popArgs $ (mtail ^.. _Just) ++ xs)
popArgs :: List Name -> List Stk.Instr
popArgs = fmap (Stk.Pop . MkReg) . reverse
pushArgs :: List Name -> List Stk.Instr
pushArgs = _
data Env = MkEnv data Env = MkEnv
{ -- | `bound` tracks the stack lifetime of bound variables.
{ bound :: List Name
-- | for each locally-bound continuation @k@, @liveness@ has an
-- entry @(k,ls)@ where @ls@ is the sequence of registers @k@
-- expects to find saved on the stack.
, liveness :: HashMap Label (List Name)
, tail :: Name
} }
deriving (Show, Generic) deriving (Show, Generic)
emptyEnv :: Env emptyEnv :: Env
emptyEnv = MkEnv emptyEnv = MkEnv
{ { bound = mempty
, liveness = mempty
, tail = "halt"
} }
stackifyProgram stackifyProgram :: GenSym :> es => Program -> Eff es Stk.Program
:: forall es. GenSym :> es stackifyProgram (MkProgram lam) = do
=> HoistedProgram -> Eff es Stk.Program let g = emptyEnv
stackifyProgram p = p (_,p) <- runStackify $ emitRoutine =<< stackifyLambda g "start" lam
& ifoldMapOf pure p
((#bindings . itraversed)
<> (#body . to (H.singleton "start" . AbsLambda) . itraversed))
(\l -> Ap . stackifyBinding l)
& getAp
where
g = emptyEnv
stackifyBinding lbl ab =
Stk.MkProgram . H.singleton lbl <$> stackifyAbs @es g lbl ab
p :: HoistedProgram letfn :: Program
p = [cps| letfn = [cps|
(letrec (($r12-code32 (λ (start-ktail0)
(κ (x13) (letrec ((lambda-body1
(prim (λ (x lambda-tail2)
(get-env) (prim (* x x) (κ (r3) (continue lambda-tail2 r3))))))
(κ (r12 start-ktail0) (letrec ((let-body6
(continue start-ktail0 x13))))) (κ (square)
($prim-k7-code22 (letrec ((r4 (κ (x5) (continue start-ktail0 x5))))
(κ (r6) (square 4 r4)))))
(prim (continue let-body6 lambda-body1))))
(get-env) |]
(κ (prim-k7 lambda-tail1 n fac)
(prim blah :: Program
(make-shared-closure ($r8-code19) (lambda-tail1 n)) blah = [cps|
(κ (r8) (λ (ktail0)
(fac r6 r8))))))) (letrec ((fac (λ (n ktail)
($prim-k11-code16 (prim (zero? n)
(κ (r10) (κ (x0)
(prim (if x0
(get-env) (continue ktail 1)
(κ (prim-k11 lambda-tail1) (prim (- n 1)
(continue lambda-tail1 r10))))) (κ (x1)
($falsey-cont5-code26 (letrec ((fac-k0
(κ () (κ (x2)
(prim (prim (* n x2)
(get-env) (κ (x3)
(κ (truthy-cont4 falsey-cont5 lambda-tail1 n fac) (continue ktail x3))))))
(prim (fac x1 fac-k0))))))))))
(make-shared-closure ($prim-k7-code22) (lambda-tail1 n fac)) (fac 6 halt)))
(κ (prim-k7)
(prim (- n 1) prim-k7)))))))
($r8-code19
(κ (x9)
(prim
(get-env)
(κ (r8 lambda-tail1 n)
(prim
(make-shared-closure ($prim-k11-code16) (lambda-tail1))
(κ (prim-k11)
(prim (* n x9) prim-k11)))))))
($truthy-cont4-code25
(κ ()
(prim
(get-env)
(κ (truthy-cont4 falsey-cont5 lambda-tail1 n fac)
(continue lambda-tail1 1)))))
($fac-code35
(λ (n lambda-tail1)
(prim
(get-env)
(κ (fac)
(prim
(make-shared-closure ($prim-k3-code29) (lambda-tail1 n fac))
(κ (prim-k3)
(prim (zero? n) prim-k3)))))))
($prim-k3-code29
(κ (r2)
(prim
(get-env)
(κ (prim-k3 lambda-tail1 n fac)
(prim
(make-shared-closure
($truthy-cont4-code25 $falsey-cont5-code26)
(lambda-tail1 n fac))
(κ (truthy-cont4 falsey-cont5)
(if r2
truthy-cont4
falsey-cont5))))))))
(λ (start-ktail0)
(prim
(make-shared-closure ($fac-code35) ())
(κ (fac)
(prim
(make-shared-closure ($r12-code32) (start-ktail0))
(κ (r12)
(fac 20 r12)))))))
|] |]
+25 -137
View File
@@ -10,12 +10,10 @@ module Gyehoek.CPS.Syntax
, Kappa(..) , Kappa(..)
, Lambda(..) , Lambda(..)
, Exp(..) , Exp(..)
, Kexp(..)
, ExpF(..) , ExpF(..)
, Name(..) , Name(..)
, Prim(..) , Prim(..)
, Program(..) , Program(..)
, HoistedProgram(..)
, Lit(..) , Lit(..)
, Imm(..) , Imm(..)
, Obj(..) , Obj(..)
@@ -41,12 +39,6 @@ module Gyehoek.CPS.Syntax
, Free(..) , Free(..)
, pattern ValLabel , pattern ValLabel
, pattern ObjLabel , pattern ObjLabel
, absBody
, pattern MkAbs
, _MkAbs
, unhoist
, pattern ExpJump
, _ExpJump
) )
where where
@@ -64,10 +56,6 @@ import Gyehoek.Sexp (G, (:-)(..))
import qualified Data.InvertibleGrammar.Base as IG import qualified Data.InvertibleGrammar.Base as IG
import Gyehoek.GenSym (Gen) import Gyehoek.GenSym (Gen)
import Data.String (IsString) import Data.String (IsString)
import Control.Applicative
import qualified Data.HashMap.Strict as H
import GHC.Records (HasField (..))
import Data.Bifunctor
-- Data types -- Data types
@@ -125,60 +113,24 @@ data Abs
| AbsLambda Lambda | AbsLambda Lambda
deriving (Show, Generic, Data, Eq) deriving (Show, Generic, Data, Eq)
pattern AbsKappa' :: List Name -> Exp -> Abs pattern AbsKappa' :: [Name] -> Exp -> Abs
pattern AbsKappa' xs e = AbsKappa (MkKappa xs e) pattern AbsKappa' xs e = AbsKappa (MkKappa xs e)
pattern AbsLambda' :: List Name -> Name -> Exp -> Abs pattern AbsLambda' :: [Name] -> Name -> Exp -> Abs
pattern AbsLambda' xs e ktail = AbsLambda (MkLambda xs e ktail) pattern AbsLambda' xs e ktail = AbsLambda (MkLambda xs e ktail)
{-# COMPLETE AbsKappa', AbsLambda' #-}
_MkAbs :: Iso' Abs (List Name, Maybe Name, Exp)
_MkAbs = iso
(\case
AbsKappa' xs e -> (xs,Nothing,e)
AbsLambda' xs ktail e -> (xs,Just ktail,e))
(\(xs,ktail,e) -> case ktail of
Just k -> AbsLambda' xs k e
Nothing -> AbsKappa' xs e)
pattern MkAbs :: List Name -> Maybe Name -> Exp -> Abs
pattern MkAbs xs ktail body <- (view _MkAbs -> (xs,ktail,body))
where MkAbs xs ktail body = review _MkAbs (xs,ktail,body)
{-# COMPLETE MkAbs #-}
_ExpJump :: Prism' Exp (Val, List Val, Maybe Kexp)
_ExpJump = prism'
(\(f,xs,ktail) -> case ktail of
Just k -> ExpApply f xs k
Nothing -> ExpContinue f xs)
\case
ExpApply f xs ktail -> Just (f,xs,Just ktail)
ExpContinue f xs -> Just (f,xs,Nothing)
_ -> Nothing
pattern ExpJump :: Val -> List Val -> Maybe Kexp -> Exp
pattern ExpJump f xs ktail <- (preview _ExpJump -> Just (f,xs,ktail))
where ExpJump f xs ktail = review _ExpJump (f,xs,ktail)
data Exp data Exp
= ExpPrim (Prim Val) Kexp = ExpPrim (Prim Val) Kappa
| ExpLetRec { binders :: List (Name, Abs), body :: Exp } | ExpLetRec { binders :: List (Name, Abs), body :: Exp }
| ExpContinue Val (List Val) | ExpContinue Val (List Val)
| ExpIf Val Name Name | ExpIf Val Exp Exp
| ExpApply | ExpApply
{ op :: Val { op :: Val
, args :: List Val , args :: List Val
, cont :: Kexp , cont :: Name
} }
deriving (Show, Generic, Data, Eq) deriving (Show, Generic, Data, Eq)
data Kexp
= KexpVar Name
| KexpKappa Kappa
deriving (Show, Generic, Data, Eq)
pattern Halt :: List Val -> Exp pattern Halt :: List Val -> Exp
pattern Halt xs = ExpContinue (ValLabel "halt") xs pattern Halt xs = ExpContinue (ValLabel "halt") xs
@@ -193,22 +145,6 @@ data Program = MkProgram
} }
deriving (Show, Generic, Data) deriving (Show, Generic, Data)
data HoistedProgram = MkHoistedProgram
{ bindings :: HashMap Label Abs
, body :: Lambda
}
deriving stock (Show, Generic, Data)
type instance Index HoistedProgram = Label
type instance IxValue HoistedProgram = Abs
instance Ixed HoistedProgram where ix j = #bindings . ix j
instance At HoistedProgram where at j = #bindings . at j
instance Each HoistedProgram HoistedProgram Abs Abs where
each = #bindings . each
makePrisms ''Kappa makePrisms ''Kappa
makePrisms ''Exp makePrisms ''Exp
makeFieldsId ''Exp makeFieldsId ''Exp
@@ -232,21 +168,6 @@ _AbsLambda' = prism'
instance Plated Exp where plate = uniplate instance Plated Exp where plate = uniplate
absBody :: Lens' Abs Exp
absBody = lens
(\case
AbsLambda lam -> lam.body
AbsKappa kap -> kap.body)
(\cases
(AbsLambda lam) b -> AbsLambda $ lam & #body .~ b
(AbsKappa kap) b -> AbsKappa $ kap & #body .~ b)
unhoist :: HoistedProgram -> Program
unhoist p =
MkProgram $ p.body & body %~ ExpLetRec
(p ^.. #bindings . itraversed . withIndex
. to (\(MkLabel l, ab) -> (l,ab)))
-- DatumIso instances -- DatumIso instances
@@ -350,51 +271,30 @@ instance S.DatumIso Exp where
if_ = S.ifLike "if" if_ = S.ifLike "if"
S.datumIso S.datumIso S.datumIso S.datumIso S.datumIso S.datumIso
app :: forall t. app :: forall t.
G (Datum :- t) (Kexp :- List Val :- Val :- t) G (Datum :- t) (Name :- ([Val] :- (Val :- t)))
app = S.list $ app = S.list $ S.el (S.datumIso @Val)
S.flipped (S.PartialIso -- >>> S.flipped Gyehoek.Datum.nonEmptyGrammar
(\(S.MkListContext ctx :- t) ->
case ctx of
f:kexp:xs -> S.MkListContext (f : snoc xs kexp) :- t
_ -> error "unreachable")
(\(S.MkListContext ctx :- t) ->
case unsnoc ctx of
Just (f:xs,kexp) -> Right $ S.MkListContext (f:kexp:xs) :- t
_ -> Left $ S.expected "continuation arg"))
>>> S.el (S.datumIso @Val)
>>> S.el (S.datumIso @Kexp)
>>> S.rest (S.datumIso @Val) >>> S.rest (S.datumIso @Val)
>>> S.onTail S.swap -- >>> _
>>> S.onTail (S.flipped $ IG.PartialIso
(\(karg :- args :- op :- t) ->
(args ++ [ValVar karg]) :- op :- t)
(\(xs :- op :- t) -> case xs ^? _Snoc of
Just (args,preview #ValVar -> Just karg) ->
Right $ karg:- args :- op :- t
_ -> Left $ S.expected "continuation arg"
))
-- prim = S.headTagged2 "prim"
-- (primDatumIso id (S.datumIso @Val))
-- (S.datumIso @Kappa)
prim = S.list $ prim = S.list $
S.el (S.decorate S.SynBuiltin >>> S.sym "prim") S.el (S.decorate S.SynBuiltin >>> S.sym "prim")
>>> S.el (primDatumIso id (S.datumIso @Val)) >>> S.el (primDatumIso id (S.datumIso @Val))
>>> S.el S.datumIso >>> S.el S.datumIso
instance S.DatumIso Kexp where
datumIso = S.match
$ S.With (S.datumIso @Name >>>)
$ S.With (S.datumIso @Kappa >>>)
$ S.End
instance S.DatumIso Program where instance S.DatumIso Program where
datumIso = S.with \prog -> S.datumIso @Lambda >>> prog datumIso = S.with \prog -> S.datumIso @Lambda >>> prog
-- the printed representation is pretty dishonest in its current
-- state. consider the following hoisted program:
--
-- (letrec ((k (κ () (continue start-ktail 123))))
-- (λ (start-ktail)
-- (continue k)))
--
-- here, `start-ktail` is bound in `k`, but the printed representation
-- fails to reflect that.
instance S.DatumIso HoistedProgram where
datumIso = S.with \prog ->
S.letLike "letrec"
(S.datumIso @Label) (S.datumIso @Abs) (S.datumIso @Lambda)
>>> S.onTail (S.iso H.fromList H.toList)
>>> prog
-- quasiquoters -- quasiquoters
@@ -407,7 +307,6 @@ instance CPS Kappa where toCPS = S.fromDatumUnsafe S.datumIso
instance CPS Lambda where toCPS = S.fromDatumUnsafe S.datumIso instance CPS Lambda where toCPS = S.fromDatumUnsafe S.datumIso
instance CPS Abs where toCPS = S.fromDatumUnsafe S.datumIso instance CPS Abs where toCPS = S.fromDatumUnsafe S.datumIso
instance CPS Program where toCPS = S.fromDatumUnsafe S.datumIso instance CPS Program where toCPS = S.fromDatumUnsafe S.datumIso
instance CPS HoistedProgram where toCPS = S.fromDatumUnsafe S.datumIso
cps :: S.QuasiQuoter cps :: S.QuasiQuoter
cps = S.makeSx' [| toCPS |] cps = S.makeSx' [| toCPS |]
@@ -430,8 +329,7 @@ class Free a where
freeWithBound :: HashSet Name -> a -> HashSet Name freeWithBound :: HashSet Name -> a -> HashSet Name
freeWithBound bound = HS.fromList . freeWithBound' bound freeWithBound bound = HS.fromList . freeWithBound' bound
-- | Free variables given in the same left-to-right order they -- | Free variables given in the order of their appearance.
-- appear.
free' :: a -> List Name free' :: a -> List Name
free' = freeWithBound' mempty free' = freeWithBound' mempty
@@ -441,21 +339,11 @@ instance Free Abs where
freeWithBound' bound (AbsKappa kap) = freeWithBound' bound kap freeWithBound' bound (AbsKappa kap) = freeWithBound' bound kap
freeWithBound' bound (AbsLambda lam) = freeWithBound' bound lam freeWithBound' bound (AbsLambda lam) = freeWithBound' bound lam
mif :: Alternative f => (a -> Bool) -> a -> f a
mif p a
| p a = pure a
| otherwise = empty
instance Free Kexp where
freeWithBound' bound = \case
KexpVar x -> mif (`notElem` bound) x
KexpKappa kap -> freeWithBound' bound kap
instance Free Exp where instance Free Exp where
freeWithBound' bound = \case freeWithBound' bound = \case
ExpPrim p k -> ExpPrim p k ->
(p ^.. folded . #ValVar . filtered (`notElem` bound)) p & toListOf (folded . #ValVar . filtered (`notElem` bound))
++ freeWithBound' bound k & (<> freeWithBound' bound k)
ExpLetRec bs m -> ExpLetRec bs m ->
foldMapOf (each . _2) (freeWithBound' bound') bs foldMapOf (each . _2) (freeWithBound' bound') bs
<> freeWithBound' bound' m <> freeWithBound' bound' m
@@ -463,10 +351,10 @@ instance Free Exp where
ExpContinue k xs -> filter (`notElem` bound) ((k:xs) ^.. each . #ValVar) ExpContinue k xs -> filter (`notElem` bound) ((k:xs) ^.. each . #ValVar)
ExpIf c t f -> ExpIf c t f ->
(c ^.. #ValVar . filtered (`notElem` bound)) (c ^.. #ValVar . filtered (`notElem` bound))
<> mif (`notElem` bound) t <> mif (`notElem` bound) f <> freeWithBound' bound t <> freeWithBound' bound f
ExpApply f xs k -> ExpApply f xs k ->
(f:xs) ^.. (each . #ValVar . filtered (`notElem` bound)) (f:xs) ^.. (each . #ValVar . filtered (`notElem` bound))
<> freeWithBound' bound k <> (k ^.. filtered (`notElem` bound))
instance Free Kappa where instance Free Kappa where
freeWithBound' bound (MkKappa xs m) = freeWithBound' bound (MkKappa xs m) =
+10 -34
View File
@@ -1,5 +1,5 @@
module Gyehoek.Driver module Gyehoek.Driver
(main, lower_e2e, convert_e2e, parse_e2e, readScm, eval_e2e, eval_cps_e2e, eval_cps2_e2e) (main, lower_e2e, convert_e2e, parse_e2e, readScm, eval_e2e)
where where
import Gyehoek.Options import Gyehoek.Options
@@ -35,8 +35,6 @@ import Control.Arrow ((>>>))
import Gyehoek.Prelude import Gyehoek.Prelude
import Gyehoek.Jalmot import Gyehoek.Jalmot
import qualified Gyehoek.Sexp as S import qualified Gyehoek.Sexp as S
import Gyehoek.CPS.Hoist (hoistProgram)
import Gyehoek.CPS.Contify (contifyProgram)
main :: IO () main :: IO ()
@@ -120,35 +118,29 @@ driver opts = do
hPutStrLn FS.stdout . view strict . pShowNoColor $ scm hPutStrLn FS.stdout . view strict . pShowNoColor $ scm
cps <- convertProgram scm cps <- convertProgram scm
when opts.dumpCPS do when opts.dumpCPS do
S.writeDatum cps hPutStrLn FS.stdout =<< S.encodeWith S.datumIso cps
closedCps <- closeProgram cps closedCps <- closeProgram cps
when opts.dumpClosed do when opts.dumpClosed do
S.writeDatum closedCps hPutStrLn FS.stdout =<< S.encodeWith S.datumIso closedCps
hoistedCps <- hoistProgram closedCps
when opts.dumpHoisted do
S.writeDatum hoistedCps
-- contifiedCps <- contifyProgram hoistedCps
-- when opts.dumpContified do
-- hPutStrLn FS.stdout =<< S.encodeWith S.datumIso contifiedCps
let rt_is p = is (_Just . p) opts.runtime let rt_is p = is (_Just . p) opts.runtime
dumpOrRun opts.dumpStackified (rt_is #Stackify) dumpOrRun opts.dumpStackified (rt_is #Stackify)
(stackifyProgram hoistedCps) (stackifyProgram closedCps)
(hPutStrLn FS.stdout <=< S.encodeDataWith S.dataIso) (hPutStrLn FS.stdout <=< S.encodeDataWith S.dataIso)
(eval >=> fmap writeObj (eval >=> fmap writeObj
>>> T.unwords >>> T.unwords
>>> hPutStrLn FS.stdout) >>> hPutStrLn FS.stdout)
when (rt_is #HigherOrderCPS) do
CPS.evalProgram cps
>>= S.writeData
when (rt_is #CPS) do when (rt_is #CPS) do
CPS.evalProgram closedCps closedCps
>>= S.writeData & CPS.evalProgram
& fmap writeObj
& T.unwords
& hPutStrLn FS.stdout
-- dumpOrRun opts.inspectWasm (rt_is #Wasm) -- dumpOrRun opts.inspectWasm (rt_is #Wasm)
-- (lowerProgram cps) -- (lowerProgram cps)
-- inspectWasm -- inspectWasm
-- (\wat -> withFile opts.output FS.WriteMode \h -> hPutStrLn h wat) -- (\wat -> withFile opts.output FS.WriteMode \h -> hPutStrLn h wat)
when opts.traceStackified do when opts.traceStackified do
stackifyProgram hoistedCps >>= traceEval stackifyProgram closedCps >>= traceEval
parse_e2e :: FilePath -> IO Scm.Program parse_e2e :: FilePath -> IO Scm.Program
parse_e2e = runJalmotIO . runFileSystem . readScm parse_e2e = runJalmotIO . runFileSystem . readScm
@@ -166,19 +158,3 @@ eval_e2e :: FilePath -> IO (List Obj)
eval_e2e fp = runJalmotIO . runFileSystem . runGenSym $ do eval_e2e fp = runJalmotIO . runFileSystem . runGenSym $ do
stk <- stackifyProgram <=< closeProgram <=< convertProgram <=< readScm $ fp stk <- stackifyProgram <=< closeProgram <=< convertProgram <=< readScm $ fp
eval stk eval stk
eval_cps_e2e :: FilePath -> IO Text
eval_cps_e2e fp = runJalmotIO . runFileSystem . runGenSym $
readScm fp
>>= convertProgram
>>= closeProgram
>>= CPS.evalProgram
>>= pure . S.encodeOrShowData' S.dataIso
eval_cps2_e2e :: FilePath -> IO Text
eval_cps2_e2e fp = runJalmotIO . runFileSystem . runGenSym $
readScm fp
>>= convertProgram
-- >>= closeProgram
>>= CPS.evalProgram
>>= pure . S.encodeOrShowData' S.dataIso
-2
View File
@@ -31,7 +31,6 @@ data AJalmot
= ReaderError (ParseErrorBundle Text Void) = ReaderError (ParseErrorBundle Text Void)
| GrammarError (Grammar.ErrorMessage Ann) | GrammarError (Grammar.ErrorMessage Ann)
| VMError Text | VMError Text
| EvalError Text
deriving (Show, Generic, Data) deriving (Show, Generic, Data)
data AJalmotCS = MkAJalmotCS !CallStack !AJalmot data AJalmotCS = MkAJalmotCS !CallStack !AJalmot
@@ -67,7 +66,6 @@ instance Exception AJalmot where
& layoutPretty defaultLayoutOptions & layoutPretty defaultLayoutOptions
& renderString & renderString
VMError err -> [i|#{err}|] VMError err -> [i|#{err}|]
EvalError err -> [i|#{err}|]
instance Exception AJalmotCS where instance Exception AJalmotCS where
backtraceDesired = const False backtraceDesired = const False
+4 -14
View File
@@ -13,7 +13,7 @@ import Data.Foldable
import Gyehoek.Prelude hiding (argument) import Gyehoek.Prelude hiding (argument)
data Runtime = Stackify | Wasm | CPS | HigherOrderCPS data Runtime = Stackify | Wasm | CPS
deriving (Show, Generic, Eq) deriving (Show, Generic, Eq)
data Language data Language
@@ -29,10 +29,7 @@ data Options = MkOptions
, dumpCPS :: Bool , dumpCPS :: Bool
, dumpParsed :: Bool , dumpParsed :: Bool
, dumpStackified :: Bool , dumpStackified :: Bool
, dumpHoisted :: Bool
, dumpContified :: Bool
, traceStackified :: Bool , traceStackified :: Bool
, noColour :: Bool
, runtime :: Maybe Runtime , runtime :: Maybe Runtime
, inspectWasm :: Bool , inspectWasm :: Bool
, output :: FilePath , output :: FilePath
@@ -54,8 +51,7 @@ runtimeValues = ["stackify","wasm","cps","none"]
runtimeReader = maybeReader \case runtimeReader = maybeReader \case
"stackify" -> Just (Just Stackify) "stackify" -> Just (Just Stackify)
"wasm" -> Just (Just Wasm) "wasm" -> Just (Just Wasm)
"cps1" -> Just (Just CPS) "cps" -> Just (Just CPS)
("cps";"higher-order-cps") -> Just (Just HigherOrderCPS)
"none" -> Just Nothing "none" -> Just Nothing
_ -> Nothing _ -> Nothing
@@ -65,20 +61,14 @@ parser = do
dumpCPS <- switch (long "dump-cps") dumpCPS <- switch (long "dump-cps")
dumpStackified <- switch (long "dump-stackified") dumpStackified <- switch (long "dump-stackified")
dumpParsed <- switch (long "dump-parsed") dumpParsed <- switch (long "dump-parsed")
dumpHoisted <- switch (long "dump-hoisted")
dumpContified <- switch (long "dump-contified")
traceStackified <- switch (long "trace-stackified") traceStackified <- switch (long "trace-stackified")
noColour <- switch . fold $
[ long "no-colour"
, long "no-color"
]
inspectWasm <- switch $ long "inspect-wasm" <> short 'p' inspectWasm <- switch $ long "inspect-wasm" <> short 'p'
runtime <- option runtimeReader . fold $ runtime <- option runtimeReader . fold $
[ long "runtime" [ long "runtime"
, short 'R' , short 'R'
, value (Just HigherOrderCPS) , value (Just Stackify)
, completeWith runtimeValues , completeWith runtimeValues
, showDefaultWith $ const "higher-order-cps" , showDefaultWith $ const "stackify"
, metavar "RUNTIME" , metavar "RUNTIME"
] ]
sourceLanguage <- option languageReader . fold $ sourceLanguage <- option languageReader . fold $
-6
View File
@@ -81,8 +81,6 @@ data Prim e
| PrimZeroP e | PrimZeroP e
| PrimNewline | PrimNewline
| PrimMakeClosure { code :: e, env :: List e } | PrimMakeClosure { code :: e, env :: List e }
| PrimMakeSharedClosure { codes :: List e, env :: List e }
| PrimGetEnv
| PrimEnv | PrimEnv
| PrimEnvRef Int | PrimEnvRef Int
| PrimCallCC e | PrimCallCC e
@@ -170,10 +168,6 @@ primDatumIso namefn a = S.match
$ S.With (. ht1 "zero?") $ S.With (. ht1 "zero?")
$ S.With (. ht0 "newline") $ S.With (. ht0 "newline")
$ S.With (. ht1' "make-closure") $ S.With (. ht1' "make-closure")
$ S.With (. S.headTagged2 (namefn "make-shared-closure")
(S.list $ S.rest a)
(S.list $ S.rest a))
$ S.With (. ht0 "get-env")
$ S.With (. ht0 "env") $ S.With (. ht0 "env")
$ S.With (. S.headTagged1 (namefn "env-ref") S.int) $ S.With (. S.headTagged1 (namefn "env-ref") S.int)
$ S.With (. ht1 "call/cc") $ S.With (. ht1 "call/cc")
-37
View File
@@ -15,7 +15,6 @@ module Gyehoek.Sexp.Grammar
, encodeDataTest , encodeDataTest
, encodeDataTestColour , encodeDataTestColour
, encodeOrShow' , encodeOrShow'
, encodeOrShowData'
, decodeDataWith , decodeDataWith
, encodeDataWith' , encodeDataWith'
, decodeTest , decodeTest
@@ -29,8 +28,6 @@ module Gyehoek.Sexp.Grammar
, fromDatumUnsafe , fromDatumUnsafe
, Control.Category.id , Control.Category.id
, fromDataUnsafe , fromDataUnsafe
, writeDatum
, writeData
) )
where where
@@ -48,7 +45,6 @@ import qualified Control.Category
import qualified Data.Vector as V import qualified Data.Vector as V
import Data.String (IsString (fromString)) import Data.String (IsString (fromString))
import qualified Data.Text as T import qualified Data.Text as T
import System.Environment (lookupEnv)
toDatum :: Jalmot :> es => DatumGrammar a -> a -> Eff es Datum toDatum :: Jalmot :> es => DatumGrammar a -> a -> Eff es Datum
@@ -130,39 +126,6 @@ encodeOrShow' g x = fromString $
Left _ -> show x Left _ -> show x
Right t -> T.unpack t Right t -> T.unpack t
encodeOrShow :: (IsString s, Show a) => DatumGrammar a -> a -> s
encodeOrShow g x = fromString $
case runPureEff . runJalmot . encodeWith g $ x of
Left _ -> show x
Right t -> T.unpack t
encodeOrShowData' :: (IsString s, Show a) => DataGrammar a -> a -> s
encodeOrShowData' g x = fromString $
case runPureEff . runJalmot . encodeDataWith' g $ x of
Left _ -> show x
Right t -> T.unpack t
encodeOrShowData :: (IsString s, Show a) => DataGrammar a -> a -> s
encodeOrShowData g x = fromString $
case runPureEff . runJalmot . encodeDataWith g $ x of
Left _ -> show x
Right t -> T.unpack t
useColour :: IO Bool
useColour = maybe True (const False) <$> lookupEnv "NO_COLOR"
writeDatum :: (Show a, DatumIso a, MonadIO m) => a -> m ()
writeDatum x = do
c <- liftIO useColour
let f = if c then encodeOrShow else encodeOrShow'
liftIO . TIO.putStrLn . f datumIso $ x
writeData :: (Show a, DataIso a, MonadIO m) => a -> m ()
writeData x = do
c <- liftIO useColour
let f = if c then encodeOrShowData else encodeOrShowData'
liftIO . TIO.putStrLn . f dataIso $ x
class DatumIso a where class DatumIso a where
datumIso :: DatumGrammar a datumIso :: DatumGrammar a
+1 -1
View File
@@ -9,7 +9,7 @@ module Gyehoek.Sexp.Grammar.Base
, DatumGrammar , DatumGrammar
, DataGrammar , DataGrammar
, Grammar , Grammar
, ListContext(..) , ListContext
, (:-)((:-)) , (:-)((:-))
-- * lists -- * lists
, list , list
+2 -2
View File
@@ -76,7 +76,7 @@ data Instr
= Pop Reg = Pop Reg
| Push Val | Push Val
| Load Reg Int | Load Reg Int
| Prim Reg (Prim Val) | Prim (Prim Val)
deriving stock (Show, Generic, Data) deriving stock (Show, Generic, Data)
deriving anyclass (NFData) deriving anyclass (NFData)
@@ -99,7 +99,7 @@ instance S.DatumIso Instr where
$ S.With (S.headTagged1 "pop!" S.datumIso >>>) $ S.With (S.headTagged1 "pop!" S.datumIso >>>)
$ S.With (S.headTagged1 "push!" S.datumIso >>>) $ S.With (S.headTagged1 "push!" S.datumIso >>>)
$ S.With (S.headTagged2 "load" S.datumIso S.datumIso >>>) $ S.With (S.headTagged2 "load" S.datumIso S.datumIso >>>)
$ S.With (S.headTagged2 "prim" S.datumIso S.datumIso >>>) $ S.With (S.headTagged1 "prim" S.datumIso >>>)
$ S.End $ S.End
where where
+14
View File
@@ -112,6 +112,20 @@ vmerror = throwError . VMError
stepI :: Jalmot :> es => Env -> VM -> Instr -> Eff es VM stepI :: Jalmot :> es => Env -> VM -> Instr -> Eff es VM
stepI e vm (Load r j) = do
x <- expectOf [i|object at index #{j}|] (activeFrame . ix j) vm
pure $ vm & #registers . at r ?~ x
stepI e vm (Push v) = traverseOf activeFrame push vm
where push xs = cons <$> evalVal e vm v <*> pure xs
stepI g vm (Prim p) = stepP g vm p
stepI e vm (Pop r) = case vm ^? activeFrame . _Cons of
Nothing -> vmerror "empty stack"
Just (x,xs) -> pure $ vm & #registers . at r ?~ x
& activeFrame .~ xs
stepI e vm ins = vmerror [i|unimplemented instruction: #{ins}|] stepI e vm ins = vmerror [i|unimplemented instruction: #{ins}|]
stepT :: Jalmot :> es => Env -> VM -> Tail -> Eff es VM stepT :: Jalmot :> es => Env -> VM -> Tail -> Eff es VM
BIN
View File
Binary file not shown.
+46 -68
View File
@@ -5,75 +5,53 @@ import Test.Tasty.HUnit
import Gyehoek.CPS.Syntax (cps, Obj(..), Hob(..), Imm(..)) import Gyehoek.CPS.Syntax (cps, Obj(..), Hob(..), Imm(..))
import Gyehoek.CPS.Eval qualified as Sut import Gyehoek.CPS.Eval qualified as Sut
import Data.List (List) import Data.List (List)
import Test.Tasty.ExpectedFailure (ignoreTestBecause, expectFail) import Test.Tasty.ExpectedFailure (ignoreTestBecause)
import System.Directory (listDirectory)
import Test.Tasty.Silver
import System.FilePath
import Control.Exception
import qualified Gyehoek.Driver as Driver
import Control.DeepSeq (($!!))
import System.Exit (ExitCode(..))
import qualified Data.Text as T
import Data.Function (applyWhen)
import Gyehoek.Prelude
brokenEvalTests :: List String test_cpsInterpreter =
brokenEvalTests = ignoreTestBecause "i forgorrrr" $
[] testGroup "cps interpreter" $
-- [ "adder" [ primitives
-- , "apply2" , testCase "halt with constant" do
-- , "apply-twice" evalsTo [ObjImm (ImmInt 123)] [cps|
-- , "arith" (continue halt 123)
-- , "begin-1" |]
-- , "callcc-constant" , testCase "identity cont" do
-- , "callcc-discard" evalsTo [ObjImm (ImmInt 154)] [cps|
-- , "callcc-early-exit-1" (letrec ((id (κ (x)
-- , "callcc-early-exit-2" (continue halt x))))
-- , "callcc-early-exit-3" (continue id 154))
-- , "callcc-early-exit-4" |]
-- , "callcc-early-exit-5" , testCase "identity function" do
-- , "callcc-early-exit-6" evalsTo [ObjImm (ImmInt 456)] [cps|
-- , "callcc-nested-1" (letrec ((id (λ (x ktail)
-- , "callcc-nested-2" (continue ktail x))))
-- , "complicated-1" (id 456 halt))
-- , "cons-1" |]
-- , "factorial" , testCase "square" do
-- , "false" evalsTo [ObjImm (ImmInt 81)] [cps|
-- , "fn-of-fn" (letrec ((square (λ (x ktail)
-- , "if-false" (prim (* x x)
-- , "if-number" (κ (r) (continue ktail r))))))
-- , "if-true" (square 9 halt))
-- , "lambda" |]
-- , "letrec-fn" ]
-- , "let-fn"
-- , "lit-int"
-- , "square"
-- , "true"
-- ]
test_eval :: IO TestTree evalsTo :: HasCallStack => List Obj -> Sut.Exp -> Assertion
test_eval = do evalsTo rs e = Sut.evalExp e @?= rs
cs <- listDirectory "golden/exec"
<&> fmap ("golden/exec" </>) primitives = testGroup "primitives"
pure $ testGroup "cps interpreter" [ testGroup "arith"
[ testGroup "higher-order" $ cpsCase Driver.eval_cps2_e2e <$> cs [ testCase "basic 1" do
, testGroup "first-order" $ cpsCase Driver.eval_cps_e2e <$> cs evalsTo [ObjImm (ImmInt 20)] [cps|
(prim (* 4 5)
(κ (x) (continue halt x)))
|]
, testCase "basic 2" do
evalsTo [ObjImm (ImmInt 35)] [cps|
(prim (* 2 16)
(κ (x) (prim (+ x 3)
(κ (r) (continue halt r)))))
|]
] ]
]
maybeBroken name broken = applyWhen (name `elem` broken) expectFail
cpsCase :: (FilePath -> IO Text) -> FilePath -> TestTree
cpsCase f test =
maybeBroken testName brokenEvalTests $
goldenVsAction testName resultFile action printProcResult
where
testName = takeFileName test
resultFile = test </> "exec"
sourceFile = test </> "source.scm"
action = catch @SomeException
(do r <- f sourceFile
pure $!! ( ExitSuccess
, r
, "" ))
\e -> pure (ExitFailure 1, "", T.pack $ displayException e)
+75 -76
View File
@@ -10,87 +10,86 @@ import Gyehoek.GenSym (runGenSym)
import Effectful import Effectful
import Gyehoek.Prelude import Gyehoek.Prelude
import Gyehoek.Jalmot import Gyehoek.Jalmot
import Test.Tasty.ExpectedFailure (expectFail, ignoreTestBecause)
-- test_stackify = test_stackify =
-- [ trivialReturn [ trivialReturn
-- , tailCall , tailCall
-- , prim , prim
-- , condition , condition
-- , procedure , procedure
-- ] ]
-- evalsTo :: HasCallStack => List Obj -> Sut.Program -> Assertion evalsTo :: HasCallStack => List Obj -> Sut.Program -> Assertion
-- evalsTo rs e = runJalmotUnsafe (Stk.eval e') @?= rs evalsTo rs e = runJalmotUnsafe (Stk.eval e') @?= rs
-- where where
-- e' = e & Sut.stackifyProgram & runGenSym & runPureEff e' = e & Sut.stackifyProgram & runGenSym & runPureEff
-- trivialReturn = testGroup "trivial return" trivialReturn = testGroup "trivial return"
-- [ testCase "return int" do [ testCase "return int" do
-- evalsTo [ObjImm (ImmInt 4)] evalsTo [ObjImm (ImmInt 4)]
-- [cps|(λ (ktail) (continue ktail 4))|] [cps|(λ (ktail) (continue ktail 4))|]
-- , testCase "return bool" do , testCase "return bool" do
-- evalsTo [ObjImm (ImmBool True)] evalsTo [ObjImm (ImmBool True)]
-- [cps|(λ (ktail) (continue ktail #t))|] [cps|(λ (ktail) (continue ktail #t))|]
-- evalsTo [ObjImm (ImmBool False)] evalsTo [ObjImm (ImmBool False)]
-- [cps|(λ (ktail) (continue ktail #f))|] [cps|(λ (ktail) (continue ktail #f))|]
-- ] ]
-- tailCall = testGroup "tail call" tailCall = testGroup "tail call"
-- [ testCase "square" do [ testCase "square" do
-- evalsTo [ObjImm (ImmInt 16)] [cps| evalsTo [ObjImm (ImmInt 16)] [cps|
-- (λ (ktail0) (λ (ktail0)
-- (letrec ((square (λ (x ktail) (letrec ((square (λ (x ktail)
-- (prim (* x x) (prim (* x x)
-- (κ (x0) (continue ktail x0)))))) (κ (x0) (continue ktail x0))))))
-- (square 4 halt))) (square 4 halt)))
-- |] |]
-- ] ]
-- prim = testGroup "prim" prim = testGroup "prim"
-- [ testCase "multiply" do [ testCase "multiply" do
-- evalsTo [ObjImm (ImmInt 20)] evalsTo [ObjImm (ImmInt 20)]
-- [cps|(λ (ktail0) [cps|(λ (ktail0)
-- (prim (* 4 5) (prim (* 4 5)
-- (κ (x) (continue ktail0 x))))|] (κ (x) (continue ktail0 x))))|]
-- , testCase "add" do , testCase "add" do
-- evalsTo [ObjImm (ImmInt 9)] evalsTo [ObjImm (ImmInt 9)]
-- [cps|(λ (ktail0) [cps|(λ (ktail0)
-- (prim (+ 4 5) (prim (+ 4 5)
-- (κ (x) (continue ktail0 x))))|] (κ (x) (continue ktail0 x))))|]
-- -- , testGroup "call/cc" -- , testGroup "call/cc"
-- -- [ testCase "trivial" do -- [ testCase "trivial" do
-- -- evalsTo [ObjImm (ImmInt 123)] -- evalsTo [ObjImm (ImmInt 123)]
-- -- [cps|(letrec ((f (λ (cc ktail) (continue cc 123)))) -- [cps|(letrec ((f (λ (cc ktail) (continue cc 123))))
-- -- (prim (call/cc f)))|] -- (prim (call/cc f)))|]
-- -- ] -- ]
-- ] ]
-- condition = testCase "if" do condition = testCase "if" do
-- evalsTo [ObjImm (ImmInt 123)] evalsTo [ObjImm (ImmInt 123)]
-- [cps|(λ (ktail0) [cps|(λ (ktail0)
-- (if #t (continue ktail0 123) (continue ktail0 456)))|] (if #t (continue ktail0 123) (continue ktail0 456)))|]
-- evalsTo [ObjImm (ImmInt 456)] evalsTo [ObjImm (ImmInt 456)]
-- [cps|(λ (ktail0) [cps|(λ (ktail0)
-- (if #f (continue ktail0 123) (continue ktail0 456)))|] (if #f (continue ktail0 123) (continue ktail0 456)))|]
-- procedure = testGroup "procedure" procedure = testGroup "procedure"
-- [ testCase "factorial" do [ testCase "factorial" do
-- evalsTo [ObjImm (ImmInt 720)] evalsTo [ObjImm (ImmInt 720)]
-- [cps|(λ (ktail0) [cps|(λ (ktail0)
-- (letrec ((fac (λ (n ktail) (letrec ((fac (λ (n ktail)
-- (prim (zero? n) (prim (zero? n)
-- (κ (x0) (κ (x0)
-- (if x0 (if x0
-- (continue ktail 1) (continue ktail 1)
-- (prim (- n 1) (prim (- n 1)
-- (κ (x1) (κ (x1)
-- (letrec ((fac-k0 (letrec ((fac-k0
-- (κ (x2) (κ (x2)
-- (prim (* n x2) (prim (* n x2)
-- (κ (x3) (κ (x3)
-- (continue ktail x3)))))) (continue ktail x3))))))
-- (fac x1 fac-k0)))))))))) (fac x1 fac-k0))))))))))
-- (fac 6 halt)))|] (fac 6 halt)))|]
-- ] ]
+2 -2
View File
@@ -46,9 +46,9 @@ qq = testGroup "parser"
, testCase "application" do , testCase "application" do
assertEqual "" (Sut.ExpApply (Sut.ValVar "f") assertEqual "" (Sut.ExpApply (Sut.ValVar "f")
[Sut.ValVar "x",Sut.ValVar "y"] [Sut.ValVar "x",Sut.ValVar "y"]
(Sut.KexpVar "k")) "k")
[cps|(f x y k)|] [cps|(f x y k)|]
assertEqual "" (Sut.ExpApply (Sut.ValVar "f") assertEqual "" (Sut.ExpApply (Sut.ValVar "f")
[] (Sut.KexpVar "k")) [] "k")
[cps|(f k)|] [cps|(f k)|]
] ]
+1 -2
View File
@@ -40,8 +40,7 @@ test_root = do
testGroup "execution" <$> sequenceA testGroup "execution" <$> sequenceA
[ ignoreTestBecause "wasm codegen is on the backburner" [ ignoreTestBecause "wasm codegen is on the backburner"
<$> wasmTests tests <$> wasmTests tests
, ignoreTestBecause "i'm killing myself" , stackifyTests tests
<$> stackifyTests tests
] ]
maybeBroken name broken = applyWhen (name `elem` broken) expectFail maybeBroken name broken = applyWhen (name `elem` broken) expectFail
+1 -2
View File
@@ -8,13 +8,12 @@ import Gyehoek.Stack.VM qualified as Sut
import Data.List (List) import Data.List (List)
import Gyehoek.Jalmot import Gyehoek.Jalmot
import Gyehoek.Prelude (i) import Gyehoek.Prelude (i)
import Test.Tasty.ExpectedFailure (expectFail, ignoreTestBecause)
evalsTo :: List Obj -> Program -> Assertion evalsTo :: List Obj -> Program -> Assertion
evalsTo rs p = runJalmotUnsafe (Sut.eval p) @?= rs evalsTo rs p = runJalmotUnsafe (Sut.eval p) @?= rs
test_root = ignoreTestBecause "i'm super-killing myself" $ testGroup "stack machine" test_root = testGroup "stack machine"
[ testCase "immediate halt" do [ testCase "immediate halt" do
evalsTo [] [stkP| evalsTo [] [stkP|
(define $start (define $start