0 | module TTImp.ProcessDef
2 | import Core.Case.CaseBuilder
3 | import Core.Case.CaseTree
4 | import Core.Case.CaseTree.Pretty
8 | import Core.LinearCheck
10 | import Core.Termination
11 | import Core.Termination.CallGraph
12 | import Core.Transform
14 | import Core.UnifyState
16 | import Idris.REPL.Opts
18 | import Idris.Pretty.Annotations
20 | import TTImp.BindImplicits
22 | import TTImp.Elab.Binders
23 | import TTImp.Elab.Check
24 | import TTImp.Elab.Utils
25 | import TTImp.Impossible
26 | import TTImp.PartialEval
28 | import TTImp.TTImp.Functor
29 | import TTImp.ProcessDef.Dot
30 | import TTImp.ProcessType
32 | import TTImp.WithClause
38 | import Libraries.Data.NameMap
39 | import Libraries.Data.WithDefault
40 | import Libraries.Text.PrettyPrint.Prettyprinter
41 | import Libraries.Data.List.SizeOf
49 | impossibleOK : {auto c : Ref Ctxt Defs} ->
51 | Defs -> NF vars -> NF vars -> Bool
52 | impossibleOK defs (NTCon _ xn _ _) (NTCon _ yn _ _) = xn /= yn
53 | impossibleOK defs (NDCon _ _ xt _ _) (NDCon _ _ yt _ _) = xt /= yt
54 | impossibleOK defs (NPrimVal _ x) (NPrimVal _ y) = x /= y
57 | impossibleOK defs (NPrimVal {}) (NDCon {}) = True
58 | impossibleOK defs (NDCon {}) (NPrimVal {}) = True
59 | impossibleOK defs (NPrimVal {}) (NBind {}) = True
60 | impossibleOK defs (NBind {}) (NPrimVal {}) = True
61 | impossibleOK defs (NPrimVal {}) (NTCon {}) = True
62 | impossibleOK defs (NTCon {}) (NPrimVal {}) = True
63 | impossibleOK defs (NPrimVal {}) (NType {}) = True
64 | impossibleOK defs (NType {}) (NPrimVal {}) = True
67 | impossibleOK defs (NTCon {}) (NBind {}) = True
68 | impossibleOK defs (NBind {}) (NTCon {}) = True
69 | impossibleOK defs (NTCon {}) (NType {}) = True
70 | impossibleOK defs (NType {}) (NTCon {}) = True
73 | impossibleOK defs (NBind {}) (NType {}) = True
74 | impossibleOK defs (NType {}) (NBind {}) = True
76 | impossibleOK defs x y = False
79 | impossibleErrOK : {auto c : Ref Ctxt Defs} ->
80 | Defs -> Error -> Core Bool
81 | impossibleErrOK defs (CantConvert fc gam env l r)
82 | = do let defs = { gamma := gam } defs
83 | impossibleOK defs <$> nf defs env l <*> nf defs env r
84 | impossibleErrOK defs (CantSolveEq fc gam env l r)
85 | = do let defs = { gamma := gam } defs
86 | impossibleOK defs <$> nf defs env l <*> nf defs env r
87 | impossibleErrOK defs (CyclicMeta {}) = pure True
88 | impossibleErrOK defs (AllFailed errs)
89 | = allM (impossibleErrOK defs) (map snd errs)
90 | impossibleErrOK defs (WhenUnifying _ _ _ _ _ err)
91 | = impossibleErrOK defs err
92 | impossibleErrOK defs ImpossibleCase = pure True
93 | impossibleErrOK defs _ = pure False
101 | extendEnv : {vars : _} ->
102 | Env Term vars -> Thin inner vars ->
103 | NestedNames vars ->
104 | Term vars -> Term vars ->
107 | Env Term vars', NestedNames vars',
108 | Term vars', Term vars'))
109 | extendEnv env p nest (Bind _ n (PVar fc c pi tmty) sc) (Bind _ n' (PVTy {}) tysc) with (nameEq n n')
110 | extendEnv env p nest (Bind _ n (PVar fc c pi tmty) sc) (Bind _ n' (PVTy {}) tysc) | Nothing
111 | = throw (InternalError "Can't happen: names don't match in pattern type")
112 | extendEnv env p nest (Bind _ n (PVar fc c pi tmty) sc) (Bind _ n (PVTy {}) tysc) | (Just Refl)
113 | = extendEnv (PVar fc c pi tmty :: env) (Drop p) (weaken (dropName n nest)) sc tysc
114 | extendEnv env p nest (Bind _ n (PLet fc c tmval tmty) sc) (Bind _ n' (PLet {}) tysc) with (nameEq n n')
115 | extendEnv env p nest (Bind _ n (PLet fc c tmval tmty) sc) (Bind _ n' (PLet {}) tysc) | Nothing
116 | = throw (InternalError "Can't happen: names don't match in pattern type")
118 | extendEnv env p nest (Bind _ n (PLet fc c tmval tmty) sc) (Bind _ n (PLet {}) tysc) | (Just Refl)
119 | = extendEnv (Let fc c tmval tmty :: env) (Drop p) (weaken (dropName n nest)) sc tysc
120 | extendEnv env p nest tm ty
121 | = pure (
_ ** (p, env, nest, tm, ty))
129 | findLinear : {vars : _} ->
130 | {auto c : Ref Ctxt Defs} ->
131 | Bool -> Nat -> RigCount -> Term vars ->
132 | Core (List (Name, RigCount))
133 | findLinear top bound rig (Bind fc n b sc)
134 | = findLinear top (S bound) rig sc
135 | findLinear top bound rig (As fc _ _ p)
136 | = findLinear top bound rig p
137 | findLinear top bound rig tm
138 | = case getFnArgs tm of
139 | (Ref _ _ n, []) => pure []
141 | => do defs <- get Ctxt
142 | Just nty <- lookupTyExact n (gamma defs)
143 | | Nothing => pure []
144 | findLinArg (accessible nt rig) !(nf defs Env.empty nty) args
147 | accessible : NameType -> RigCount -> RigCount
148 | accessible Func r = if top then r else erased
151 | findLinArg : {vars : _} ->
152 | RigCount -> ClosedNF -> List (Term vars) ->
153 | Core (List (Name, RigCount))
154 | findLinArg rig ty@(NBind _ _ (Pi _ c _ _) _) (As fc u a p :: as)
157 | UseLeft => findLinArg rig ty (p :: as)
158 | UseRight => findLinArg rig ty (a :: as)
159 | else pure $
!(findLinArg rig ty [a]) ++ !(findLinArg rig ty (p :: as))
160 | findLinArg rig (NBind _ x (Pi _ c _ _) sc) (Local {name=a} fc _ idx prf :: as)
161 | = do defs <- get Ctxt
164 | then do sc' <- sc defs (toClosure defaultOpts Env.empty (Ref fc Bound x))
165 | pure $
(a, rigMult c rig) ::
166 | !(findLinArg rig sc' as)
167 | else do sc' <- sc defs (toClosure defaultOpts Env.empty (Ref fc Bound x))
168 | findLinArg rig sc' as
169 | findLinArg rig (NBind fc x (Pi _ c _ _) sc) (a :: as)
170 | = do defs <- get Ctxt
171 | pure $
!(findLinear False bound (c |*| rig) a) ++
172 | !(findLinArg rig !(sc defs (toClosure defaultOpts Env.empty (Ref fc Bound x))) as)
173 | findLinArg rig ty (a :: as)
174 | = pure $
!(findLinear False bound rig a) ++ !(findLinArg rig ty as)
175 | findLinArg _ _ [] = pure []
177 | setLinear : List (Name, RigCount) -> Term vars -> Term vars
178 | setLinear vs tm@(Bind fc x b sc)
179 | = if isPatternBinder b
180 | then let b' = maybe b (setMultiplicity b) (lookup x vs)
181 | in Bind fc x b' (setLinear vs sc)
184 | isPatternBinder : Binder a -> Bool
185 | isPatternBinder (PVar {}) = True
186 | isPatternBinder (PVTy {}) = True
187 | isPatternBinder (PLet {}) = True
188 | isPatternBinder _ = False
189 | setLinear vs tm = tm
195 | combineLinear : FC -> List (Name, RigCount) ->
196 | Core (List (Name, RigCount))
197 | combineLinear loc [] = pure []
198 | combineLinear loc ((n, count) :: cs)
199 | = case lookupAll n cs of
200 | [] => pure $
(n, count) :: !(combineLinear loc cs)
201 | counts => do count' <- combineAll count counts
202 | pure $
(n, count') ::
203 | !(combineLinear loc (filter notN cs))
205 | notN : (Name, RigCount) -> Bool
206 | notN (n', _) = n /= n'
208 | lookupAll : Name -> List (Name, RigCount) -> List RigCount
209 | lookupAll n [] = []
210 | lookupAll n ((n', c) :: cs)
211 | = if n == n' then c :: lookupAll n cs else lookupAll n cs
214 | combine : RigCount -> RigCount -> Core RigCount
215 | combine l r = if l |+| r == top && not (isErased $
l `glb` r) && (l `glb` r) /= top
216 | then throw (LinearUsed loc 2 n)
219 | else pure (l `lub` r)
221 | combineAll : RigCount -> List RigCount -> Core RigCount
222 | combineAll c [] = pure c
223 | combineAll c (c' :: cs)
224 | = do newc <- combine c c'
228 | checkLHS : {vars : _} ->
229 | {auto c : Ref Ctxt Defs} ->
230 | {auto m : Ref MD Metadata} ->
231 | {auto u : Ref UST UState} ->
232 | {auto s : Ref Syn SyntaxInfo} ->
233 | {auto o : Ref ROpts REPLOpts} ->
235 | (mult : RigCount) ->
236 | Int -> List ElabOpt -> NestedNames vars -> Env Term vars ->
239 | (
vars' ** (Thin vars vars',
240 | Env Term vars', NestedNames vars',
241 | Term vars', Term vars'))
)
242 | checkLHS {vars} trans mult n opts nest env fc lhs_in
243 | = do defs <- get Ctxt
244 | logRaw "declare.def.lhs" 30 "Raw LHS: " lhs_in
245 | lhs_raw <- if trans
247 | else lhsInCurrentNS nest lhs_in
248 | logRaw "declare.def.lhs" 30 "Raw LHS in current NS: " lhs_raw
250 | autoimp <- isUnboundImplicits
251 | setUnboundImplicits True
252 | (_, lhs_bound) <- bindNames False lhs_raw
253 | setUnboundImplicits autoimp
254 | logRaw "declare.def.lhs" 30 "Raw LHS with implicits bound" lhs_bound
257 | then pure lhs_bound
258 | else implicitsAs n defs vars lhs_bound
260 | fullname <- getFullName (Resolved n)
261 | log "declare.def.lhs" 5 $
"Checking LHS of " ++ show fullname
264 | log "declare.def.lhs" 10 $
show lhs
265 | logEnv "declare.def.lhs" 5 "In env" env
266 | let lhsMode = if trans
270 | wrapErrorC opts (InLHS fc fullname) $
271 | elabTerm n lhsMode opts nest env
272 | (IBindHere fc PATTERN lhs) Nothing
273 | logTerm "declare.def.lhs" 5 "Checked LHS term" lhstm
274 | lhsty <- getTerm lhstyg
277 | let lhsenv = letToLam env
282 | lhstm <- normaliseHoles defs lhsenv lhstm
283 | lhsty <- normaliseHoles defs env lhsty
284 | linvars_in <- findLinear True 0 linear lhstm
285 | logTerm "declare.def.lhs" 10 "Checked LHS term after normalise" lhstm
287 | log "declare.def.lhs" 5 $
"Linearity of names in " ++ show n ++ ": " ++
290 | linvars <- combineLinear fc linvars_in
291 | let lhstm_lin = setLinear linvars lhstm
292 | let lhsty_lin = setLinear linvars lhsty
294 | logTerm "declare.def.lhs" 3 "LHS term" lhstm_lin
295 | logTerm "declare.def.lhs" 5 "LHS type" lhsty_lin
296 | setHoleLHS (bindEnv fc env lhstm_lin)
298 | (
vars' ** (sub', env', nest', lhstm', lhsty'))
<-
299 | extendEnv env Refl nest lhstm_lin lhsty_lin
300 | logTerm "declare.def.lhs" 3 "LHS term after extension" lhstm'
302 | lhstm' <- if trans || not (isErased mult)
304 | else do res <- wrapErrorC opts (InLHS fc fullname) $
305 | dotInferred defs (thinNestedNames nest sub') env' True lhs lhstm'
306 | logTerm "declare.def.lhs" 3 "LHS term after dotting" res
309 | pure (lhs, (
vars' ** (sub', env', nest', lhstm', lhsty'))
)
316 | hasEmptyPat : {vars : _} ->
317 | {auto c : Ref Ctxt Defs} ->
318 | Defs -> Env Term vars -> Term vars -> Core Bool
319 | hasEmptyPat defs env (Bind fc x b sc)
320 | = pure $
!(isEmpty defs env !(nf defs env (binderType b)))
321 | || !(hasEmptyPat defs (b :: env) sc)
322 | hasEmptyPat defs env _ = pure False
325 | applyEnv : {vars : _} ->
326 | {auto c : Ref Ctxt Defs} ->
327 | Env Term vars -> Name ->
328 | Core (Name, (Maybe Name, List (Var vars), FC -> NameType -> Term vars))
329 | applyEnv env withname
330 | = do n' <- resolveName withname
331 | pure (withname, (Just withname, reverse (allVarsNoLet env),
332 | \fc, nt => applyTo fc
333 | (Ref fc nt (Resolved n')) env))
338 | checkClause : {vars : _} ->
339 | {auto c : Ref Ctxt Defs} ->
340 | {auto m : Ref MD Metadata} ->
341 | {auto u : Ref UST UState} ->
342 | {auto s : Ref Syn SyntaxInfo} ->
343 | {auto o : Ref ROpts REPLOpts} ->
344 | (mult : RigCount) -> (vis : Visibility) ->
345 | (totreq : TotalReq) -> (hashit : Bool) ->
346 | Int -> List ElabOpt -> NestedNames vars -> Env Term vars ->
347 | ImpClause -> Core (Either RawImp Clause)
348 | checkClause mult vis totreq hashit n opts nest env (ImpossibleClause fc lhs)
349 | = do lhs_raw <- lhsInCurrentNS nest lhs
351 | (do autoimp <- isUnboundImplicits
352 | setUnboundImplicits True
353 | (_, lhs) <- bindNames False lhs_raw
354 | setUnboundImplicits autoimp
357 | let lhs = INamedApp fc lhs (UN Underscore) (Implicit fc True)
359 | log "declare.def.clause.impossible" 5 $
"Checking " ++ show lhs
360 | logEnv "declare.def.clause.impossible" 5 "In env" env
362 | elabTerm n (InLHS mult) opts nest env
363 | (IBindHere fc COVERAGE lhs) Nothing
365 | lhs <- normaliseHoles defs env lhstm
366 | if !(hasEmptyPat defs env lhs)
367 | then pure (Left lhs_raw)
368 | else throw (ValidCase fc env (Left lhs)))
371 | ValidCase {} => throw err
372 | _ => do defs <- get Ctxt
373 | if !(impossibleErrOK defs err)
374 | then pure (Left lhs_raw)
375 | else throw (ValidCase fc env (Right err)))
376 | checkClause {vars} mult vis totreq hashit n opts nest env (PatClause fc lhs_in rhs)
377 | = do (_, (
vars' ** (sub', env', nest', lhstm', lhsty'))
) <-
378 | checkLHS False mult n opts nest env fc lhs_in
379 | let rhsMode = if isErased mult then InType else InExpr
380 | log "declare.def.clause" 5 $
"Checking RHS " ++ show rhs
381 | logEnv "declare.def.clause" 5 "In env" env'
383 | rhstm <- logTime 3 ("Check RHS " ++ show fc) $
384 | wrapErrorC opts (InRHS fc !(getFullName (Resolved n))) $
385 | checkTermSub n rhsMode opts nest' env' env sub' rhs (gnf env' lhsty')
388 | logTerm "declare.def.clause" 3 "RHS term" rhstm
390 | do addHashWithNames lhstm'
391 | addHashWithNames rhstm
392 | log "module.hash" 15 "Adding hash for def."
398 | addLHS (getFC lhs_in) (length env) env' lhstm'
401 | pure (Right (MkClause env' lhstm' rhstm))
403 | checkClause {vars} mult vis totreq hashit n opts nest env
404 | (WithClause ifc lhs_in rig wval_raw mprf flags cs)
405 | = do (lhs, (
vars' ** (sub', env', nest', lhspat, reqty))
) <-
406 | checkLHS False mult n opts nest env ifc lhs_in
408 | = if isErased mult || isErased rig then InType else InExpr
410 | (wval, gwvalTy) <- wrapErrorC opts (InRHS ifc !(getFullName (Resolved n))) $
411 | elabTermSub n wmode opts nest' env' env sub' wval_raw Nothing
414 | logTerm "declare.def.clause.with" 5 "With value (at quantity \{show rig})" wval
415 | logTerm "declare.def.clause.with" 3 "Required type" reqty
416 | wvalTy <- getTerm gwvalTy
418 | wval <- normaliseHoles defs env' wval
419 | wvalTy <- normaliseHoles defs env' wvalTy
421 | let (
wevars ** withSub)
= keepOldEnv sub' (snd (findSubEnv env' wval))
422 | logTerm "declare.def.clause.with" 5 "With value type" wvalTy
423 | log "declare.def.clause.with" 5 $
"Using vars " ++ show wevars
425 | let Just wval = shrink wval withSub
426 | | Nothing => throw (InternalError "Impossible happened: With abstraction failure #1")
427 | let Just wvalTy = shrink wvalTy withSub
428 | | Nothing => throw (InternalError "Impossible happened: With abstraction failure #2")
431 | let Just wvalEnv = shrinkEnv env' withSub
432 | | Nothing => throw (InternalError "Impossible happened: With abstraction failure #3")
436 | (
wargs ** (scenv, var, binder))
<- bindWithArgs rig wvalTy ((,wval) <$> mprf) wvalEnv
438 | let bnr = bindNotReq vfc 0 env' withSub [] reqty
439 | let notreqns = fst bnr
440 | let notreqty = snd bnr
442 | rdefs <- if Syntactic `elem` flags
443 | then clearDefs defs
445 | wtyScope <- replace rdefs scenv !(nf rdefs scenv (weakenNs (mkSizeOf wargs) wval))
448 | (weakenNs (mkSizeOf wargs) notreqty))
449 | let bNotReq = binder wtyScope
456 | let env' = mkExplicit env'
458 | let Just (reqns, envns, wtype) = bindReq vfc env' withSub [] bNotReq
459 | | Nothing => throw (InternalError "Impossible happened: With abstraction failure #4")
465 | = map Just reqns ++
466 | Nothing :: map Just notreqns
468 | logTerm "declare.def.clause.with" 3 "With function type" wtype
469 | log "declare.def.clause.with" 5 $
"Argument names " ++ show wargNames
471 | wname <- genWithName !(prettyName !(toFullNames (Resolved n)))
472 | widx <- addDef wname ({flags $= (SetTotal totreq ::)}
473 | (newDef vfc wname (if isErased mult then erased else top)
474 | vars wtype (specified vis) None))
476 | let toWarg : Maybe (PiInfo RawImp, Name) -> List (Maybe Name, RawImp)
477 | := flip maybe (\pn => [(Nothing, IVar vfc (snd pn))]) $
478 | (Nothing, wval_raw) ::
482 | let fc = emptyFC in
483 | let refl = IVar fc (NS builtinNS (UN $
Basic "Refl")) in
484 | [(map snd mprf, INamedApp fc refl (UN $
Basic "x") wval_raw)]
486 | let rhs_in = gapply (IVar vfc wname)
487 | $
map (\ nm => (Nothing, IVar vfc nm)) envns
488 | ++ concatMap toWarg wargNames
490 | log "declare.def.clause.with" 3 $
"Applying to with argument " ++ show rhs_in
491 | rhs <- wrapErrorC opts (InRHS ifc !(getFullName (Resolved n))) $
492 | checkTermSub n wmode opts nest' env' env sub' rhs_in
496 | cs' <- traverse (mkClauseWith 1 wname wargNames lhs) cs
497 | log "declare.def.clause.with" 3 $
"With clauses: " ++ show cs'
500 | nestname <- applyEnv env wname
501 | let nest'' = { names $= (nestname ::) } nest
503 | let wdef = IDef ifc wname cs'
504 | processDecl [] nest'' env wdef
506 | pure (Right (MkClause env' lhspat rhs))
509 | vfc = virtualiseFC ifc
512 | (rig : RigCount) -> (wvalTy : Term xs) -> Maybe ((RigCount, Name), Term xs) ->
513 | (wvalEnv : Env Term xs) ->
515 | ** ( Env Term (ext ++ xs)
517 | , (Term (ext ++ xs) -> Term xs)
519 | bindWithArgs {xs} rig wvalTy Nothing wvalEnv =
521 | wargn = MN "warg" 0
525 | scenv : Env Term (wargs ++ xs)
526 | := Pi vfc top Explicit wvalTy :: wvalEnv
528 | var : Term (wargs ++ xs)
529 | := Local vfc (Just False) Z First
531 | binder : Term (wargs ++ xs) -> Term xs
532 | := Bind vfc wargn (Pi vfc rig Explicit wvalTy)
534 | in pure (
wargs ** (scenv, var, binder))
536 | bindWithArgs {xs} rig wvalTy (Just ((rigPrf, name), wval)) wvalEnv = do
539 | let eqName = NS builtinNS (UN $
Basic "Equal")
540 | Just (TCon ar _ _ _ _ _ _) <- lookupDefExact eqName (gamma defs)
541 | | _ => throw (InternalError "Cannot find builtin Equal")
542 | let eqTyCon = Ref vfc (TyCon ar) !(toResolvedNames eqName)
545 | wargn = MN "warg" 0
547 | wargs = [name, wargn]
549 | wvalTy' := weaken wvalTy
550 | eqTy : Term (MN "warg" 0 :: xs)
551 | := apply vfc eqTyCon
555 | , Local vfc (Just False) Z First
558 | scenv : Env Term (wargs ++ xs)
559 | := Pi vfc top Implicit eqTy
560 | :: Pi vfc top Explicit wvalTy
563 | var : Term (wargs ++ xs)
564 | := Local vfc (Just False) (S Z) (Later First)
566 | binder : Term (wargs ++ xs) -> Term xs
567 | := \ t => Bind vfc wargn (Pi vfc rig Explicit wvalTy)
568 | $
Bind vfc name (Pi vfc rigPrf Implicit eqTy) t
570 | pure (
wargs ** (scenv, var, binder))
575 | keepOldEnv : {0 outer : _} -> {vs : _} ->
576 | (outprf : Thin outer vs) -> Thin vs' vs ->
577 | (vs'' : Scope ** Thin vs'' vs)
578 | keepOldEnv {vs} Refl p = (
vs ** Refl)
579 | keepOldEnv {vs} p Refl = (
vs ** Refl)
580 | keepOldEnv (Drop p) (Drop p')
581 | = let (
_ ** rest)
= keepOldEnv p p' in
583 | keepOldEnv (Drop p) (Keep p')
584 | = let (
_ ** rest)
= keepOldEnv p p' in
586 | keepOldEnv (Keep p) (Drop p')
587 | = let (
_ ** rest)
= keepOldEnv p p' in
589 | keepOldEnv (Keep p) (Keep p')
590 | = let (
_ ** rest)
= keepOldEnv p p' in
596 | mkClauseWith : (drop : Nat) -> Name ->
597 | List (Maybe (PiInfo RawImp, Name)) ->
598 | RawImp -> ImpClause ->
600 | mkClauseWith drop wname wargnames lhs (PatClause ploc patlhs rhs)
601 | = do log "declare.def.clause.with" 20 "PatClause"
602 | newlhs <- getNewLHS ploc drop nest wname wargnames lhs patlhs
603 | newrhs <- withRHS ploc drop wname wargnames rhs lhs
604 | pure (PatClause ploc newlhs newrhs)
605 | mkClauseWith drop wname wargnames lhs (WithClause ploc patlhs rig wval prf flags ws)
606 | = do log "declare.def.clause.with" 20 "WithClause"
607 | newlhs <- getNewLHS ploc drop nest wname wargnames lhs patlhs
608 | newwval <- withRHS ploc drop wname wargnames wval lhs
609 | ws' <- traverse (mkClauseWith (S drop) wname wargnames lhs) ws
610 | pure (WithClause ploc newlhs rig newwval prf flags ws')
611 | mkClauseWith drop wname wargnames lhs (ImpossibleClause ploc patlhs)
612 | = do log "declare.def.clause.with" 20 "ImpossibleClause"
613 | newlhs <- getNewLHS ploc drop nest wname wargnames lhs patlhs
614 | pure (ImpossibleClause ploc newlhs)
618 | calcRefs : {auto c : Ref Ctxt Defs} ->
619 | (runtime : Bool) -> (aTotal : Name) -> (fn : Name) -> Core ()
621 | = do defs <- get Ctxt
622 | Just gdef <- lookupCtxtExact fn (gamma defs)
624 | let PMDef r cargs tree_ct tree_rt pats = definition gdef
626 | let refs : Maybe (NameMap Bool)
627 | = if rt then refersToRuntimeM gdef else refersToM gdef
629 | | Just _ => pure ()
630 | let tree : CaseTree cargs = if rt then tree_rt else tree_ct
631 | let metas = CaseTree.getMetas tree
632 | traverse_ addToSave (keys metas)
633 | let refs_all = addRefs at metas tree
634 | refs <- ifThenElse rt
635 | (dropErased (keys refs_all) refs_all)
637 | ignore $
ifThenElse rt
638 | (addDef fn ({ refersToRuntimeM := Just refs } gdef))
639 | (addDef fn ({ refersToM := Just refs } gdef))
640 | traverse_ (calcRefs rt at) (keys refs)
642 | dropErased : List Name -> NameMap Bool -> Core (NameMap Bool)
643 | dropErased [] refs = pure refs
644 | dropErased (n :: ns) refs
645 | = do defs <- get Ctxt
646 | Just gdef <- lookupCtxtExact n (gamma defs)
647 | | Nothing => dropErased ns refs
648 | if multiplicity gdef /= erased
649 | then dropErased ns refs
650 | else dropErased ns (delete n refs)
653 | mkRunTime : {auto c : Ref Ctxt Defs} ->
654 | {auto m : Ref MD Metadata} ->
655 | {auto u : Ref UST UState} ->
656 | {auto s : Ref Syn SyntaxInfo} ->
657 | {auto o : Ref ROpts REPLOpts} ->
658 | FC -> Name -> Core ()
660 | = do logC "compile.casetree" 5 $
do pure $
"Making run time definition for " ++ show !(toFullNames n)
662 | Just gdef <- lookupCtxtExact n (gamma defs)
664 | let cov = gdef.totality.isCovering
666 | when (not (isErased $
multiplicity gdef)) $
do
667 | let PMDef r cargs tree_ct _ pats = definition gdef
672 | pats' <- traverse (toErased (location gdef) (getSpec (flags gdef)))
675 | let clauses_init = map (toClause (location gdef)) pats'
676 | clauses <- case cov of
677 | MissingCases _ => do log "compile.casetree.missing" 5 $
"Adding uncovered error to \{show clauses_init}"
678 | pure $
addErrorCase clauses_init
679 | _ => pure clauses_init
681 | (
rargs ** (tree_rt, _))
<- getPMDef (location gdef) RunTime n ty clauses
682 | logC "compile.casetree" 5 $
do
683 | tree_rt <- toFullNames tree_rt
686 | , "Runtime tree for " ++ show (fullname gdef) ++ ":"
687 | , show (indent 2 $
prettyTree tree_rt)
689 | log "compile.casetree" 10 $
show tree_rt
690 | log "compile.casetree.measure" 15 $
show (measure tree_rt)
692 | let Just Refl = scopeEq cargs rargs
693 | | Nothing => throw (InternalError "WAT")
694 | ignore $
addDef n $
695 | { definition := PMDef r rargs tree_ct tree_rt pats
699 | when (caseName !(toFullNames n) && noInline (flags gdef)) $
700 | do inl <- canInlineCaseBlock n
702 | logC "compiler.inline.eval" 5 $
do pure "Marking \{show !(toFullNames n)} for inlining in runtime case tree."
703 | setFlag fc n Inline
706 | noInline : List DefFlag -> Bool
707 | noInline (Inline :: _) = False
708 | noInline (NoInline :: _) = False
709 | noInline (x :: xs) = noInline xs
712 | caseName : Name -> Bool
713 | caseName (CaseBlock {}) = True
714 | caseName (NS _ n) = caseName n
717 | mkCrash : {vars : _} -> String -> Term vars
719 | = apply fc (Ref fc Func (UN $
Basic "prim__crash"))
720 | [Erased fc Placeholder, PrimVal fc (Str msg)]
722 | matchAny : Term vars -> Term vars
723 | matchAny (App fc f a) = App fc (matchAny f) (Erased fc Placeholder)
726 | makeErrorClause : {vars : _} -> Env Term vars -> Term vars -> Clause
727 | makeErrorClause env lhs
728 | = MkClause env (matchAny lhs)
729 | (mkCrash ("Unhandled input for " ++ show n ++ " at " ++ show fc))
731 | addErrorCase : List Clause -> List Clause
732 | addErrorCase [] = []
733 | addErrorCase [MkClause env lhs rhs]
734 | = MkClause env lhs rhs :: makeErrorClause env lhs :: []
735 | addErrorCase (x :: xs) = x :: addErrorCase xs
737 | getSpec : List DefFlag -> Maybe (List (Name, Nat))
738 | getSpec [] = Nothing
739 | getSpec (PartialEval n :: _) = Just n
740 | getSpec (x :: xs) = getSpec xs
742 | toErased : FC -> Maybe (List (Name, Nat)) ->
743 | (
vars ** (Env Term vars, Term vars, Term vars))
->
744 | Core (
vars ** (Env Term vars, Term vars, Term vars))
745 | toErased fc spec (
_ ** (env, lhs, rhs))
746 | = do lhs_erased <- linearCheck fc linear True env lhs
748 | rhs' <- applyTransforms env rhs
749 | rhs' <- applySpecialise env spec rhs'
750 | rhs_erased <- linearCheck fc linear True env rhs'
751 | pure (
_ ** (env, lhs_erased, rhs_erased))
753 | toClause : FC -> (
vars ** (Env Term vars, Term vars, Term vars))
-> Clause
754 | toClause fc (
_ ** (env, lhs, rhs))
755 | = MkClause env lhs rhs
757 | compileRunTime : {auto c : Ref Ctxt Defs} ->
758 | {auto m : Ref MD Metadata} ->
759 | {auto u : Ref UST UState} ->
760 | {auto s : Ref Syn SyntaxInfo} ->
761 | {auto o : Ref ROpts REPLOpts} ->
762 | FC -> Name -> Core ()
763 | compileRunTime fc atotal
764 | = do defs <- get Ctxt
765 | traverse_ (mkRunTime fc) (toCompileCase defs)
766 | traverse_ (calcRefs True atotal) (toCompileCase defs)
768 | update Ctxt { toCompileCase := [] }
770 | toPats : Clause -> (
vs ** (Env Term vs, Term vs, Term vs))
771 | toPats (MkClause {vars} env lhs rhs)
772 | = (
_ ** (env, lhs, rhs))
774 | warnUnreachable : {auto c : Ref Ctxt Defs} ->
776 | warnUnreachable (MkClause env lhs rhs)
777 | = recordWarning (UnreachableClause (getLoc lhs) env lhs)
779 | isAlias : RawImp -> Maybe ((FC, Name)
780 | , List (FC, (FC, Name)))
782 | = do let (hd, apps) = getFnArgs lhs []
784 | args <- traverse (isExplicit >=> bitraverse pure isIBindVar) apps
787 | lookupOrAddAlias : {vars : _} ->
788 | {auto m : Ref MD Metadata} ->
789 | {auto c : Ref Ctxt Defs} ->
790 | {auto u : Ref UST UState} ->
791 | {auto s : Ref Syn SyntaxInfo} ->
792 | {auto o : Ref ROpts REPLOpts} ->
793 | List ElabOpt -> NestedNames vars -> Env Term vars -> FC ->
794 | Name -> List ImpClause -> Core (Maybe GlobalDef)
795 | lookupOrAddAlias eopts nest env fc n [cl@(PatClause _ lhs _)]
796 | = do defs <- get Ctxt
797 | log "declare.def.alias" 20 $
"Looking at \{show cl}"
798 | Nothing <- lookupCtxtExact n (gamma defs)
799 | | Just gdef => pure (Just gdef)
802 | let Just (hd, args) = isAlias lhs
803 | | Nothing => pure Nothing
805 | log "declare.def" 5 $
806 | "Missing type declaration for the alias "
808 | ++ ". Checking first whether it is a misspelling."
810 | Just (str, kept) <- getSimilarNames n
811 | | Nothing => pure []
813 | decls <- for kept $
\ (cand, vis, weight) => do
814 | Just gdef <- lookupCtxtExact cand (gamma defs)
815 | | Nothing => pure Nothing
816 | let None = definition gdef
817 | | _ => pure Nothing
818 | pure (Just (cand, vis, weight))
819 | pure $
showSimilarNames (currentNS defs) n str $
catMaybes decls
820 | | (x :: xs) => throw (MaybeMisspelling (NoDeclaration fc n) (x ::: xs))
822 | log "declare.def" 5 "Not a misspelling: go ahead and declare it!"
823 | processType eopts nest env fc top Public []
825 | $
Mk [fc, MkFCVal fc n] $
holeyType (map snd args)
827 | lookupCtxtExact n (gamma defs)
830 | holeyType : List (FC, Name) -> RawImp
831 | holeyType [] = Implicit fc False
832 | holeyType ((xfc, x) :: xs)
833 | = let xfc = virtualiseFC xfc in
834 | IPi xfc top Explicit (Just x) (Implicit xfc False)
837 | lookupOrAddAlias _ _ _ fc n _
838 | = do defs <- get Ctxt
839 | lookupCtxtExact n (gamma defs)
842 | processDef : {vars : _} ->
843 | {auto c : Ref Ctxt Defs} ->
844 | {auto m : Ref MD Metadata} ->
845 | {auto u : Ref UST UState} ->
846 | {auto s : Ref Syn SyntaxInfo} ->
847 | {auto o : Ref ROpts REPLOpts} ->
848 | List ElabOpt -> NestedNames vars -> Env Term vars -> FC ->
849 | Name -> List ImpClause -> Core ()
850 | processDef opts nest env fc n_in cs_in
851 | = do n <- inCurrentNS n_in
852 | withDefStacked n $
do
854 | Just gdef <- lookupOrAddAlias opts nest env fc n cs_in
855 | | Nothing => noDeclaration fc n
856 | let None = definition gdef
857 | | _ => throw (AlreadyDefined fc n)
863 | let hashit = (collapseDefault $
visibility gdef) == Public || (Inline `elem` gdef.flags)
864 | let mult = if isErased (multiplicity gdef)
867 | nidx <- resolveName n
871 | log "declare.def" 5 $
"Traversing clauses of " ++ show n ++ " with mult " ++ show mult
872 | let treq = fromMaybe !getDefaultTotalityOption (findSetTotal (flags gdef))
873 | cs <- withTotality treq $
874 | traverse (checkClause mult (collapseDefault $
visibility gdef) treq
875 | hashit nidx opts nest env) cs_in
877 | let pats = map toPats (rights cs)
879 | (
cargs ** (tree_ct, unreachable))
<-
880 | logTime 3 ("Building compile time case tree for " ++ show n) $
881 | getPMDef fc (CompileTime mult) n ty (rights cs)
883 | traverse_ warnUnreachable unreachable
885 | logC "declare.def" 2 $
886 | do t <- toFullNames tree_ct
887 | pure ("Case tree for " ++ show n ++ ": " ++ show t)
891 | let pi = case lookup n (userHoles defs) of
892 | Nothing => defaultPI
893 | Just e => { externalDecl := e } defaultPI
897 | ignore $
addDef (Resolved nidx)
898 | ({ definition := PMDef pi cargs tree_ct tree_ct pats
901 | when (collapseDefault (visibility gdef) == Public) $
902 | do let rmetas = getMetas tree_ct
903 | log "declare.def" 10 $
"Saving from " ++ show n ++ ": " ++ show (keys rmetas)
904 | traverse_ addToSave (keys rmetas)
905 | when (isUserName n && collapseDefault (visibility gdef) /= Private) $
906 | do let tymetas = getMetas (type gdef)
907 | traverse_ addToSave (keys tymetas)
911 | update Ctxt { toCompileCase $= (n ::) }
913 | atotal <- toResolvedNames (NS builtinNS (UN $
Basic "assert_total"))
914 | logTime 3 ("Building size change graphs " ++ show n) $
915 | when (not (InCase `elem` opts)) $
916 | do calcRefs False atotal (Resolved nidx)
917 | sc <- calculateSizeChange fc n
918 | setSizeChange fc n sc
919 | checkIfGuarded fc n
923 | cov <- logTime 3 ("Checking Coverage " ++ show n) $
checkCoverage nidx ty mult cs
924 | setCovering fc n cov
929 | when (not (elem InCase opts)) $
930 | compileRunTime fc atotal
934 | withTotality : TotalReq -> Lazy (Core a) -> Core a
935 | withTotality tot c = do
936 | defaultTotality <- getDefaultTotalityOption
937 | setDefaultTotalityOption tot
938 | x <- catch c (\error => do setDefaultTotalityOption defaultTotality
940 | setDefaultTotalityOption defaultTotality
944 | simplePat : forall vars . Term vars -> Bool
945 | simplePat (Local {}) = True
946 | simplePat (Erased {}) = True
947 | simplePat (As _ _ _ p) = simplePat p
948 | simplePat _ = False
953 | catchAll : Clause -> Bool
954 | catchAll (MkClause env lhs _)
955 | = all simplePat (getArgs lhs)
960 | checkImpossible : Int -> RigCount -> ClosedTerm ->
961 | Core (Maybe ClosedTerm)
962 | checkImpossible n mult tm
963 | = do itm <- unelabNoPatvars Env.empty tm
964 | let itm = map rawName itm
966 | (do ctxt <- get Ctxt
967 | log "declare.def.impossible" 3 $
"Checking for impossibility: " ++ show itm
968 | autoimp <- isUnboundImplicits
969 | setUnboundImplicits True
970 | (_, lhstm) <- bindNames False itm
971 | setUnboundImplicits autoimp
972 | (lhstm, _) <- elabTerm n (InLHS mult) [] (MkNested []) Env.empty
973 | (IBindHere fc COVERAGE lhstm) Nothing
975 | lhs <- normaliseHoles defs Env.empty lhstm
976 | if !(hasEmptyPat defs Env.empty lhs)
977 | then do log "declare.def.impossible" 5 "Some empty pat"
980 | else do log "declare.def.impossible" 5 "No empty pat"
981 | empty <- clearDefs ctxt
982 | rtm <- closeEnv empty !(nf empty Env.empty lhs)
985 | (\err => do defs <- get Ctxt
986 | if !(impossibleErrOK defs err)
988 | log "declare.def.impossible" 5 "impossible because \{show err}"
990 | else pure (Just tm))
992 | closeEnv : Defs -> ClosedNF -> Core ClosedTerm
993 | closeEnv defs (NBind _ x (PVar {}) sc)
994 | = closeEnv defs !(sc defs (toClosure defaultOpts Env.empty (Ref fc Bound x)))
995 | closeEnv defs nf = quote defs Env.empty nf
997 | getClause : Either RawImp Clause -> Core (Maybe Clause)
998 | getClause (Left rawlhs)
999 | = catch (do lhsp <- getImpossibleTerm env nest rawlhs
1000 | log "declare.def.impossible" 3 $
"Generated impossible LHS: " ++ show lhsp
1001 | pure $
Just $
MkClause Env.empty lhsp (Erased (getFC rawlhs) Impossible))
1002 | (\e => do log "declare.def" 5 $
"Error in getClause " ++ show e
1003 | recordWarning $
GenericWarn (fromMaybe (getFC rawlhs) $
getErrorLoc e) (show e)
1005 | getClause (Right c) = pure (Just c)
1007 | checkCoverage : Int -> ClosedTerm -> RigCount ->
1008 | List (Either RawImp Clause) ->
1010 | checkCoverage n ty mult cs
1011 | = do covcs' <- traverse getClause cs
1012 | log "declare.def" 5 $
unlines
1014 | :: map ((" " ++) . show) !(traverse toFullNames covcs')
1015 | let covcs = mapMaybe id covcs'
1017 | getPMDef fc (CompileTime mult) (Resolved n) ty covcs
1018 | logC "declare.def" 3 $
do pure $
"Working from " ++ show !(toFullNames ctree)
1019 | missCase <- if any catchAll covcs
1020 | then do logC "declare.def" 3 $
do pure "Catch all case in \{show !(getFullName (Resolved n))}"
1022 | else getMissing fc (Resolved n) ty ctree
1024 | do mc <- traverse toFullNames missCase
1025 | pure ("Initially missing in " ++
1026 | show !(getFullName (Resolved n)) ++ ":\n" ++
1027 | showSep "\n" (map show mc))
1029 | missImp <- traverse (checkImpossible n mult) missCase
1032 | missMatch <- traverse (checkMatched (not $
isErased mult) covcs) (mapMaybe id missImp)
1035 | let miss = catMaybes missMatch
1037 | then do [] <- getNonCoveringRefs fc (Resolved n)
1038 | | ns => toFullNames (NonCoveringCall ns)
1040 | else pure (MissingCases miss)