1{-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-}
3module IRTS.Compiler where
6import IRTS.Defunctionalise
8import IRTS.CodegenCommon
10import IRTS.CodegenJava
12import IRTS.CodegenJavaScript
14import IRTS.CodegenLLVM
25import Idris.Core.Evaluate
26import Idris.Core.CaseTree
28import Control.Monad.State
30import qualified Data.Map as M
33import System.Directory
34import System.Environment
35import System.FilePath ((</>), addTrailingPathSeparator)
39compile :: Codegen -> FilePath -> Term -> Idris ()
42 let tmnames = namesUsed (STerm tm)
43 usedIn <- mapM (allNames []) tmnames
44 let used = sUN "prim__subBigInt" : sUN "prim__addBigInt" : concat usedIn
45 defsIn <- mkDecls tm used
48 -- TODO: DEBUG-ONLY, remove
50 let usedF = findUsed (tt_ctxt ist) (idris_callgraph ist) used
51 iLOG $ "USAGE ANALYSIS:\n" ++ unlines (map show . M.toList $ usedF)
55 objs <- getObjectFiles codegen
56 libs <- getLibs codegen
57 flags <- getFlags codegen
58 hdrs <- getHdrs codegen
59 impdirs <- allImportDirs
60 let defs = defsIn ++ [(sMN 0 "runMain", maindef)]
61 -- iputStrLn $ showSep "\n" (map show defs)
62 let (nexttag, tagged) = addTags 65536 (liftAll defs)
63 let ctxtIn = addAlist tagged emptyContext
64 iLOG "Defunctionalising"
65 let defuns_in = defunctionalise nexttag ctxtIn
66 logLvl 5 $ show defuns_in
68 let defuns = inline defuns_in
69 logLvl 5 $ show defuns
70 iLOG "Resolving variables for CG"
71 -- iputStrLn $ showSep "\n" (map show (toAlist defuns))
72 let checked = checkDefs defuns (toAlist defuns)
74 dumpCases <- getDumpCases
75 dumpDefun <- getDumpDefun
78 Just f -> runIO $ writeFile f (showCaseTrees defs)
81 Just f -> runIO $ writeFile f (dumpDefuns defuns)
82 triple <- Idris.AbsSyntax.targetTriple
83 cpu <- Idris.AbsSyntax.targetCPU
85 iLOG "Building output"
88 OK c -> do let cginfo = CodegenInfo f outty triple cpu optimise
89 hdrs impdirs objs libs flags
90 NONE c (toAlist defuns)
92 runIO $ case codegen of
93 ViaC -> codegenC cginfo
94 ViaJava -> codegenJava cginfo
95 ViaJavaScript -> codegenJavaScript cginfo
96 ViaNode -> codegenNode cginfo
97 ViaLLVM -> codegenLLVM cginfo
98 Bytecode -> dumpBC c f
100 where checkMVs = do i <- getIState
101 case map fst (idris_metavars i) \\ primDefs of
103 ms -> ifail $ "There are undefined metavariables: " ++ show ms
104 inDir d h = do let f = d </> h
105 ex <- doesFileExist f
106 if ex then return f else return h
108irMain :: TT Name -> Idris LDecl
109irMain tm = do i <- ir tm
110 return $ LFun [] (sMN 0 "runMain") [] (LForce i)
112mkDecls :: Term -> [Name] -> Idris [(Name, LDecl)]
115 let ds = filter (\ (n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i)
117 decls <- mapM build ds
120showCaseTrees :: [(Name, LDecl)] -> String
121showCaseTrees ds = showSep "\n\n" (map showCT ds)
123 showCT (n, LFun _ f args lexp)
124 = show n ++ " " ++ showSep " " (map show args) ++ " =\n\t "
126 showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a
128isCon (TyDecl _ _) = True
132 ir :: a -> Idris LExp
134build :: (Name, Def) -> Idris (Name, LDecl)
137 case lookup n (idris_scprims i) of
139 let args = map (\x -> sMN x "op") [0..] in
140 return (n, (LFun [] n (take ar args)
141 (LOp op (map (LV . Glob) (take ar args)))))
142 _ -> do def <- mkLDecl n d
143 logLvl 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def
146getPrim :: IState -> Name -> [LExp] -> Maybe LExp
147getPrim i n args = case lookup n (idris_scprims i) of
149 if (ar == length args)
150 then return (LOp op args)
154declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x
155declArgs args inl n x = LFun (if inl then [Inline] else []) n args x
157mkLDecl n (Function tm _) = do e <- ir tm
158 return (declArgs [] True n e)
159mkLDecl n (CaseOp ci _ _ _ pats cd)
160 = let (args, sc) = cases_runtime cd in
161 do e <- ir (args, sc)
162 return (declArgs [] (case_inlinable ci) n e)
163mkLDecl n (TyDecl (DCon t a) _) = return $ LConstructor n t a
164mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a
165mkLDecl n _ = return $ (declArgs [] True n LNothing) -- postulate, never run
167instance ToIR (TT Name) where
168 ir tm = ir' [] tm where
170 | (P _ (UN m) _, args) <- unApply tm,
171 m == txt "mkForeignPrim"
173 | (P _ (UN u) _, [_, arg]) <- unApply tm,
174 u == txt "unsafePerformPrimIO"
176 -- TMP HACK - until we get inlining.
177 | (P _ (UN r) _, [_, _, _, _, _, arg]) <- unApply tm,
180 -- Laziness, the old way
181 | (P _ (UN l) _, [_, arg]) <- unApply tm,
183 = do arg' <- ir' env arg
184 error "lazy has crept in somehow"
185-- return $ LLazyExp arg'
186 | (P _ (UN l) _, [_, arg]) <- unApply tm,
188 = do arg' <- ir' env arg
190 -- Laziness, the new way
191 | (P _ (UN l) _, [arg]) <- unApply tm,
193 = do arg' <- ir' env arg
194 return $ LLazyExp arg'
195 | (P _ (UN l) _, [_, _, arg]) <- unApply tm,
197 = do arg' <- ir' env arg
199 | (P _ (UN a) _, [_, _, arg]) <- unApply tm,
200 a == txt "assert_smaller"
202 | (P _ (UN a) _, [_, arg]) <- unApply tm,
203 a == txt "assert_total"
205 | (P _ (UN p) _, [_, arg]) <- unApply tm,
207 = do arg' <- ir' env arg
208 return $ LOp LPar [LLazyExp arg']
209 | (P _ (UN pf) _, [arg]) <- unApply tm,
210 pf == txt "prim_fork"
211 = do arg' <- ir' env arg
212 return $ LOp LFork [LLazyExp arg']
213 | (P _ (UN m) _, [_,size,t]) <- unApply tm,
215 = do size' <- ir' env size
217 return t' -- TODO $ malloc_ size' t'
218 | (P _ (UN tm) _, [_,t]) <- unApply tm,
219 tm == txt "trace_malloc"
222 -- This case is here until we get more general inlining. It's just
223 -- a really common case, and the laziness hurts...
224 | (P _ (NS (UN be) [b,p]) _, [_,x,(App (P _ (UN d) _) t),
225 (App (P _ (UN d') _) e)]) <- unApply tm,
226 be == txt "boolElim" && d == txt "Delay" && d' == txt "Delay"
230 return (LCase x' [LConCase 0 (sNS (sUN "False") ["Bool","Prelude"]) [] e',
231 LConCase 1 (sNS (sUN "True") ["Bool","Prelude"]) [] t'])
232 | (P (DCon t a) n _, args) <- unApply tm
233 = irCon env t a n args
234 | (P (TCon t a) n _, args) <- unApply tm
236 | (P _ n _, args) <- unApply tm
238 args' <- mapM (ir' env) args
239 case getPrim i n args' of
243 = case lookupCtxtExact n
244 (idris_optimisation i) of
245 Just oi -> collapsible oi
248 = case lookupCtxtExact n
249 (idris_callgraph i) of
250 Just (CGInfo _ _ _ _ unusedpos) ->
255 else return (LApp False (LV (Glob n))
256 (mkUnused unused 0 args'))
257 | (f, args) <- unApply tm
259 args' <- mapM (ir' env) args
260 return (LApp False f' args')
261 where mkUnused u i [] = []
262 mkUnused u i (x : xs) | i `elem` u = LNothing : mkUnused u (i + 1) xs
263 | otherwise = x : mkUnused u (i + 1) xs
264-- ir' env (P _ (NS (UN "Z") ["Nat", "Prelude"]) _)
265-- = return $ LConst (BI 0)
266 ir' env (P _ n _) = return $ LV (Glob n)
267 ir' env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i))
268 | otherwise = ifail $ "IR fail " ++ show i ++ " " ++ show tm
269 ir' env (Bind n (Lam _) sc)
270 = do let n' = uniqueName n env
271 sc' <- ir' (n' : env) sc
272 return $ LLam [n'] sc'
273 ir' env (Bind n (Let _ v) sc)
274 = do sc' <- ir' (n : env) sc
276 return $ LLet n v' sc'
277 ir' env (Bind _ _ _) = return $ LNothing
278 ir' env (Proj t i) | i == -1
280 return $ LOp (LMinus (ATInt ITBig))
282 ir' env (Proj t i) = do t' <- ir' env t
284 ir' env (Constant c) = return $ LConst c
285 ir' env (TType _) = return $ LNothing
286 ir' env Erased = return $ LNothing
287 ir' env Impossible = return $ LNothing
288-- ir' env _ = return $ LError "Impossible"
290 irCon env t arity n args
291 | length args == arity = buildApp env (LV (Glob n)) args
292 | otherwise = let extra = satArgs (arity - length args) in
293 do sc' <- irCon env t arity n
294 (args ++ map (\n -> P Bound n undefined) extra)
295 return $ LLam extra sc'
297 satArgs n = map (\i -> sMN i "sat") [1..n]
299 buildApp env e [] = return e
300 buildApp env e xs = do xs' <- mapM (ir' env) xs
301 return $ LApp False e xs'
303 doForeign :: [Name] -> [TT Name] -> Idris LExp
304 doForeign env (_ : fgn : args)
305 | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
306 = let maybeTys = getFTypes fgnArgTys
309 Nothing -> ifail $ "Foreign type specification is not a constant list: " ++ show (fgn:args)
311 args' <- mapM (ir' env) (init args)
312 -- wrap it in a prim__IO
313 -- return $ con_ 0 @@ impossible @@
314 return $ -- LLazyExp $
315 LForeign LANG_C rty fgnName (zip tys args')
316 | otherwise = ifail "Badly formed foreign function call"
318getFTypes :: TT Name -> Maybe [FType]
319getFTypes tm = case unApply tm of
322 fmap (mkIty' ty :) (getFTypes xs)
325mkIty' (P _ (UN ty) _) = mkIty (str ty)
326mkIty' (App (P _ (UN fi) _) (P _ (UN intTy) _))
327 | fi == txt "FIntT" = mkIntIty (str intTy)
328mkIty' (App (App (P _ (UN ff) _) _) (App (P _ (UN fa) _) (App (P _ (UN io) _) _)))
329 | ff == txt "FFunction" && fa == txt "FAny" &&
332mkIty' (App (App (P _ (UN ff) _) _) _)
333 | ff == txt "FFunction" = FFunction
336-- would be better if these FInt types were evaluated at compile time
337-- TODO: add %eval directive for such things
339mkIty "FFloat" = FArith ATFloat
340mkIty "FInt" = mkIntIty "ITNative"
341mkIty "FChar" = mkIntIty "ITChar"
342mkIty "FByte" = mkIntIty "IT8"
343mkIty "FShort" = mkIntIty "IT16"
344mkIty "FLong" = mkIntIty "IT64"
345mkIty "FBits8" = mkIntIty "IT8"
346mkIty "FBits16" = mkIntIty "IT16"
347mkIty "FBits32" = mkIntIty "IT32"
348mkIty "FBits64" = mkIntIty "IT64"
349mkIty "FString" = FString
351mkIty "FManagedPtr" = FManagedPtr
353mkIty "FFunction" = FFunction
354mkIty "FFunctionIO" = FFunctionIO
355mkIty "FBits8x16" = FArith (ATInt (ITVec IT8 16))
356mkIty "FBits16x8" = FArith (ATInt (ITVec IT16 8))
357mkIty "FBits32x4" = FArith (ATInt (ITVec IT32 4))
358mkIty "FBits64x2" = FArith (ATInt (ITVec IT64 2))
359mkIty x = error $ "Unknown type " ++ x
361mkIntIty "ITNative" = FArith (ATInt ITNative)
362mkIntIty "ITChar" = FArith (ATInt ITChar)
363mkIntIty "IT8" = FArith (ATInt (ITFixed IT8))
364mkIntIty "IT16" = FArith (ATInt (ITFixed IT16))
365mkIntIty "IT32" = FArith (ATInt (ITFixed IT32))
366mkIntIty "IT64" = FArith (ATInt (ITFixed IT64))
368zname = sNS (sUN "Z") ["Nat","Prelude"]
369sname = sNS (sUN "S") ["Nat","Prelude"]
371instance ToIR ([Name], SC) where
372 ir (args, tree) = do logLvl 3 $ "Compiling " ++ show args ++ "\n" ++ show tree
374 return $ LLam args tree'
376instance ToIR SC where
380 ir' (UnmatchedCase str) = return $ LError str
381 ir' (ProjCase tm alt) = do tm' <- ir tm
382 alt' <- mkIRAlt tm' alt
383 return $ LCase tm' [alt']
384 ir' (Case n alts) = do alts' <- mapM (mkIRAlt (LV (Glob n))) alts
385 return $ LCase (LV (Glob n)) alts'
386 ir' ImpossibleCase = return LNothing
388 -- special cases for Z and S
389 -- Needs rethink: projections make this fail
390-- mkIRAlt n (ConCase z _ [] rhs) | z == zname
391-- = mkIRAlt n (ConstCase (BI 0) rhs)
392-- mkIRAlt n (ConCase s _ [arg] rhs) | s == sname
395-- return $ LDefaultCase
396-- (LLet arg (LOp LBMinus [n', LConst (BI 1)])
398 mkIRAlt _ (ConCase n t args rhs)
400 return $ LConCase (-1) n args rhs'
401 mkIRAlt _ (ConstCase x rhs)
404 return $ LConstCase x rhs'
407 return $ LDefaultCase rhs'
408 mkIRAlt tm (SucCase n rhs)
410 return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig))
412 LConst (BI 1)]) rhs')
413-- return $ LSucCase n rhs'
414 mkIRAlt _ (ConstCase c rhs)
415 = ifail $ "Can't match on (" ++ show c ++ ")"
416 mkIRAlt _ (DefaultCase rhs)
418 return $ LDefaultCase rhs'
420 matchable (I _) = True
421 matchable (BI _) = True
422 matchable (Ch _) = True
423 matchable (Str _) = True
426 matchableTy (AType (ATInt ITNative)) = True
427 matchableTy (AType (ATInt ITBig)) = True
428 matchableTy (AType (ATInt ITChar)) = True
429 matchableTy StrType = True
431 matchableTy (AType (ATInt (ITFixed IT8))) = True
432 matchableTy (AType (ATInt (ITFixed IT16))) = True
433 matchableTy (AType (ATInt (ITFixed IT32))) = True
434 matchableTy (AType (ATInt (ITFixed IT64))) = True
436 matchableTy _ = False
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list