on e16f741 help sign in
Idris-dev/src/IRTS/Compiler.hs
732 lines 27 kB history raw
1{-|
2Module : IRTS.Compiler
3Description : Coordinates the compilation process.
5License : BSD3
6Maintainer : The Idris Community.
7-}
8{-# LANGUAGE CPP, FlexibleContexts, PatternGuards, TypeSynonymInstances, NamedFieldPuns #-}
10module IRTS.Compiler(compile, generate) where
12import Idris.AbsSyntax
13import Idris.ASTUtils
14import Idris.Core.CaseTree
15import Idris.Core.Evaluate
16import Idris.Core.TT
17import Idris.Erasure
18import Idris.Error
19import Idris.Options
20import Idris.Output
21import IRTS.CodegenC
22import IRTS.CodegenCommon
23import IRTS.Defunctionalise
24import IRTS.DumpBC
25import IRTS.Exports
26import IRTS.Inliner
27import IRTS.LangOpts
28import IRTS.Portable
29import IRTS.Simplified
31import Prelude hiding (id, (.))
33import Control.Category
34import Control.Monad.State
35import Data.List
36import Data.Maybe (maybe)
37import qualified Data.Map as M
38import Data.Ord
39import qualified Data.Set as S
40import System.Directory
41import System.Exit
42import System.IO
43import System.Process
45-- | Compile to simplified forms and return CodegenInfo
46compile :: Codegen -> FilePath -> Maybe Term -> Idris CodegenInfo
47compile codegen f mtm = do
48 logCodeGen 1 "Compiling Output."
49 iReport 2 "Compiling Output."
50 checkMVs -- check for undefined metavariables
51 checkTotality -- refuse to compile if there are totality problems
52 exports <- findExports
53 let rootNames = case mtm of
54 Nothing -> []
55 Just t -> freeNames t
57 logCodeGen 1 "Running Erasure Analysis"
58 iReport 3 "Running Erasure Analysis"
59 reachableNames <- performUsageAnalysis
60 (rootNames ++ getExpNames exports)
61 maindef <- case mtm of
62 Nothing -> return []
63 Just tm -> do md <- irMain tm
64 logCodeGen 1 $ "MAIN: " ++ show md
65 return [(sMN 0 "runMain", md)]
66 objs <- getObjectFiles codegen
67 libs <- getLibs codegen
68 flags <- getFlags codegen
69 hdrs <- getHdrs codegen
70 impdirs <- rankedImportDirs f
71 ttDeclarations <- getDeclarations reachableNames
72 defsIn <- mkDecls reachableNames
73 -- if no 'main term' given, generate interface files
74 let iface = case mtm of
75 Nothing -> True
76 Just _ -> False
78 let defs = defsIn ++ maindef
80 -- Inlined top level LDecl made here
81 let defsInlined = inlineAll defs
82 let defsUniq = map (allocUnique (addAlist defsInlined emptyContext))
83 defsInlined
85 logCodeGen 1 "Inlining"
87 dumpCases <- getDumpCases
88 case dumpCases of
89 Nothing -> return ()
90 Just f -> runIO $ writeFile f (showCaseTrees defsUniq)
92 let (nexttag, tagged) = addTags 65536 (liftAll defsInlined)
93 let ctxtIn = addAlist tagged emptyContext
95 logCodeGen 1 "Defunctionalising"
96 iReport 3 "Defunctionalising"
97 let defuns_in = defunctionalise nexttag ctxtIn
98 logCodeGen 5 $ show defuns_in
99 logCodeGen 1 "Inlining"
100 iReport 3 "Inlining"
101 let defuns = inline defuns_in
102 logCodeGen 5 $ show defuns
103 logCodeGen 1 "Resolving variables for CG"
105 let checked = simplifyDefs defuns (toAlist defuns)
106 outty <- outputTy
107 dumpDefun <- getDumpDefun
108 case dumpDefun of
109 Nothing -> return ()
110 Just f -> runIO $ writeFile f (dumpDefuns defuns)
111 triple <- Idris.AbsSyntax.targetTriple
112 cpu <- Idris.AbsSyntax.targetCPU
113 logCodeGen 1 "Generating Code."
114 iReport 2 "Generating Code."
115 case checked of
116 OK c -> do return $ CodegenInfo f outty triple cpu
117 hdrs impdirs objs libs flags
118 NONE c (toAlist defuns)
119 tagged iface exports
120 ttDeclarations
121 Error e -> ierror e
122 where checkMVs = do i <- getIState
123 case map fst (idris_metavars i) \\ primDefs of
124 [] -> return ()
125 ms -> do iputStrLn $ "WARNING: There are incomplete holes:\n " ++ show ms
126 iputStrLn "\nEvaluation of any of these will crash at run time."
127 return ()
128 checkTotality = do i <- getIState
129 case idris_totcheckfail i of
130 [] -> return ()
131 ((fc, msg):fs) -> ierror . At fc . Msg $ "Cannot compile:\n " ++ msg
133generate :: Codegen -> FilePath -> CodegenInfo -> IO ()
134generate codegen mainmod ir
135 = case codegen of
136 -- Built-in code generators (FIXME: lift these out!)
137 Via _ "c" -> codegenC ir
138 -- Any external code generator
139 Via fm cg -> do input <- case fm of
140 IBCFormat -> return mainmod
141 JSONFormat -> do
142 tempdir <- getTemporaryDirectory
143 (fn, h) <- openTempFile tempdir "idris-cg.json"
144 writePortable h ir
145 hClose h
146 return fn
147 let cmd = "idris-codegen-" ++ cg
148 args = [input, "-o", outputFile ir] ++ compilerFlags ir
149 exit <- rawSystem cmd (if interfaces ir then "--interface" : args else args)
150 when (exit /= ExitSuccess) $
151 putStrLn ("FAILURE: " ++ show cmd ++ " " ++ show args)
152 Bytecode -> dumpBC (simpleDecls ir) (outputFile ir)
154irMain :: TT Name -> Idris LDecl
155irMain tm = do
156 i <- irTerm (sMN 0 "runMain") M.empty [] tm
157 return $ LFun [] (sMN 0 "runMain") [] (LForce i)
159mkDecls :: [Name] -> Idris [(Name, LDecl)]
160mkDecls used
161 = do i <- getIState
162 let ds = filter (\(n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i)
163 decls <- mapM build ds
164 return decls
166getDeclarations :: [Name] -> Idris ([(Name, TTDecl)])
167getDeclarations used
168 = do i <- getIState
169 let ds = filter (\(n, (d,_,_,_,_,_)) -> n `elem` used || isCon d) $ ((toAlist . definitions . tt_ctxt) i)
170 return ds
172showCaseTrees :: [(Name, LDecl)] -> String
173showCaseTrees = showSep "\n\n" . map showCT . sortBy (comparing defnRank)
174 where
175 showCT (n, LFun opts f args lexp)
176 = showOpts ++
177 show n ++ " " ++ showSep " " (map show args) ++ " =\n\t"
178 ++ show lexp
179 where
180 showOpts | Inline `elem` opts = "%inline "
181 | otherwise = ""
182 showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a
184 defnRank :: (Name, LDecl) -> String
185 defnRank (n, LFun _ _ _ _) = "1" ++ nameRank n
186 defnRank (n, LConstructor _ _ _) = "2" ++ nameRank n
188 nameRank :: Name -> String
189 nameRank (UN s) = "1" ++ show s
190 nameRank (MN i s) = "2" ++ show s ++ show i
191 nameRank (NS n ns) = "3" ++ concatMap show (reverse ns) ++ nameRank n
192 nameRank (SN sn) = "4" ++ snRank sn
193 nameRank n = "5" ++ show n
195 snRank :: SpecialName -> String
196 snRank (WhereN i n n') = "1" ++ nameRank n' ++ nameRank n ++ show i
197 snRank (ImplementationN n args) = "2" ++ nameRank n ++ concatMap show args
198 snRank (ParentN n s) = "3" ++ nameRank n ++ show s
199 snRank (MethodN n) = "4" ++ nameRank n
200 snRank (CaseN _ n) = "5" ++ nameRank n
201 snRank (ImplementationCtorN n) = "7" ++ nameRank n
202 snRank (WithN i n) = "8" ++ nameRank n ++ show i
204isCon (TyDecl _ _) = True
205isCon _ = False
207build :: (Name, Def) -> Idris (Name, LDecl)
208build (n, d)
209 = do i <- getIState
210 case getPrim n i of
211 Just (ar, op) ->
212 let args = map (\x -> sMN x "op") [0..] in
213 return (n, (LFun [] n (take ar args)
214 (LOp op (map LV (take ar args)))))
215 _ -> do def <- mkLDecl n d
216 logCodeGen 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def
217 return (n, def)
218 where getPrim n i
219 | Just (ar, op) <- lookup n (idris_scprims i)
220 = Just (ar, op)
221 | Just ar <- lookup n (S.toList (idris_externs i))
222 = Just (ar, LExternal n)
223 getPrim n i = Nothing
225declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x
226declArgs args inl n x = LFun (if inl then [Inline] else []) n args x
228mkLDecl n (Function tm _)
229 = declArgs [] True n <$> irTerm n M.empty [] tm
231mkLDecl n (CaseOp ci _ _ _ pats cd)
232 = declArgs [] (case_inlinable ci || caseName n) n <$> irTree n args sc
233 where
234 (args, sc) = cases_runtime cd
236 -- Always attempt to inline functions arising from 'case' expressions
237 caseName (SN (CaseN _ _)) = True
238 caseName (SN (WithN _ _)) = True
239 caseName (NS n _) = caseName n
240 caseName _ = False
242mkLDecl n (TyDecl (DCon tag arity _) _) =
243 LConstructor n tag . length <$> fgetState (cg_usedpos . ist_callgraph n)
245mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a
246mkLDecl n _ = return $ (declArgs [] True n LNothing) -- postulate, never run
248data VarInfo = VI
249 { viMethod :: Maybe Name
250 }
251 deriving Show
253type Vars = M.Map Name VarInfo
255irTerm :: Name -> Vars -> [Name] -> Term -> Idris LExp
256irTerm top vs env tm@(App _ f a) = do
257 ist <- getIState
258 let (likeNatZ, likeNatS) = getNatLikeCtors ist
259 case unApply tm of
260 (P _ n _, args)
261 | n `elem` map fst (idris_metavars ist) \\ primDefs
262 -> return $ LError $ "ABORT: Attempt to evaluate hole " ++ show n
263 (P _ (UN m) _, args)
264 | m == txt "mkForeignPrim"
265 -> doForeign vs env (reverse (drop 4 args)) -- drop implicits
267 (P _ (UN u) _, [_, arg])
268 | u == txt "unsafePerformPrimIO"
269 -> irTerm top vs env arg
271 (P _ (UN u) _, _)
272 | u == txt "assert_unreachable"
273 -> return $ LError $ "ABORT: Reached an unreachable case in " ++ show top
275 (P _ (UN u) _, [_, msg])
276 | u == txt "idris_crash"
277 -> do msg' <- irTerm top vs env msg
278 return $ LOp LCrash [msg']
280 -- TMP HACK - until we get inlining.
281 (P _ (UN r) _, [_, _, _, _, _, arg])
282 | r == txt "replace"
283 -> irTerm top vs env arg
285 -- 'void' doesn't have any pattern clauses and only gets called on
286 -- erased things in higher order contexts (also a TMP HACK...)
287 (P _ (UN r) _, _)
288 | r == txt "void"
289 -> return LNothing
291 -- Laziness, the old way
292 (P _ (UN l) _, [_, arg])
293 | l == txt "lazy"
294 -> error "lazy has crept in somehow"
296 (P _ (UN l) _, [_, arg])
297 | l == txt "force"
298 -> LForce <$> irTerm top vs env arg
300 -- Laziness, the new way
301 (P _ (UN l) _, [_, _, arg])
302 | l == txt "Delay"
303 -> LLazyExp <$> irTerm top vs env arg
305 (P _ (UN l) _, [_, _, arg])
306 | l == txt "Force"
307 -> LForce <$> irTerm top vs env arg
309 (P _ (UN a) _, [_, _, _, arg])
310 | a == txt "assert_smaller"
311 -> irTerm top vs env arg
313 (P _ (UN a) _, [_, arg])
314 | a == txt "assert_total"
315 -> irTerm top vs env arg
317 (P _ (UN p) _, [_, arg])
318 | p == txt "par"
319 -> do arg' <- irTerm top vs env arg
320 return $ LOp LPar [LLazyExp arg']
322 (P _ (UN pf) _, [arg])
323 | pf == txt "prim_fork"
324 -> do arg' <- irTerm top vs env arg
325 return $ LOp LFork [LLazyExp arg']
327 (P _ (UN m) _, [_,size,t])
328 | m == txt "malloc"
329 -> irTerm top vs env t
331 (P _ (UN tm) _, [_,t])
332 | tm == txt "trace_malloc"
333 -> irTerm top vs env t -- TODO
335 -- This case is here until we get more general inlining. It's just
336 -- a really common case, and the laziness hurts...
337 (P _ (NS (UN be) [b,p]) _, [_,x,(App _ (App _ (App _ (P _ (UN d) _) _) _) t),
338 (App _ (App _ (App _ (P _ (UN d') _) _) _) e)])
339 | be == txt "ifThenElse"
340 , d == txt "Delay"
341 , d' == txt "Delay"
342 , b == txt "Bool"
343 , p == txt "Prelude"
344 -> do
345 x' <- irTerm top vs env x
346 t' <- irTerm top vs env t
347 e' <- irTerm top vs env e
348 return (LCase Shared x'
349 [LConCase 0 (sNS (sUN "False") ["Bool","Prelude"]) [] e'
350 ,LConCase 1 (sNS (sUN "True" ) ["Bool","Prelude"]) [] t'
351 ])
353 -- data constructor
354 (P (DCon t arity _) n _, args) -> do
355 detag <- fgetState (opt_detaggable . ist_optimisation n)
356 used <- map fst <$> fgetState (cg_usedpos . ist_callgraph n)
358 let isNewtype = length used == 1 && detag
359 let argsPruned = [a | (i,a) <- zip [0..] args, i `elem` used]
361 -- The following code removes fields from data constructors
362 -- and performs the newtype optimisation.
363 --
364 -- The general rule here is:
365 -- Everything we get as input is not touched by erasure,
366 -- so it conforms to the official arities and types
367 -- and we can reason about it like it's plain TT.
368 --
369 -- It's only the data that leaves this point that's erased
370 -- and possibly no longer typed as the original TT version.
371 --
372 -- Especially, underapplied constructors must yield functions
373 -- even if all the remaining arguments are erased
374 -- (the resulting function *will* be applied, to NULLs).
375 --
376 -- This will probably need rethinking when we get erasure from functions.
378 -- "padLams" will wrap our term in LLam-bdas and give us
379 -- the "list of future unerased args" coming from these lambdas.
380 --
381 -- We can do whatever we like with the list of unerased args,
382 -- hence it takes a lambda: \unerased_argname_list -> resulting_LExp.
383 let padLams = padLambdas used (length args) arity
385 case compare (length args) arity of
387 -- overapplied
388 GT -> ifail ("overapplied data constructor: " ++ show tm ++
389 "\nDEBUG INFO:\n" ++
390 "Arity: " ++ show arity ++ "\n" ++
391 "Arguments: " ++ show args ++ "\n" ++
392 "Pruned arguments: " ++ show argsPruned)
394 -- exactly saturated
395 EQ | isNewtype
396 -> irTerm top vs env (head argsPruned)
398 -- compile Nat-likes as bigints
399 | n `S.member` likeNatZ
400 -> irTerm top vs env $ Constant (BI 0)
402 -- compile Nat-likes as bigints
403 | n `S.member` likeNatS
404 -> irTerm top vs env $
405 App Complete (P Ref (sUN "prim__addBigInt") Erased) (Constant $ BI 1)
407 | otherwise -- not newtype, plain data ctor
408 -> buildApp (LV n) argsPruned
410 -- not saturated, underapplied
411 LT | isNewtype -- newtype
412 , length argsPruned == 1 -- and we already have the value
413 -> padLams . (\tm [] -> tm) -- the [] asserts there are no unerased args
414 <$> irTerm top vs env (head argsPruned)
416 | isNewtype -- newtype but the value is not among args yet
417 -> return . padLams $ \[vn] -> LApp False (LV n) [LV vn]
419 -- compile Nat-likes as bigints
420 | n `S.member` likeNatS
421 -> irTerm top vs env $
422 App Complete (P Ref (sUN "prim__addBigInt") Erased) (Constant $ BI 1)
424 -- not a newtype, just apply to a constructor
425 | otherwise
426 -> padLams . applyToNames <$> buildApp (LV n) argsPruned
428 -- type constructor
429 (P (TCon t a) n _, args) -> return LNothing
431 -- an external name applied to arguments
432 (P _ n _, args) | S.member (n, length args) (idris_externs ist) -> do
433 LOp (LExternal n) <$> mapM (irTerm top vs env) args
435 -- a name applied to arguments
436 (P _ n _, args) -> do
437 case lookup n (idris_scprims ist) of
438 -- if it's a primitive that is already saturated,
439 -- compile to the corresponding op here already to save work
440 Just (arity, op) | length args == arity
441 -> LOp op <$> mapM (irTerm top vs env) args
443 -- otherwise, just apply the name
444 _ -> applyName n ist args
446 -- turn de bruijn vars into regular named references and try again
447 (V i, args) -> irTerm top vs env $ mkApp (P Bound (env !! i) Erased) args
449 (f, args)
450 -> LApp False
451 <$> irTerm top vs env f
452 <*> mapM (irTerm top vs env) args
454 where
455 buildApp :: LExp -> [Term] -> Idris LExp
456 buildApp e [] = return e
457 buildApp e xs = LApp False e <$> mapM (irTerm top vs env) xs
459 applyToNames :: LExp -> [Name] -> LExp
460 applyToNames tm [] = tm
461 applyToNames tm ns = LApp False tm $ map LV ns
463 padLambdas :: [Int] -> Int -> Int -> ([Name] -> LExp) -> LExp
464 padLambdas used startIdx endSIdx mkTerm
465 = LLam allNames $ mkTerm nonerasedNames
466 where
467 allNames = [sMN i "sat" | i <- [startIdx .. endSIdx-1]]
468 nonerasedNames = [sMN i "sat" | i <- [startIdx .. endSIdx-1], i `elem` used]
470 applyName :: Name -> IState -> [Term] -> Idris LExp
471 applyName n ist args =
472 LApp False (LV n) <$> mapM (irTerm top vs env . erase) (zip [0..] args)
473 where
474 erase (i, x)
475 | i >= arity || i `elem` used = x
476 | otherwise = Erased
478 arity = case fst4 <$> lookupCtxtExact n (definitions . tt_ctxt $ ist) of
479 Just (CaseOp ci ty tys def tot cdefs) -> length tys
480 Just (TyDecl (DCon tag ar _) _) -> ar
481 Just (TyDecl Ref ty) -> length $ getArgTys ty
482 Just (Operator ty ar op) -> ar
483 Just def -> error $ "unknown arity: " ++ show (n, def)
484 Nothing -> 0 -- no definition, probably local name => can't erase anything
486 -- name for purposes of usage info lookup
487 uName
488 | Just n' <- viMethod =<< M.lookup n vs = n'
489 | otherwise = n
491 used = maybe [] (map fst . usedpos) $ lookupCtxtExact uName (idris_callgraph ist)
492 fst4 (x,_,_,_,_,_) = x
494irTerm top vs env (P _ n _) = return $ LV n
495irTerm top vs env (V i)
496 | i >= 0 && i < length env = return $ LV (env!!i)
497 | otherwise = ifail $ "bad de bruijn index: " ++ show i
499irTerm top vs env (Bind n (Lam _ _) sc) = LLam [n'] <$> irTerm top vs (n':env) sc
500 where
501 n' = uniqueName n env
503irTerm top vs env (Bind n (Let _ _ v) sc)
504 = LLet n <$> irTerm top vs env v <*> irTerm top vs (n : env) sc
506irTerm top vs env (Bind _ _ _) = return $ LNothing
508irTerm top vs env (Proj t (-1)) = do
509 t' <- irTerm top vs env t
510 return $ LOp (LMinus (ATInt ITBig))
511 [t', LConst (BI 1)]
513irTerm top vs env (Proj t i) = LProj <$> irTerm top vs env t <*> pure i
514irTerm top vs env (Constant TheWorld) = return LNothing
515irTerm top vs env (Constant c) = return (LConst c)
516irTerm top vs env (TType _) = return LNothing
517irTerm top vs env Erased = return LNothing
518irTerm top vs env Impossible = return LNothing
520getNatLikeCtors :: IState -> (S.Set Name, S.Set Name)
521getNatLikeCtors ist =
522 ( S.fromList $ map fst natLikeTypes
523 , S.fromList $ map snd natLikeTypes
524 )
525 where
526 getUsedCount :: Name -> Int
527 getUsedCount n =
528 maybe 0 (length . usedpos)
529 $ lookupCtxtExact n
530 $ idris_callgraph ist
532 natLikeTypes :: [(Name, Name)]
533 natLikeTypes = do
534 (_typeName, TI{con_names}) <- toAlist $ idris_datatypes ist
535 case con_names of
536 [z, s]
537 | getUsedCount z == 0
538 , getUsedCount s == 1
539 -> [(z, s)]
541 [s, z]
542 | getUsedCount z == 0
543 , getUsedCount s == 1
544 -> [(z, s)]
546 _ -> [] -- not a 2-constructor family
548doForeign :: Vars -> [Name] -> [Term] -> Idris LExp
549doForeign vs env (ret : fname : world : args)
550 = do args' <- mapM splitArg args
551 let fname' = toFDesc fname
552 let ret' = toFDesc ret
553 return $ LForeign ret' fname' args'
554 where
555 splitArg tm | (_, [_,_,l,r]) <- unApply tm -- pair, two implicits
556 = do let l' = toFDesc l
557 r' <- irTerm (sMN 0 "__foreignCall") vs env r
558 return (l', r')
559 splitArg _ = ifail $ "Badly formed foreign function call: " ++
560 show (ret : fname : world : args)
563 toFDesc (Constant (Str str)) = FStr str
564 toFDesc tm
565 | (P _ n _, []) <- unApply tm = FCon (deNS n)
566 | (P _ n _, as) <- unApply tm = FApp (deNS n) (map toFDesc as)
567 toFDesc _ = FUnknown
569 deNS (NS n _) = n
570 deNS n = n
571doForeign vs env xs = ifail "Badly formed foreign function call"
573irTree :: Name -> [Name] -> SC -> Idris LExp
574irTree top args tree = do
575 logCodeGen 3 $ "Compiling " ++ show args ++ "\n" ++ show tree
576 LLam args <$> irSC top M.empty tree
578irSC :: Name -> Vars -> SC -> Idris LExp
579irSC top vs (STerm t) = irTerm top vs [] t
580irSC top vs (UnmatchedCase str) = return $ LError str
582irSC top vs (ProjCase tm alts) = do
583 tm' <- irTerm top vs [] tm
584 alts' <- mapM (irAlt top vs tm') alts
585 return $ LCase Shared tm' alts'
587-- Transform matching on Delay to applications of Force.
588irSC top vs (Case up n [ConCase (UN delay) i [_, _, n'] sc])
589 | delay == txt "Delay"
590 = do sc' <- irSC top vs sc -- mkForce n' n sc
591 return $ lsubst n' (LForce (LV n)) sc'
593-- There are two transformations in this case:
594--
595-- 1. Newtype-case elimination:
596-- case {e0} of
597-- wrap({e1}) -> P({e1}) ==> P({e0})
598--
599-- This is important because newtyped constructors are compiled away entirely
600-- and we need to do that everywhere.
601--
602-- 2. Unused-case elimination (only valid for singleton branches):
603-- case {e0} of ==> P
604-- C(x,y) -> P[... x,y not used ...]
605--
606-- This is important for runtime because sometimes we case on irrelevant data:
607--
608-- In the example above, {e0} will most probably have been erased
609-- so this vain projection would make the resulting program segfault
610-- because the code generator still emits a PROJECT(...) G-machine instruction.
611--
612-- Hence, we check whether the variables are used at all
613-- and erase the casesplit if they are not.
614--
615irSC top vs (Case up n [alt]) = do
616 replacement <- case alt of
617 ConCase cn a ns sc -> do
618 detag <- fgetState (opt_detaggable . ist_optimisation cn)
619 used <- map fst <$> fgetState (cg_usedpos . ist_callgraph cn)
620 if detag && length used == 1
621 then return . Just $ substSC (ns !! head used) n sc
622 else return Nothing
623 _ -> return Nothing
625 case replacement of
626 Just sc -> irSC top vs sc
627 _ -> do
628 alt' <- irAlt top vs (LV n) alt
629 return $ case namesBoundIn alt' `usedIn` subexpr alt' of
630 [] -> subexpr alt' -- strip the unused top-most case
631 _ -> LCase up (LV n) [alt']
632 where
633 namesBoundIn :: LAlt -> [Name]
634 namesBoundIn (LConCase cn i ns sc) = ns
635 namesBoundIn (LConstCase c sc) = []
636 namesBoundIn (LDefaultCase sc) = []
638 subexpr :: LAlt -> LExp
639 subexpr (LConCase _ _ _ e) = e
640 subexpr (LConstCase _ e) = e
641 subexpr (LDefaultCase e) = e
643-- FIXME: When we have a non-singleton case-tree of the form
644--
645-- case {e0} of
646-- C(x) => ...
647-- ... => ...
648--
649-- and C is detaggable (the only constructor of the family), we can be sure
650-- that the first branch will be always taken -- so we add special handling
651-- to remove the dead default branch.
652--
653-- If we don't do so and C is newtype-optimisable, we will miss this newtype
654-- transformation and the resulting code will probably segfault.
655--
656-- This work-around is not entirely optimal; the best approach would be
657-- to ensure that such case trees don't arise in the first place.
658--
659irSC top vs (Case up n alts@[ConCase cn a ns sc, DefaultCase sc']) = do
660 detag <- fgetState (opt_detaggable . ist_optimisation cn)
661 if detag
662 then irSC top vs (Case up n [ConCase cn a ns sc])
663 else LCase up (LV n) <$> mapM (irAlt top vs (LV n)) alts
665irSC top vs sc@(Case up n alts) = do
666 -- check that neither alternative needs the newtype optimisation,
667 -- see comment above
668 goneWrong <- or <$> mapM isDetaggable alts
669 when goneWrong
670 $ ifail ("irSC: non-trivial case-match on detaggable data: " ++ show sc)
672 -- everything okay
673 LCase up (LV n) <$> mapM (irAlt top vs (LV n)) alts
674 where
675 isDetaggable (ConCase cn _ _ _) = fgetState $ opt_detaggable . ist_optimisation cn
676 isDetaggable _ = return False
678irSC top vs ImpossibleCase = return LNothing
680irAlt :: Name -> Vars -> LExp -> CaseAlt -> Idris LAlt
682-- this leaves out all unused arguments of the constructor
683irAlt top vs _ (ConCase n t args sc) = do
684 used <- map fst <$> fgetState (cg_usedpos . ist_callgraph n)
685 let usedArgs = [a | (i,a) <- zip [0..] args, i `elem` used]
686 LConCase (-1) n usedArgs <$> irSC top (methodVars `M.union` vs) sc
687 where
688 methodVars = case n of
689 SN (ImplementationCtorN interfaceName)
690 -> M.fromList [(v, VI
691 { viMethod = Just $ mkFieldName n i
692 }) | (v,i) <- zip args [0..]]
693 _
694 -> M.empty -- not an implementation constructor
696irAlt top vs _ (ConstCase x rhs)
697 | matchable x = LConstCase x <$> irSC top vs rhs
698 | matchableTy x = LDefaultCase <$> irSC top vs rhs
699 where
700 matchable (I _) = True
701 matchable (BI _) = True
702 matchable (Ch _) = True
703 matchable (Str _) = True
704 matchable (B8 _) = True
705 matchable (B16 _) = True
706 matchable (B32 _) = True
707 matchable (B64 _) = True
708 matchable _ = False
710 matchableTy (AType (ATInt ITNative)) = True
711 matchableTy (AType (ATInt ITBig)) = True
712 matchableTy (AType (ATInt ITChar)) = True
713 matchableTy StrType = True
715 matchableTy (AType (ATInt (ITFixed IT8))) = True
716 matchableTy (AType (ATInt (ITFixed IT16))) = True
717 matchableTy (AType (ATInt (ITFixed IT32))) = True
718 matchableTy (AType (ATInt (ITFixed IT64))) = True
720 matchableTy _ = False
722irAlt top vs tm (SucCase n rhs) = do
723 rhs' <- irSC top vs rhs
724 return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig))
725 [tm,
726 LConst (BI 1)]) rhs')
728irAlt top vs _ (ConstCase c rhs)
729 = ifail $ "Can't match on (" ++ show c ++ ")"
731irAlt top vs _ (DefaultCase rhs)
732 = LDefaultCase <$> irSC top vs rhs