c - Is it possible to generate and run TemplateHaskell generated code at runtime? -



c - Is it possible to generate and run TemplateHaskell generated code at runtime? -

is possible generate , run templatehaskell generated code @ runtime?

using c, @ runtime, can:

create source code of function, call out gcc compile .so (linux) (or utilize llvm, etc.), load .so and call function.

is similar thing possible template haskell?

yes, it's possible. ghc api compile template haskell. proof-of-concept available @ https://github.com/johnlato/meta-th, which, although not sophisticated, shows 1 general technique provides modicum of type safety. template haskell expressions build using meta type, can compiled , loaded usable function.

{-# language scopedtypevariables #-} {-# language templatehaskell #-} {-# options_ghc -wall #-} module data.meta.meta ( -- * meta type meta (..) -- * functions , metacompile ) import language.haskell.th import data.typeable typ import control.exception (bracket) import system.plugins -- plugins import system.io import system.directory newtype meta = meta { unmeta :: expq } -- | super-dodgy moment, meta type should register -- imports needs. metacompile :: forall a. typeable => meta -> io (either string a) metacompile (meta expr) = expr' <- runq expr -- pretty-print th look source code compiled @ -- run-time allow interpstr = pprint expr' typetyperep = typ.typeof (undefined :: a) allow opener = (tfile, h) <- opentempfile "." "footmpfile.hs" hputstr h (unlines [ "module tempmod where" , "import prelude" , "import language.haskell.th" , "import ghc.num" , "import ghc.base" , "" , "myfunc :: " ++ show typetyperep , "myfunc = " ++ interpstr] ) hflush h hclose h homecoming tfile bracket opener removefile $ \tfile -> res <- create tfile ["-o2", "-ddump-simpl"] allow ofile = case res of makesuccess _ fp -> fp makefailure errs -> error $ show errs print $ "loading from: " ++ show ofile r2 <- load (ofile) [] [] "myfunc" print "loaded" case r2 of loadfailure er -> homecoming (left (show er)) loadsuccess _ (fn :: a) -> homecoming $ right fn

this function takes expq, , first runs in io create plain exp. exp pretty-printed source code, compiled , loaded @ run-time. in practice, i've found 1 of more hard obstacles specifying right imports in generated th code.

c haskell runtime template-haskell ghc-api

Comments

Popular posts from this blog

c - Compilation of a code: unkown type name string -

java - Bypassing "final local variable defined in an enclosing type" -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -