on 6412ae4 help sign in
Idris-dev/src/Core/Evaluate.hs
899 lines 39 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances,
2 PatternGuards #-}
4module Core.Evaluate(normalise, normaliseTrace, normaliseC, normaliseAll,
5 rt_simplify, simplify, specialise, hnf, convEq, convEq',
6 Def(..), CaseInfo(..), CaseDefs(..),
7 Accessibility(..), Totality(..), PReason(..),
8 Context, initContext, ctxtAlist, uconstraints, next_tvar,
9 addToCtxt, setAccess, setTotal, addCtxtDef, addTyDecl,
10 addDatatype, addCasedef, simplifyCasedef, addOperator,
11 lookupNames, lookupTy, lookupP, lookupDef, lookupDefAcc, lookupVal,
12 lookupTotal, lookupTyEnv, isDConName, isTConName, isConName, isFnName,
13 Value(..), Quote(..), initEval) where
15import Debug.Trace
16import Control.Monad.State
17import qualified Data.Binary as B
18import Data.Binary hiding (get, put)
20import Core.TT
21import Core.CaseTree
23data EvalState = ES { limited :: [(Name, Int)],
24 nexthole :: Int }
25 deriving Show
27type Eval a = State EvalState a
29data EvalOpt = Spec
30 | HNF
31 | Simplify
32 | AtREPL
33 | RunTT
34 deriving (Show, Eq)
36initEval = ES [] 0
38-- VALUES (as HOAS) ---------------------------------------------------------
39-- | A HOAS representation of values
40data Value = VP NameType Name Value
41 | VV Int
42 -- True for Bool indicates safe to reduce
43 | VBind Bool Name (Binder Value) (Value -> Eval Value)
44 -- For frozen let bindings when simplifying
45 | VBLet Int Name Value Value Value
46 | VApp Value Value
47 | VType UExp
48 | VErased
49 | VImpossible
50 | VConstant Const
51 | VProj Value Int
52-- | VLazy Env [Value] Term
53 | VTmp Int
55instance Show Value where
56 show x = show $ evalState (quote 100 x) initEval
58instance Show (a -> b) where
59 show x = "<<fn>>"
61-- THE EVALUATOR ------------------------------------------------------------
63-- The environment is assumed to be "locally named" - i.e., not de Bruijn
64-- indexed.
65-- i.e. it's an intermediate environment that we have while type checking or
66-- while building a proof.
68-- | Normalise fully type checked terms (so, assume all names/let bindings resolved)
69normaliseC :: Context -> Env -> TT Name -> TT Name
70normaliseC ctxt env t
71 = evalState (do val <- eval False ctxt [] env t []
72 quote 0 val) initEval
74normaliseAll :: Context -> Env -> TT Name -> TT Name
75normaliseAll ctxt env t
76 = evalState (do val <- eval False ctxt [] env t [AtREPL]
77 quote 0 val) initEval
79normalise :: Context -> Env -> TT Name -> TT Name
80normalise = normaliseTrace False
82normaliseTrace :: Bool -> Context -> Env -> TT Name -> TT Name
83normaliseTrace tr ctxt env t
84 = evalState (do val <- eval tr ctxt [] (map finalEntry env) (finalise t) []
85 quote 0 val) initEval
87specialise :: Context -> Env -> [(Name, Int)] -> TT Name -> TT Name
88specialise ctxt env limits t
89 = evalState (do val <- eval False ctxt []
90 (map finalEntry env) (finalise t)
91 [Spec]
92 quote 0 val) (initEval { limited = limits })
94-- | Like normalise, but we only reduce functions that are marked as okay to
95-- inline (and probably shouldn't reduce lets?)
96-- 20130908: now only used to reduce for totality checking. Inlining should
97-- be done elsewhere.
99simplify :: Context -> Env -> TT Name -> TT Name
100simplify ctxt env t
101 = evalState (do val <- eval False ctxt [(UN "lazy", 0),
102 (UN "assert_smaller", 0),
103 (UN "par", 0),
104 (UN "prim__syntactic_eq", 0),
105 (UN "fork", 0)]
106 (map finalEntry env) (finalise t)
107 [Simplify]
108 quote 0 val) initEval
110-- | Simplify for run-time (i.e. basic inlining)
111rt_simplify :: Context -> Env -> TT Name -> TT Name
112rt_simplify ctxt env t
113 = evalState (do val <- eval False ctxt [(UN "lazy", 0),
114 (UN "assert_smaller", 0),
115 (UN "par", 0),
116 (UN "prim__syntactic_eq", 0),
117 (UN "prim_fork", 0)]
118 (map finalEntry env) (finalise t)
119 [RunTT]
120 quote 0 val) initEval
122-- | Reduce a term to head normal form
123hnf :: Context -> Env -> TT Name -> TT Name
124hnf ctxt env t
125 = evalState (do val <- eval False ctxt []
126 (map finalEntry env)
127 (finalise t) [HNF]
128 quote 0 val) initEval
131-- unbindEnv env (quote 0 (eval ctxt (bindEnv env t)))
133finalEntry :: (Name, Binder (TT Name)) -> (Name, Binder (TT Name))
134finalEntry (n, b) = (n, fmap finalise b)
136bindEnv :: EnvTT n -> TT n -> TT n
137bindEnv [] tm = tm
138bindEnv ((n, Let t v):bs) tm = Bind n (NLet t v) (bindEnv bs tm)
139bindEnv ((n, b):bs) tm = Bind n b (bindEnv bs tm)
141unbindEnv :: EnvTT n -> TT n -> TT n
142unbindEnv [] tm = tm
143unbindEnv (_:bs) (Bind n b sc) = unbindEnv bs sc
145usable :: Bool -- specialising
146 -> Name -> [(Name, Int)] -> Eval (Bool, [(Name, Int)])
147-- usable _ _ ns@((MN 0 "STOP", _) : _) = return (False, ns)
148usable False n [] = return (True, [])
149usable True n ns
150 = do ES ls num <- get
151 case lookup n ls of
152 Just 0 -> return (False, ns)
153 Just i -> return (True, ns)
154 _ -> return (True, ns)
155usable False n ns
156 = case lookup n ns of
157 Just 0 -> return (False, ns)
158 Just i -> return $ (True, (n, abs (i-1)) : filter (\ (n', _) -> n/=n') ns)
159 _ -> return $ (True, (n, 100) : filter (\ (n', _) -> n/=n') ns)
162deduct :: Name -> Eval ()
163deduct n = do ES ls num <- get
164 case lookup n ls of
165 Just i -> do put $ ES ((n, (i-1)) :
166 filter (\ (n', _) -> n/=n') ls) num
167 _ -> return ()
169-- | Evaluate in a context of locally named things (i.e. not de Bruijn indexed,
170-- such as we might have during construction of a proof)
172-- The (Name, Int) pair in the arguments is the maximum depth of unfolding of
173-- a name. The corresponding pair in the state is the maximum number of
174-- unfoldings overall.
176eval :: Bool -> Context -> [(Name, Int)] -> Env -> TT Name ->
177 [EvalOpt] -> Eval Value
178eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
179 spec = Spec `elem` opts
180 simpl = Simplify `elem` opts
181 runtime = RunTT `elem` opts
182 atRepl = AtREPL `elem` opts
183 hnf = HNF `elem` opts
185 -- returns 'True' if the function should block
186 -- normal evaluation should return false
187 blockSimplify (CaseInfo inl dict) n stk
188 | RunTT `elem` opts
189 = not (inl || dict) || elem n stk
190 | Simplify `elem` opts
191 = (not (inl || dict) || elem n stk)
192 || (n == UN "prim__syntactic_eq")
193 | otherwise = False
195 getCases cd | simpl = cases_totcheck cd
196 | runtime = cases_runtime cd
197 | otherwise = cases_compiletime cd
199 ev ntimes stk top env (P _ n ty)
200 | Just (Let t v) <- lookup n genv = ev ntimes stk top env v
201 ev ntimes_in stk top env (P Ref n ty)
202 | not top && hnf = liftM (VP Ref n) (ev ntimes stk top env ty)
203 | otherwise
204 = do (u, ntimes) <- usable spec n ntimes_in
205 if u then
206 do let val = lookupDefAcc n (spec || atRepl) ctxt
207 case val of
208 [(Function _ tm, Public)] ->
209 ev ntimes (n:stk) True env tm
210 [(TyDecl nt ty, _)] -> do vty <- ev ntimes stk True env ty
211 return $ VP nt n vty
212 [(CaseOp ci _ _ _ cd, acc)]
213 | acc == Public &&
214 null (fst (cases_totcheck cd)) -> -- unoptimised version
215 let (ns, tree) = getCases cd in
216 if blockSimplify ci n stk
217 then liftM (VP Ref n) (ev ntimes stk top env ty)
218 else -- traceWhen runtime (show (n, ns, tree)) $
219 do c <- evCase ntimes n (n:stk) top env ns [] tree
220 case c of
221 (Nothing, _) -> liftM (VP Ref n) (ev ntimes stk top env ty)
222 (Just v, _) -> return v
223 _ -> liftM (VP Ref n) (ev ntimes stk top env ty)
224 else liftM (VP Ref n) (ev ntimes stk top env ty)
225 ev ntimes stk top env (P nt n ty)
226 = liftM (VP nt n) (ev ntimes stk top env ty)
227 ev ntimes stk top env (V i)
228 | i < length env && i >= 0 = return $ env !! i
229 | otherwise = return $ VV i
230 ev ntimes stk top env (Bind n (Let t v) sc)
231 = do v' <- ev ntimes stk top env v --(finalise v)
232 sc' <- ev ntimes stk top (v' : env) sc
233 wknV (-1) sc'
234-- | otherwise
235-- = do t' <- ev ntimes stk top env t
236-- v' <- ev ntimes stk top env v --(finalise v)
237-- -- use Tmp as a placeholder, then make it a variable reference
238-- -- again when evaluation finished
239-- hs <- get
240-- let vd = nexthole hs
241-- put (hs { nexthole = vd + 1 })
242-- sc' <- ev ntimes stk top (VP Bound (MN vd "vlet") VErased : env) sc
243-- return $ VBLet vd n t' v' sc'
244 ev ntimes stk top env (Bind n (NLet t v) sc)
245 = do t' <- ev ntimes stk top env (finalise t)
246 v' <- ev ntimes stk top env (finalise v)
247 sc' <- ev ntimes stk top (v' : env) sc
248 return $ VBind True n (Let t' v') (\x -> return sc')
249 ev ntimes stk top env (Bind n b sc)
250 = do b' <- vbind env b
251 return $ VBind True -- (vinstances 0 sc < 2)
252 n b' (\x -> ev ntimes stk False (x:env) sc)
253 where vbind env t
254-- | simpl
255-- = fmapMB (\tm -> ev ((MN 0 "STOP", 0) : ntimes)
256-- stk top env (finalise tm)) t
257-- | otherwise
258 = fmapMB (\tm -> ev ntimes stk top env (finalise tm)) t
259 ev ntimes stk top env (App f a)
260 = do f' <- ev ntimes stk False env f
261 a' <- ev ntimes stk False env a
262 evApply ntimes stk top env [a'] f'
263 ev ntimes stk top env (Proj t i)
264 = do -- evaluate dictionaries if it means the projection works
265 t' <- ev ntimes stk top env t
266-- tfull' <- reapply ntimes stk top env t' []
267 return (doProj t' (getValArgs t'))
268 where doProj t' (VP (DCon _ _) _ _, args) | i < length args = args!!i
269 doProj t' _ = VProj t' i
271 ev ntimes stk top env (Constant c) = return $ VConstant c
272 ev ntimes stk top env Erased = return VErased
273 ev ntimes stk top env Impossible = return VImpossible
274 ev ntimes stk top env (TType i) = return $ VType i
276 evApply ntimes stk top env args (VApp f a)
277 = evApply ntimes stk top env (a:args) f
278 evApply ntimes stk top env args f
279 = apply ntimes stk top env f args
281 reapply ntimes stk top env f@(VP Ref n ty) args
282 = let val = lookupDefAcc n (spec || atRepl) ctxt in
283 case val of
284 [(CaseOp ci _ _ _ cd, acc)] ->
285 let (ns, tree) = getCases cd in
286 do c <- evCase ntimes n (n:stk) top env ns args tree
287 case c of
288 (Nothing, _) -> return $ unload env (VP Ref n ty) args
289 (Just v, rest) -> evApply ntimes stk top env rest v
290 _ -> case args of
291 (a : as) -> return $ unload env f (a : as)
292 [] -> return f
293 reapply ntimes stk top env (VApp f a) args
294 = reapply ntimes stk top env f (a : args)
295 reapply ntimes stk top env v args = return v
297 apply ntimes stk top env (VBind True n (Lam t) sc) (a:as)
298 = do a' <- sc a
299 app <- apply ntimes stk top env a' as
300 wknV (-1) app
301 apply ntimes_in stk top env f@(VP Ref n ty) args
302 | not top && hnf = case args of
303 [] -> return f
304 _ -> return $ unload env f args
305 | otherwise
306 = do (u, ntimes) <- usable spec n ntimes_in
307 if u then
308 do let val = lookupDefAcc n (spec || atRepl) ctxt
309 case val of
310 [(CaseOp ci _ _ _ cd, acc)]
311 | acc == Public -> -- unoptimised version
312 let (ns, tree) = getCases cd in
313 if blockSimplify ci n stk
314 then return $ unload env (VP Ref n ty) args
315 else -- traceWhen runtime (show (n, ns, tree)) $
316 do c <- evCase ntimes n (n:stk) top env ns args tree
317 case c of
318 (Nothing, _) -> return $ unload env (VP Ref n ty) args
319 (Just v, rest) -> evApply ntimes stk top env rest v
320 [(Operator _ i op, _)] ->
321 if (i <= length args)
322 then case op (take i args) of
323 Nothing -> return $ unload env (VP Ref n ty) args
324 Just v -> evApply ntimes stk top env (drop i args) v
325 else return $ unload env (VP Ref n ty) args
326 _ -> case args of
327 [] -> return f
328 _ -> return $ unload env f args
329 else case args of
330 (a : as) -> return $ unload env f (a:as)
331 [] -> return f
332 apply ntimes stk top env f (a:as) = return $ unload env f (a:as)
333 apply ntimes stk top env f [] = return f
335-- specApply stk env f@(VP Ref n ty) args
336-- = case lookupCtxt n statics of
337-- [as] -> if or as
338-- then trace (show (n, map fst (filter (\ (_, s) -> s) (zip args as)))) $
339-- return $ unload env f args
340-- else return $ unload env f args
341-- _ -> return $ unload env f args
342-- specApply stk env f args = return $ unload env f args
344 unload :: [Value] -> Value -> [Value] -> Value
345 unload env f [] = f
346 unload env f (a:as) = unload env (VApp f a) as
348 evCase ntimes n stk top env ns args tree
349 | length ns <= length args
350 = do let args' = take (length ns) args
351 let rest = drop (length ns) args
352 when spec $ deduct n -- successful, so deduct usages
353 t <- evTree ntimes stk top env (zip ns args') tree
354-- (zipWith (\n , t) -> (n, t)) ns args') tree
355 return (t, rest)
356 | otherwise = return (Nothing, args)
358 evTree :: [(Name, Int)] -> [Name] -> Bool ->
359 [Value] -> [(Name, Value)] -> SC -> Eval (Maybe Value)
360 evTree ntimes stk top env amap (UnmatchedCase str) = return Nothing
361 evTree ntimes stk top env amap (STerm tm)
362 = do let etm = pToVs (map fst amap) tm
363 etm' <- ev ntimes stk (not (conHeaded tm))
364 (map snd amap ++ env) etm
365 return $ Just etm'
366 evTree ntimes stk top env amap (ProjCase t alts)
367 = do t' <- ev ntimes stk top env t
368 doCase ntimes stk top env amap t' alts
369 evTree ntimes stk top env amap (Case n alts)
370 = case lookup n amap of
371 Just v -> doCase ntimes stk top env amap v alts
372 _ -> return Nothing
373 evTree ntimes stk top env amap ImpossibleCase = return Nothing
375 doCase ntimes stk top env amap v alts =
376 do c <- chooseAlt env v (getValArgs v) alts amap
377 case c of
378 Just (altmap, sc) -> evTree ntimes stk top env altmap sc
379 _ -> do c' <- chooseAlt' ntimes stk env v (getValArgs v) alts amap
380 case c' of
381 Just (altmap, sc) -> evTree ntimes stk top env altmap sc
382 _ -> return Nothing
384 conHeaded tm@(App _ _)
385 | (P (DCon _ _) _ _, args) <- unApply tm = True
386 conHeaded t = False
388 chooseAlt' ntimes stk env _ (f, args) alts amap
389 = do f' <- apply ntimes stk True env f args
390 chooseAlt env f' (getValArgs f')
391 alts amap
393 chooseAlt :: [Value] -> Value -> (Value, [Value]) -> [CaseAlt] ->
394 [(Name, Value)] ->
395 Eval (Maybe ([(Name, Value)], SC))
396 chooseAlt env _ (VP (DCon i a) _ _, args) alts amap
397 | Just (ns, sc) <- findTag i alts = return $ Just (updateAmap (zip ns args) amap, sc)
398 | Just v <- findDefault alts = return $ Just (amap, v)
399 chooseAlt env _ (VP (TCon i a) _ _, args) alts amap
400 | Just (ns, sc) <- findTag i alts
401 = return $ Just (updateAmap (zip ns args) amap, sc)
402 | Just v <- findDefault alts = return $ Just (amap, v)
403 chooseAlt env _ (VConstant c, []) alts amap
404 | Just v <- findConst c alts = return $ Just (amap, v)
405 | Just (n', sub, sc) <- findSuc c alts
406 = return $ Just (updateAmap [(n',sub)] amap, sc)
407 | Just v <- findDefault alts = return $ Just (amap, v)
408 chooseAlt env _ (VP _ n _, args) alts amap
409 | Just (ns, sc) <- findFn n alts = return $ Just (updateAmap (zip ns args) amap, sc)
410 chooseAlt env _ (VBind _ _ (Pi s) t, []) alts amap
411 | Just (ns, sc) <- findFn (UN "->") alts
412 = do t' <- t (VV 0) -- we know it's not in scope or it's not a pattern
413 return $ Just (updateAmap (zip ns [s, t']) amap, sc)
414 chooseAlt _ _ _ alts amap
415 | Just v <- findDefault alts
416 = if (any fnCase alts)
417 then return $ Just (amap, v)
418 else return Nothing
419 | otherwise = return Nothing
421 fnCase (FnCase _ _ _) = True
422 fnCase _ = False
424 -- Replace old variable names in the map with new matches
425 -- (This is possibly unnecessary since we make unique names and don't
426 -- allow repeated variables...?)
427 updateAmap newm amap
428 = newm ++ filter (\ (x, _) -> not (elem x (map fst newm))) amap
429 findTag i [] = Nothing
430 findTag i (ConCase n j ns sc : xs) | i == j = Just (ns, sc)
431 findTag i (_ : xs) = findTag i xs
433 findFn fn [] = Nothing
434 findFn fn (FnCase n ns sc : xs) | fn == n = Just (ns, sc)
435 findFn fn (_ : xs) = findFn fn xs
437 findDefault [] = Nothing
438 findDefault (DefaultCase sc : xs) = Just sc
439 findDefault (_ : xs) = findDefault xs
441 findSuc c [] = Nothing
442 findSuc (BI val) (SucCase n sc : _)
443 | val /= 0 = Just (n, VConstant (BI (val - 1)), sc)
444 findSuc c (_ : xs) = findSuc c xs
446 findConst c [] = Nothing
447 findConst c (ConstCase c' v : xs) | c == c' = Just v
448 findConst (AType (ATInt ITNative)) (ConCase n 1 [] v : xs) = Just v
449 findConst (AType ATFloat) (ConCase n 2 [] v : xs) = Just v
450 findConst (AType (ATInt ITChar)) (ConCase n 3 [] v : xs) = Just v
451 findConst StrType (ConCase n 4 [] v : xs) = Just v
452 findConst PtrType (ConCase n 5 [] v : xs) = Just v
453 findConst (AType (ATInt ITBig)) (ConCase n 6 [] v : xs) = Just v
454 findConst (AType (ATInt (ITFixed ity))) (ConCase n tag [] v : xs)
455 | tag == 7 + fromEnum ity = Just v
456 findConst (AType (ATInt (ITVec ity count))) (ConCase n tag [] v : xs)
457 | tag == (fromEnum ity + 1) * 1000 + count = Just v
458 findConst c (_ : xs) = findConst c xs
460 getValArgs tm = getValArgs' tm []
461 getValArgs' (VApp f a) as = getValArgs' f (a:as)
462 getValArgs' f as = (f, as)
464-- tmpToV i vd (VLetHole j) | vd == j = return $ VV i
465-- tmpToV i vd (VP nt n v) = liftM (VP nt n) (tmpToV i vd v)
466-- tmpToV i vd (VBind n b sc) = do b' <- fmapMB (tmpToV i vd) b
467-- let sc' = \x -> do x' <- sc x
468-- tmpToV (i + 1) vd x'
469-- return (VBind n b' sc')
470-- tmpToV i vd (VApp f a) = liftM2 VApp (tmpToV i vd f) (tmpToV i vd a)
471-- tmpToV i vd x = return x
473instance Eq Value where
474 (==) x y = getTT x == getTT y
475 where getTT v = evalState (quote 0 v) initEval
477class Quote a where
478 quote :: Int -> a -> Eval (TT Name)
480instance Quote Value where
481 quote i (VP nt n v) = liftM (P nt n) (quote i v)
482 quote i (VV x) = return $ V x
483 quote i (VBind _ n b sc) = do sc' <- sc (VTmp i)
484 b' <- quoteB b
485 liftM (Bind n b') (quote (i+1) sc')
486 where quoteB t = fmapMB (quote i) t
487 quote i (VBLet vd n t v sc)
488 = do sc' <- quote i sc
489 t' <- quote i t
490 v' <- quote i v
491 let sc'' = pToV (MN vd "vlet") (addBinder sc')
492 return (Bind n (Let t' v') sc'')
493 quote i (VApp f a) = liftM2 App (quote i f) (quote i a)
494 quote i (VType u) = return $ TType u
495 quote i VErased = return $ Erased
496 quote i VImpossible = return $ Impossible
497 quote i (VProj v j) = do v' <- quote i v
498 return (Proj v' j)
499 quote i (VConstant c) = return $ Constant c
500 quote i (VTmp x) = return $ V (i - x - 1)
502wknV :: Int -> Value -> Eval Value
503wknV i (VV x) = return $ VV (x + i)
504wknV i (VBind red n b sc) = do b' <- fmapMB (wknV i) b
505 return $ VBind red n b' (\x -> do x' <- sc x
506 wknV i x')
507wknV i (VApp f a) = liftM2 VApp (wknV i f) (wknV i a)
508wknV i t = return t
510convEq' ctxt x y = evalStateT (convEq ctxt x y) (0, [])
512convEq :: Context -> TT Name -> TT Name -> StateT UCs TC Bool
513convEq ctxt = ceq [] where
514 ceq :: [(Name, Name)] -> TT Name -> TT Name -> StateT UCs TC Bool
515 ceq ps (P xt x _) (P yt y _)
516 | x == y || (x, y) `elem` ps || (y,x) `elem` ps = return True
517 | otherwise = sameDefs ps x y
518 ceq ps x (Bind n (Lam t) (App y (V 0))) = ceq ps x y
519 ceq ps (Bind n (Lam t) (App x (V 0))) y = ceq ps x y
520 ceq ps x (Bind n (Lam t) (App y (P Bound n' _)))
521 | n == n' = ceq ps x y
522 ceq ps (Bind n (Lam t) (App x (P Bound n' _))) y
523 | n == n' = ceq ps x y
524 ceq ps (V x) (V y) = return (x == y)
525 ceq ps (Bind _ xb xs) (Bind _ yb ys)
526 = liftM2 (&&) (ceqB ps xb yb) (ceq ps xs ys)
527 where
528 ceqB ps (Let v t) (Let v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')
529 ceqB ps (Guess v t) (Guess v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')
530 ceqB ps b b' = ceq ps (binderTy b) (binderTy b')
531 ceq ps (App fx ax) (App fy ay) = liftM2 (&&) (ceq ps fx fy) (ceq ps ax ay)
532 ceq ps (Constant x) (Constant y) = return (x == y)
533 ceq ps (TType x) (TType y) = do (v, cs) <- get
534 put (v, ULE x y : cs)
535 return True
536 ceq ps Erased _ = return True
537 ceq ps _ Erased = return True
538 ceq ps _ _ = return False
540 caseeq ps (Case n cs) (Case n' cs') = caseeqA ((n,n'):ps) cs cs'
541 where
542 caseeqA ps (ConCase x i as sc : rest) (ConCase x' i' as' sc' : rest')
543 = do q1 <- caseeq (zip as as' ++ ps) sc sc'
544 q2 <- caseeqA ps rest rest'
545 return $ x == x' && i == i' && q1 && q2
546 caseeqA ps (ConstCase x sc : rest) (ConstCase x' sc' : rest')
547 = do q1 <- caseeq ps sc sc'
548 q2 <- caseeqA ps rest rest'
549 return $ x == x' && q1 && q2
550 caseeqA ps (DefaultCase sc : rest) (DefaultCase sc' : rest')
551 = liftM2 (&&) (caseeq ps sc sc') (caseeqA ps rest rest')
552 caseeqA ps [] [] = return True
553 caseeqA ps _ _ = return False
554 caseeq ps (STerm x) (STerm y) = ceq ps x y
555 caseeq ps (UnmatchedCase _) (UnmatchedCase _) = return True
556 caseeq ps _ _ = return False
558 sameDefs ps x y = case (lookupDef x ctxt, lookupDef y ctxt) of
559 ([Function _ xdef], [Function _ ydef])
560 -> ceq ((x,y):ps) xdef ydef
561 ([CaseOp _ _ _ _ xd],
562 [CaseOp _ _ _ _ yd])
563 -> let (_, xdef) = cases_compiletime xd
564 (_, ydef) = cases_compiletime yd in
565 caseeq ((x,y):ps) xdef ydef
566 _ -> return False
568-- SPECIALISATION -----------------------------------------------------------
569-- We need too much control to be able to do this by tweaking the main
570-- evaluator
572spec :: Context -> Ctxt [Bool] -> Env -> TT Name -> Eval (TT Name)
573spec ctxt statics genv tm = error "spec undefined"
575-- CONTEXTS -----------------------------------------------------------------
577{-| A definition is either a simple function (just an expression with a type),
578 a constant, which could be a data or type constructor, an axiom or as an
579 yet undefined function, or an Operator.
580 An Operator is a function which explains how to reduce.
581 A CaseOp is a function defined by a simple case tree -}
583data Def = Function Type Term
584 | TyDecl NameType Type
585 | Operator Type Int ([Value] -> Maybe Value)
586 | CaseOp CaseInfo
587 Type
588 [Either Term (Term, Term)] -- original definition
589 [([Name], Term, Term)] -- simplified for totality check definition
590 CaseDefs
591-- [Name] SC -- Compile time case definition
592-- [Name] SC -- Run time cae definitions
594data CaseDefs = CaseDefs {
595 cases_totcheck :: ([Name], SC),
596 cases_compiletime :: ([Name], SC),
597 cases_inlined :: ([Name], SC),
598 cases_runtime :: ([Name], SC)
599 }
601data CaseInfo = CaseInfo {
602 case_inlinable :: Bool,
603 tc_dictionary :: Bool
604 }
606{-!
607deriving instance Binary Def
608!-}
609{-!
610deriving instance Binary CaseInfo
611!-}
612{-!
613deriving instance Binary CaseDefs
614!-}
616instance Show Def where
617 show (Function ty tm) = "Function: " ++ show (ty, tm)
618 show (TyDecl nt ty) = "TyDecl: " ++ show nt ++ " " ++ show ty
619 show (Operator ty _ _) = "Operator: " ++ show ty
620 show (CaseOp (CaseInfo inlc inlr) ty ps_in ps cd)
621 = let (ns, sc) = cases_compiletime cd
622 (ns_t, sc_t) = cases_totcheck cd
623 (ns', sc') = cases_runtime cd in
624 "Case: " ++ show ty ++ " " ++ show ps ++ "\n" ++
625 "TOTALITY CHECK TIME:\n\n" ++
626 show ns_t ++ " " ++ show sc_t ++ "\n\n" ++
627 "COMPILE TIME:\n\n" ++
628 show ns ++ " " ++ show sc ++ "\n\n" ++
629 "RUN TIME:\n\n" ++
630 show ns' ++ " " ++ show sc' ++ "\n\n" ++
631 if inlc then "Inlinable\n" else "Not inlinable\n"
633-- We need this for serialising Def. Fortunately, it never gets used because
634-- we'll never serialise a primitive operator
636instance Binary (a -> b) where
637 put x = return ()
638 get = error "Getting a function"
640-------
642-- Frozen => doesn't reduce
643-- Hidden => doesn't reduce and invisible to type checker
645data Accessibility = Public | Frozen | Hidden
646 deriving (Show, Eq)
648-- | The result of totality checking
649data Totality = Total [Int] -- ^ well-founded arguments
650 | Productive -- ^ productive
651 | Partial PReason
652 | Unchecked
653 deriving Eq
655-- | Reasons why a function may not be total
656data PReason = Other [Name] | Itself | NotCovering | NotPositive | UseUndef Name
657 | BelieveMe | Mutual [Name] | NotProductive
658 deriving (Show, Eq)
660instance Show Totality where
661 show (Total args)= "Total" -- ++ show args ++ " decreasing arguments"
662 show Productive = "Productive" -- ++ show args ++ " decreasing arguments"
663 show Unchecked = "not yet checked for totality"
664 show (Partial Itself) = "possibly not total as it is not well founded"
665 show (Partial NotCovering) = "not total as there are missing cases"
666 show (Partial NotPositive) = "not strictly positive"
667 show (Partial NotProductive) = "not productive"
668 show (Partial BelieveMe) = "not total due to use of believe_me in proof"
669 show (Partial (Other ns)) = "possibly not total due to: " ++ showSep ", " (map show ns)
670 show (Partial (Mutual ns)) = "possibly not total due to recursive path " ++
671 showSep " --> " (map show ns)
673{-!
674deriving instance Binary Accessibility
675!-}
677{-!
678deriving instance Binary Totality
679!-}
681{-!
682deriving instance Binary PReason
683!-}
685-- | Contexts used for global definitions and for proof state. They contain
686-- universe constraints and existing definitions.
687data Context = MkContext {
688 uconstraints :: [UConstraint],
689 next_tvar :: Int,
690 definitions :: Ctxt (Def, Accessibility, Totality)
691 } deriving Show
693-- | The initial empty context
694initContext = MkContext [] 0 emptyContext
696-- | Get the definitions from a context
697ctxtAlist :: Context -> [(Name, Def)]
698ctxtAlist ctxt = map (\(n, (d, a, t)) -> (n, d)) $ toAlist (definitions ctxt)
700veval ctxt env t = evalState (eval False ctxt [] env t []) initEval
702addToCtxt :: Name -> Term -> Type -> Context -> Context
703addToCtxt n tm ty uctxt
704 = let ctxt = definitions uctxt
705 ctxt' = addDef n (Function ty tm, Public, Unchecked) ctxt in
706 uctxt { definitions = ctxt' }
708setAccess :: Name -> Accessibility -> Context -> Context
709setAccess n a uctxt
710 = let ctxt = definitions uctxt
711 ctxt' = updateDef n (\ (d, _, t) -> (d, a, t)) ctxt in
712 uctxt { definitions = ctxt' }
714setTotal :: Name -> Totality -> Context -> Context
715setTotal n t uctxt
716 = let ctxt = definitions uctxt
717 ctxt' = updateDef n (\ (d, a, _) -> (d, a, t)) ctxt in
718 uctxt { definitions = ctxt' }
720addCtxtDef :: Name -> Def -> Context -> Context
721addCtxtDef n d c = let ctxt = definitions c
722 ctxt' = addDef n (d, Public, Unchecked) ctxt in
723 c { definitions = ctxt' }
725addTyDecl :: Name -> NameType -> Type -> Context -> Context
726addTyDecl n nt ty uctxt
727 = let ctxt = definitions uctxt
728 ctxt' = addDef n (TyDecl nt ty, Public, Unchecked) ctxt in
729 uctxt { definitions = ctxt' }
731addDatatype :: Datatype Name -> Context -> Context
732addDatatype (Data n tag ty cons) uctxt
733 = let ctxt = definitions uctxt
734 ty' = normalise uctxt [] ty
735 ctxt' = addCons 0 cons (addDef n
736 (TyDecl (TCon tag (arity ty')) ty, Public, Unchecked) ctxt) in
737 uctxt { definitions = ctxt' }
738 where
739 addCons tag [] ctxt = ctxt
740 addCons tag ((n, ty) : cons) ctxt
741 = let ty' = normalise uctxt [] ty in
742 addCons (tag+1) cons (addDef n
743 (TyDecl (DCon tag (arity ty')) ty, Public, Unchecked) ctxt)
745-- FIXME: Too many arguments! Refactor all these Bools.
746addCasedef :: Name -> CaseInfo -> Bool -> Bool -> Bool -> Bool ->
747 [Either Term (Term, Term)] ->
748 [([Name], Term, Term)] -> -- totality
749 [([Name], Term, Term)] -> -- compile time
750 [([Name], Term, Term)] -> -- inlined
751 [([Name], Term, Term)] -> -- run time
752 Type -> Context -> Context
753addCasedef n ci@(CaseInfo alwaysInline tcdict)
754 tcase covering reflect asserted ps_in
755 ps_tot ps_inl ps_ct ps_rt ty uctxt
756 = let ctxt = definitions uctxt
757 access = case lookupDefAcc n False uctxt of
758 [(_, acc)] -> acc
759 _ -> Public
760 ctxt' = case (simpleCase tcase covering reflect CompileTime emptyFC ps_tot,
761 simpleCase tcase covering reflect CompileTime emptyFC ps_ct,
762 simpleCase tcase covering reflect CompileTime emptyFC ps_inl,
763 simpleCase tcase covering reflect RunTime emptyFC ps_rt) of
764 (OK (CaseDef args_tot sc_tot _),
765 OK (CaseDef args_ct sc_ct _),
766 OK (CaseDef args_inl sc_inl _),
767 OK (CaseDef args_rt sc_rt _)) ->
768 let inl = alwaysInline -- || tcdict
769 inlc = (inl || small n args_ct sc_ct) && (not asserted)
770 inlr = inl || small n args_rt sc_rt
771 cdef = CaseDefs (args_tot, sc_tot)
772 (args_ct, sc_ct)
773 (args_inl, sc_inl)
774 (args_rt, sc_rt) in
775 addDef n (CaseOp (ci { case_inlinable = inlc })
776 ty ps_in ps_tot cdef,
777 access, Unchecked) ctxt in
778 uctxt { definitions = ctxt' }
780-- simplify a definition for totality checking
781simplifyCasedef :: Name -> Context -> Context
782simplifyCasedef n uctxt
783 = let ctxt = definitions uctxt
784 ctxt' = case lookupCtxt n ctxt of
785 [(CaseOp ci ty [] ps _, acc, tot)] ->
786 ctxt -- nothing to simplify (or already done...)
787 [(CaseOp ci ty ps_in ps cd, acc, tot)] ->
788 let ps_in' = map simpl ps_in
789 pdef = map debind ps_in' in
790 case simpleCase False True False CompileTime emptyFC pdef of
791 OK (CaseDef args sc _) ->
792 addDef n (CaseOp ci
793 ty ps_in' ps (cd { cases_totcheck = (args, sc) }),
794 acc, tot) ctxt
795 Error err -> error (show err)
796 _ -> ctxt in
797 uctxt { definitions = ctxt' }
798 where
799 depat acc (Bind n (PVar t) sc)
800 = depat (n : acc) (instantiate (P Bound n t) sc)
801 depat acc x = (acc, x)
802 debind (Right (x, y)) = let (vs, x') = depat [] x
803 (_, y') = depat [] y in
804 (vs, x', y')
805 debind (Left x) = let (vs, x') = depat [] x in
806 (vs, x', Impossible)
807 simpl (Right (x, y)) = Right (x, simplify uctxt [] y)
808 simpl t = t
810addOperator :: Name -> Type -> Int -> ([Value] -> Maybe Value) ->
811 Context -> Context
812addOperator n ty a op uctxt
813 = let ctxt = definitions uctxt
814 ctxt' = addDef n (Operator ty a op, Public, Unchecked) ctxt in
815 uctxt { definitions = ctxt' }
817tfst (a, _, _) = a
819lookupNames :: Name -> Context -> [Name]
820lookupNames n ctxt
821 = let ns = lookupCtxtName n (definitions ctxt) in
822 map fst ns
824lookupTy :: Name -> Context -> [Type]
825lookupTy n ctxt
826 = do def <- lookupCtxt n (definitions ctxt)
827 case tfst def of
828 (Function ty _) -> return ty
829 (TyDecl _ ty) -> return ty
830 (Operator ty _ _) -> return ty
831 (CaseOp _ ty _ _ _) -> return ty
833isConName :: Name -> Context -> Bool
834isConName n ctxt = isTConName n ctxt || isDConName n ctxt
836isTConName :: Name -> Context -> Bool
837isTConName n ctxt
838 = or $ do def <- lookupCtxt n (definitions ctxt)
839 case tfst def of
840 (TyDecl (TCon _ _) _) -> return True
841 _ -> return False
843isDConName :: Name -> Context -> Bool
844isDConName n ctxt
845 = or $ do def <- lookupCtxt n (definitions ctxt)
846 case tfst def of
847 (TyDecl (DCon _ _) _) -> return True
848 _ -> return False
850isFnName :: Name -> Context -> Bool
851isFnName n ctxt
852 = or $ do def <- lookupCtxt n (definitions ctxt)
853 case tfst def of
854 (Function _ _) -> return True
855 (Operator _ _ _) -> return True
856 (CaseOp _ _ _ _ _) -> return True
857 _ -> return False
859lookupP :: Name -> Context -> [Term]
860lookupP n ctxt
861 = do def <- lookupCtxt n (definitions ctxt)
862 p <- case def of
863 (Function ty tm, a, _) -> return (P Ref n ty, a)
864 (TyDecl nt ty, a, _) -> return (P nt n ty, a)
865 (CaseOp _ ty _ _ _, a, _) -> return (P Ref n ty, a)
866 (Operator ty _ _, a, _) -> return (P Ref n ty, a)
867 case snd p of
868 Hidden -> []
869 _ -> return (fst p)
871lookupDef :: Name -> Context -> [Def]
872lookupDef n ctxt = map tfst $ lookupCtxt n (definitions ctxt)
874lookupDefAcc :: Name -> Bool -> Context ->
875 [(Def, Accessibility)]
876lookupDefAcc n mkpublic ctxt
877 = map mkp $ lookupCtxt n (definitions ctxt)
878 -- io_bind a special case for REPL prettiness
879 where mkp (d, a, _) = if mkpublic && (not (n == UN "io_bind" || n == UN "io_return"))
880 then (d, Public) else (d, a)
882lookupTotal :: Name -> Context -> [Totality]
883lookupTotal n ctxt = map mkt $ lookupCtxt n (definitions ctxt)
884 where mkt (d, a, t) = t
886lookupVal :: Name -> Context -> [Value]
887lookupVal n ctxt
888 = do def <- lookupCtxt n (definitions ctxt)
889 case tfst def of
890 (Function _ htm) -> return (veval ctxt [] htm)
891 (TyDecl nt ty) -> return (VP nt n (veval ctxt [] ty))
893lookupTyEnv :: Name -> Env -> Maybe (Int, Type)
894lookupTyEnv n env = li n 0 env where
895 li n i [] = Nothing
896 li n i ((x, b): xs)
897 | n == x = Just (i, binderTy b)
898 | otherwise = li n (i+1) xs