1{-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-}
3module IRTS.Compiler where
6import IRTS.Defunctionalise
8import IRTS.CodegenCommon
10import IRTS.CodegenJava
12import IRTS.CodegenJavaScript
14import IRTS.CodegenLLVM
21import Idris.UnusedArgs
28import Control.Monad.State
32import System.Directory
33import System.Environment
34import System.FilePath ((</>), addTrailingPathSeparator)
38compile :: Codegen -> FilePath -> Term -> Idris ()
41 let tmnames = namesUsed (STerm tm)
42 usedIn <- mapM (allNames []) tmnames
43 let used = [UN "prim__subBigInt", UN "prim__addBigInt"] : usedIn
44 defsIn <- mkDecls tm (concat used)
45 findUnusedArgs (concat used)
47 objs <- getObjectFiles codegen
48 libs <- getLibs codegen
49 flags <- getFlags codegen
50 hdrs <- getHdrs codegen
51 impdirs <- allImportDirs
52 let defs = defsIn ++ [(MN 0 "runMain", maindef)]
53 -- iputStrLn $ showSep "\n" (map show defs)
54 let (nexttag, tagged) = addTags 65536 (liftAll defs)
55 let ctxtIn = addAlist tagged emptyContext
56 iLOG "Defunctionalising"
57 let defuns_in = defunctionalise nexttag ctxtIn
58 logLvl 5 $ show defuns_in
60 let defuns = inline defuns_in
61 logLvl 5 $ show defuns
62 iLOG "Resolving variables for CG"
63 -- iputStrLn $ showSep "\n" (map show (toAlist defuns))
64 let checked = checkDefs defuns (toAlist defuns)
66 dumpCases <- getDumpCases
67 dumpDefun <- getDumpDefun
70 Just f -> liftIO $ writeFile f (showCaseTrees tagged)
73 Just f -> liftIO $ writeFile f (dumpDefuns defuns)
74 triple <- targetTriple
77 iLOG "Building output"
79 OK c -> liftIO $ case codegen of
81 codegenC c f outty hdrs
82 (concatMap mkObj objs)
83 (concatMap mkLib libs)
84 (concatMap mkFlag flags ++
85 concatMap incdir impdirs) NONE
87 codegenJava [] c f hdrs libs outty
89 codegenJavaScript JavaScript c f outty
91 codegenJavaScript Node c f outty
92 ViaLLVM -> codegenLLVM c triple cpu optimize f outty
94 Bytecode -> dumpBC c f
96 where checkMVs = do i <- getIState
97 case idris_metavars i \\ primDefs of
99 ms -> ifail $ "There are undefined metavariables: " ++ show ms
100 inDir d h = do let f = d </> h
101 ex <- doesFileExist f
102 if ex then return f else return h
104 mkLib l = "-l" ++ l ++ " "
107 incdir i = "-I" ++ i ++ " "
110irMain :: TT Name -> Idris LDecl
111irMain tm = do i <- ir tm
112 return $ LFun [] (MN 0 "runMain") [] (LForce i)
114allNames :: [Name] -> Name -> Idris [Name]
115allNames ns n | n `elem` ns = return []
116allNames ns n = do i <- getIState
117 case lookupCtxt n (idris_callgraph i) of
118 [ns'] -> do more <- mapM (allNames (n:ns)) (map fst (calls ns'))
119 return (nub (n : concat more))
122mkDecls :: Term -> [Name] -> Idris [(Name, LDecl)]
125 let ds = filter (\ (n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i)
126 mapM traceUnused used
127 decls <- mapM build ds
130showCaseTrees :: [(Name, LDecl)] -> String
131showCaseTrees ds = showSep "\n\n" (map showCT ds)
133 showCT (n, LFun _ f args lexp)
134 = show n ++ " " ++ showSep " " (map show args) ++ " =\n\t "
136 showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a
138isCon (TyDecl _ _) = True
142 ir :: a -> Idris LExp
144build :: (Name, Def) -> Idris (Name, LDecl)
147 case lookup n (idris_scprims i) of
149 let args = map (\x -> MN x "op") [0..] in
150 return (n, (LFun [] n (take ar args)
151 (LOp op (map (LV . Glob) (take ar args)))))
152 _ -> do def <- mkLDecl n d
153 logLvl 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def
156getPrim :: IState -> Name -> [LExp] -> Maybe LExp
157getPrim i n args = case lookup n (idris_scprims i) of
159 if (ar == length args)
160 then return (LOp op args)
164declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x
165declArgs args inl n x = LFun (if inl then [Inline] else []) n args x
167mkLDecl n (Function tm _) = do e <- ir tm
168 return (declArgs [] True n e)
169mkLDecl n (CaseOp ci _ _ pats cd)
170 = let (args, sc) = cases_runtime cd in
171 do e <- ir (args, sc)
172 return (declArgs [] (case_inlinable ci) n e)
173mkLDecl n (TyDecl (DCon t a) _) = return $ LConstructor n t a
174mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a
175mkLDecl n _ = return (LFun [] n [] (LError ("Impossible declaration " ++ show n)))
177instance ToIR (TT Name) where
178 ir tm = ir' [] tm where
180 | (P _ (UN "mkForeignPrim") _, args) <- unApply tm
182 | (P _ (UN "unsafePerformPrimIO") _, [_, arg]) <- unApply tm
184 -- TMP HACK - until we get inlining.
185 | (P _ (UN "replace") _, [_, _, _, _, _, arg]) <- unApply tm
187 | (P _ (UN "lazy") _, [_, arg]) <- unApply tm
188 = do arg' <- ir' env arg
189 return $ LLazyExp arg'
190 | (P _ (UN "assert_smaller") _, [_, _, _, arg]) <- unApply tm
192 | (P _ (UN "par") _, [_, arg]) <- unApply tm
193 = do arg' <- ir' env arg
194 return $ LOp LPar [LLazyExp arg']
195 | (P _ (UN "prim_fork") _, [arg]) <- unApply tm
196 = do arg' <- ir' env arg
197 return $ LOp LFork [LLazyExp arg']
198-- | (P _ (UN "prim__IO") _, [v]) <- unApply tm
199-- = do v' <- ir' env v
201-- | (P _ (UN "prim_io_bind") _, [_,_,v,Bind n (Lam _) sc]) <- unApply tm
202-- = do v' <- ir' env v
203-- sc' <- ir' (n:env) sc
204-- return (LLet n (LForce v') sc')
205-- | (P _ (UN "prim_io_bind") _, [_,_,v,k]) <- unApply tm
206-- = do v' <- ir' env v
208-- return (LApp False k' [LForce v'])
209 | (P _ (UN "malloc") _, [_,size,t]) <- unApply tm
210 = do size' <- ir' env size
212 return t' -- TODO $ malloc_ size' t'
213 | (P _ (UN "trace_malloc") _, [_,t]) <- unApply tm
216-- | (P _ (NS (UN "S") ["Nat", "Prelude"]) _, [k]) <- unApply tm
217-- = do k' <- ir' env k
218-- return (LOp LBPlus [k', LConst (BI 1)])
219 | (P (DCon t a) n _, args) <- unApply tm
220 = irCon env t a n args
221 | (P _ n _, args) <- unApply tm
223 args' <- mapM (ir' env) args
224 case getPrim i n args' of
229 (idris_optimisation i) of
230 [oi] -> collapsible oi
234 (idris_callgraph i) of
235 [CGInfo _ _ _ _ unusedpos] ->
240 else return (LApp False (LV (Glob n))
241 (mkUnused unused 0 args'))
242 | (f, args) <- unApply tm
244 args' <- mapM (ir' env) args
245 return (LApp False f' args')
246 where mkUnused u i [] = []
247 mkUnused u i (x : xs) | i `elem` u = LNothing : mkUnused u (i + 1) xs
248 | otherwise = x : mkUnused u (i + 1) xs
249-- ir' env (P _ (NS (UN "Z") ["Nat", "Prelude"]) _)
250-- = return $ LConst (BI 0)
251 ir' env (P _ n _) = return $ LV (Glob n)
252 ir' env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i))
253 | otherwise = ifail $ "IR fail " ++ show i ++ " " ++ show tm
254 ir' env (Bind n (Lam _) sc)
255 = do let n' = uniqueName n env
256 sc' <- ir' (n' : env) sc
257 return $ LLam [n'] sc'
258 ir' env (Bind n (Let _ v) sc)
259 = do sc' <- ir' (n : env) sc
261 return $ LLet n v' sc'
262 ir' env (Bind _ _ _) = return $ LNothing
263 ir' env (Proj t i) = do t' <- ir' env t
265 ir' env (Constant c) = return $ LConst c
266 ir' env (TType _) = return $ LNothing
267 ir' env Erased = return $ LNothing
268 ir' env Impossible = return $ LNothing
269-- ir' env _ = return $ LError "Impossible"
271 irCon env t arity n args
272 | length args == arity = buildApp env (LV (Glob n)) args
273 | otherwise = let extra = satArgs (arity - length args) in
274 do sc' <- irCon env t arity n
275 (args ++ map (\n -> P Bound n undefined) extra)
276 return $ LLam extra sc'
278 satArgs n = map (\i -> MN i "sat") [1..n]
280 buildApp env e [] = return e
281 buildApp env e xs = do xs' <- mapM (ir' env) xs
282 return $ LApp False e xs'
284 doForeign :: [Name] -> [TT Name] -> Idris LExp
285 doForeign env (_ : fgn : args)
286 | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
287 = let maybeTys = getFTypes fgnArgTys
290 Nothing -> ifail $ "Foreign type specification is not a constant list: " ++ show (fgn:args)
292 args' <- mapM (ir' env) (init args)
293 -- wrap it in a prim__IO
294 -- return $ con_ 0 @@ impossible @@
295 return $ -- LLazyExp $
296 LForeign LANG_C rty fgnName (zip tys args')
297 | otherwise = ifail "Badly formed foreign function call"
299getFTypes :: TT Name -> Maybe [FType]
300getFTypes tm = case unApply tm of
303 fmap (mkIty' ty :) (getFTypes xs)
306mkIty' (P _ (UN ty) _) = mkIty ty
307mkIty' (App (P _ (UN "FIntT") _) (P _ (UN intTy) _)) = mkIntIty intTy
308mkIty' (App (App (P _ (UN "FFunction") _) _) (App (P _ (UN "FAny") _) (App (P _ (UN "IO") _) _))) = FFunctionIO
309mkIty' (App (App (P _ (UN "FFunction") _) _) _) = FFunction
312-- would be better if these FInt types were evaluated at compile time
313-- TODO: add %eval directive for such things
315mkIty "FFloat" = FArith ATFloat
316mkIty "FInt" = mkIntIty "ITNative"
317mkIty "FChar" = mkIntIty "ITChar"
318mkIty "FByte" = mkIntIty "IT8"
319mkIty "FShort" = mkIntIty "IT16"
320mkIty "FLong" = mkIntIty "IT64"
321mkIty "FBits8" = mkIntIty "IT8"
322mkIty "FBits16" = mkIntIty "IT16"
323mkIty "FBits32" = mkIntIty "IT32"
324mkIty "FBits64" = mkIntIty "IT64"
325mkIty "FString" = FString
328mkIty "FFunction" = FFunction
329mkIty "FFunctionIO" = FFunctionIO
330mkIty "FBits8x16" = FArith (ATInt (ITVec IT8 16))
331mkIty "FBits16x8" = FArith (ATInt (ITVec IT16 8))
332mkIty "FBits32x4" = FArith (ATInt (ITVec IT32 4))
333mkIty "FBits64x2" = FArith (ATInt (ITVec IT64 2))
334mkIty x = error $ "Unknown type " ++ x
336mkIntIty "ITNative" = FArith (ATInt ITNative)
337mkIntIty "ITChar" = FArith (ATInt ITChar)
338mkIntIty "IT8" = FArith (ATInt (ITFixed IT8))
339mkIntIty "IT16" = FArith (ATInt (ITFixed IT16))
340mkIntIty "IT32" = FArith (ATInt (ITFixed IT32))
341mkIntIty "IT64" = FArith (ATInt (ITFixed IT64))
343zname = NS (UN "Z") ["Nat","Prelude"]
344sname = NS (UN "S") ["Nat","Prelude"]
346instance ToIR ([Name], SC) where
347 ir (args, tree) = do logLvl 3 $ "Compiling " ++ show args ++ "\n" ++ show tree
349 return $ LLam args tree'
351instance ToIR SC where
355 ir' (UnmatchedCase str) = return $ LError str
356 ir' (ProjCase tm alts) = do tm' <- ir tm
357 alts' <- mapM (mkIRAlt tm') alts
358 return $ LCase tm' alts'
359 ir' (Case n alts) = do alts' <- mapM (mkIRAlt (LV (Glob n))) alts
360 return $ LCase (LV (Glob n)) alts'
361 ir' ImpossibleCase = return LNothing
363 -- special cases for Z and S
364 -- Needs rethink: projections make this fail
365-- mkIRAlt n (ConCase z _ [] rhs) | z == zname
366-- = mkIRAlt n (ConstCase (BI 0) rhs)
367-- mkIRAlt n (ConCase s _ [arg] rhs) | s == sname
370-- return $ LDefaultCase
371-- (LLet arg (LOp LBMinus [n', LConst (BI 1)])
373 mkIRAlt _ (ConCase n t args rhs)
375 return $ LConCase (-1) n args rhs'
376 mkIRAlt _ (ConstCase x rhs)
379 return $ LConstCase x rhs'
382 return $ LDefaultCase rhs'
383 mkIRAlt tm (SucCase n rhs)
385 return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig))
387 LConst (BI 1)]) rhs')
388-- return $ LSucCase n rhs'
389 mkIRAlt _ (ConstCase c rhs)
390 = ifail $ "Can't match on (" ++ show c ++ ")"
391 mkIRAlt _ (DefaultCase rhs)
393 return $ LDefaultCase rhs'
395 matchable (I _) = True
396 matchable (BI _) = True
397 matchable (Ch _) = True
398 matchable (Str _) = True
401 matchableTy (AType (ATInt ITNative)) = True
402 matchableTy (AType (ATInt ITBig)) = True
403 matchableTy (AType (ATInt ITChar)) = True
404 matchableTy StrType = True
406 matchableTy (AType (ATInt (ITFixed IT8))) = True
407 matchableTy (AType (ATInt (ITFixed IT16))) = True
408 matchableTy (AType (ATInt (ITFixed IT32))) = True
409 matchableTy (AType (ATInt (ITFixed IT64))) = True
411 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