@@ -1,10 +1,68 @@
1module RTS.CodegenC where
1module RTS.CodegenC where
3import Core.TT
3import Core.TT
4import RTS.PreC
7import RTS.PreC
5import RTS.SC
8import RTS.SC
11+import Idris.AbsSyntax
7import Data.Char
13import Data.Char
15+import Control.Monad.State
18+import System.Directory
19+import System.Environment
23+compileC :: FilePath -> Term -> Idris ()
26+ let tmnames = namesUsed (STerm tm)
27+ used <- mapM (allNames []) tmnames
29+ let entry = mainFn (idris_scprims i) tm
30+ scs' <- mkDecls tm (concat used)
31+ let scs = scs' ++ entry
32+ objs <- getObjectFiles
35+ ddir <- liftIO $ getDataDir
36+ -- if any includes exist in the data directory, use that
37+ hdrs' <- liftIO $ mapM (inDir ddir) hdrs
39+ let pcs = preCdefs bcs
41+ liftIO $ writeFile (f ++ ".c") code
42+ where checkMVs = do i <- get
43+ case idris_metavars i \\ primDefs of
45+ ms -> fail $ "There are undefined metavariables: " ++ show ms
46+ inDir d h = do let f = d ++ "/" ++ h
47+ ex <- doesFileExist f
48+ if ex then return f else return h
51+mainFn ps tm = toSC ps (MN 0 "_main", Function undefined tm)
53+allNames :: [Name] -> Name -> Idris [Name]
54+allNames ns n | n `elem` ns = return []
55+allNames ns n = do i <- get
56+ case lookupCtxt Nothing n (idris_callgraph i) of
57+ [ns'] -> do more <- mapM (allNames (n:ns)) ns'
58+ return (nub (n : concat more))
61+mkDecls :: Term -> [Name] -> Idris [(Name, SCDef)]
64+ let ds = filter (\ (n, d) -> n `elem` used) $ ctxtAlist (tt_ctxt i)
65+ return $ concatMap (toSC (idris_scprims i)) ds
9cdefs :: [(Name, (Int, PreC))] -> String
67cdefs :: [(Name, (Int, PreC))] -> String
10cdefs xs = concatMap (\ (n, (i, c)) -> proto n) xs ++ "\n" ++
68cdefs xs = concatMap (\ (n, (i, c)) -> proto n) xs ++ "\n" ++
@@ -12,7 +70,8 @@ cdefs xs = concatMap (\ (n, (i, c)) -> proto n) xs ++ "\n" ++
13codegenC :: Name -> Int -> PreC -> String
71codegenC :: Name -> Int -> PreC -> String
14codegenC n args prec
72codegenC n args prec
73+ = "/* " ++ show prec ++ " */\n\n" ++
15− = "void " ++ cname n ++ "(VM* vm) {\n" ++
74+ "void " ++ cname n ++ "(VM* vm) {\n" ++
16 concatMap (cg 1) prec ++ "}\n\n"
75 concatMap (cg 1) prec ++ "}\n\n"
18indent i = take (i * 4) (repeat ' ')
77indent i = take (i * 4) (repeat ' ')
@@ -23,6 +82,7 @@ reg (LVar v) = "*(vm->stack-" ++ show v ++ ")"
23catom :: CAtom -> String
82catom :: CAtom -> String
24catom (CL l) = reg (LVar l)
83catom (CL l) = reg (LVar l)
25catom (CC (I i)) = "MKINT(" ++ show i ++ ")"
84catom (CC (I i)) = "MKINT(" ++ show i ++ ")"
85+catom (CC v) = "const(" ++ show v ++ ")"
26catom (CP n) = cname n
86catom (CP n) = cname n
28assignCon i r tag args
88assignCon i r tag args