0 | module TTImp.ProcessDef
   1 |
   2 | import Core.Case.CaseBuilder
   3 | import Core.Case.CaseTree
   4 | import Core.Case.CaseTree.Pretty
   5 | import Core.Coverage
   6 | import Core.Env
   7 | import Core.Hash
   8 | import Core.LinearCheck
   9 | import Core.Metadata
  10 | import Core.Termination
  11 | import Core.Termination.CallGraph
  12 | import Core.Transform
  13 | import Core.Value
  14 | import Core.UnifyState
  15 |
  16 | import Idris.REPL.Opts
  17 | import Idris.Syntax
  18 | import Idris.Pretty.Annotations
  19 |
  20 | import TTImp.BindImplicits
  21 | import TTImp.Elab
  22 | import TTImp.Elab.Binders
  23 | import TTImp.Elab.Check
  24 | import TTImp.Elab.Utils
  25 | import TTImp.Impossible
  26 | import TTImp.PartialEval
  27 | import TTImp.TTImp
  28 | import TTImp.TTImp.Functor
  29 | import TTImp.ProcessDef.Dot
  30 | import TTImp.ProcessType
  31 | import TTImp.Unelab
  32 | import TTImp.WithClause
  33 |
  34 | import Data.Either
  35 | import Data.List
  36 | import Data.String
  37 | import Data.Maybe
  38 | import Libraries.Data.NameMap
  39 | import Libraries.Data.WithDefault
  40 | import Libraries.Text.PrettyPrint.Prettyprinter
  41 | import Libraries.Data.List.SizeOf
  42 |
  43 | %default covering
  44 |
  45 | -- If the terms have the same type constructor at the head, and one of
  46 | -- the argument positions has different constructors at its head, then this
  47 | -- is an impossible case, so return True
  48 | export
  49 | impossibleOK : {auto c : Ref Ctxt Defs} ->
  50 |                {vars : _} ->
  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
  55 |
  56 | -- NPrimVal is apart from NDCon, NTCon, NBind, and NType
  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
  65 |
  66 | -- NTCon is apart from NBind, and NType
  67 | impossibleOK defs (NTCon {}) (NBind {}) = True
  68 | impossibleOK defs (NBind {}) (NTCon {}) = True
  69 | impossibleOK defs (NTCon {}) (NType {}) = True
  70 | impossibleOK defs (NType {}) (NTCon {}) = True
  71 |
  72 | -- NBind is apart from NType
  73 | impossibleOK defs (NBind {}) (NType {}) = True
  74 | impossibleOK defs (NType {}) (NBind {}) = True
  75 |
  76 | impossibleOK defs x y = False
  77 |
  78 | export
  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
  94 |
  95 | -- Given a type checked LHS and its type, return the environment in which we
  96 | -- should check the RHS, the LHS and its type in that environment,
  97 | -- and a function which turns a checked RHS into a
  98 | -- pattern clause
  99 | -- The 'Thin' proof contains a proof that refers to the *inner* environment,
 100 | -- so all the outer things are marked as 'Drop'
 101 | extendEnv : {vars : _} ->
 102 |             Env Term vars -> Thin inner vars ->
 103 |             NestedNames vars ->
 104 |             Term vars -> Term vars ->
 105 |             Core (vars' **
 106 |                     (Thin inner 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")
 117 |   -- PLet on the left becomes Let on the right, to give it computational force
 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))
 122 |
 123 | -- Find names which are applied to a function in a Rig1/Rig0 position,
 124 | -- so that we know how they should be bound on the right hand side of the
 125 | -- pattern.
 126 | -- 'bound' counts the number of variables locally bound; these are the
 127 | -- only ones we're checking linearity of (we may be shadowing names if this
 128 | -- is a local definition, so we need to leave the earlier ones alone)
 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 []
 140 |            (Ref _ nt n, args)
 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
 145 |            _ => pure []
 146 |     where
 147 |       accessible : NameType -> RigCount -> RigCount
 148 |       accessible Func r = if top then r else erased
 149 |       accessible _ r = r
 150 |
 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)
 155 |           = if isLinear c
 156 |                then case u of
 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
 162 |                let a = nameAt prf
 163 |                if idx < bound
 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 []
 176 |
 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)
 182 |          else tm
 183 |   where
 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
 190 |
 191 | -- Combining multiplicities on LHS:
 192 | -- Rig1 + Rig1/W not valid, since it means we have repeated use of name
 193 | -- Rig0 + RigW = RigW
 194 | -- Rig0 + Rig1 = Rig1
 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))
 204 |   where
 205 |     notN : (Name, RigCount) -> Bool
 206 |     notN (n', _) = n /= n'
 207 |
 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
 212 |
 213 |     -- Those combine rules are obtuse enough that they are worth investigating
 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)
 217 |                      -- if everything is fine, return the linearity that has the
 218 |                      -- highest bound
 219 |                      else pure (l `lub` r)
 220 |
 221 |     combineAll : RigCount -> List RigCount -> Core RigCount
 222 |     combineAll c [] = pure c
 223 |     combineAll c (c' :: cs)
 224 |         = do newc <- combine c c'
 225 |              combineAll newc cs
 226 |
 227 | export -- also used by Transforms
 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} ->
 234 |            (trans : Bool) -> -- in transform
 235 |            (mult : RigCount) ->
 236 |            Int -> List ElabOpt -> NestedNames vars -> Env Term vars ->
 237 |            FC -> RawImp ->
 238 |            Core (RawImp, -- checked LHS with implicits added
 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
 246 |                        then pure lhs_in
 247 |                        else lhsInCurrentNS nest lhs_in
 248 |          logRaw "declare.def.lhs" 30 "Raw LHS in current NS: " lhs_raw
 249 |
 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
 255 |
 256 |          lhs <- if trans
 257 |                    then pure lhs_bound
 258 |                    else implicitsAs n defs vars lhs_bound
 259 |
 260 |          fullname <- getFullName (Resolved n)
 261 |          log "declare.def.lhs" 5 $ "Checking LHS of " ++ show fullname
 262 | -- todo: add Pretty RawImp instance
 263 | --         logC "declare.def.lhs" 5 $ do pure $ show $ indent {ann = ()} 2 $ pretty lhs
 264 |          log "declare.def.lhs" 10 $ show lhs
 265 |          logEnv "declare.def.lhs" 5 "In env" env
 266 |          let lhsMode = if trans
 267 |                           then InTransform
 268 |                           else InLHS mult
 269 |          (lhstm, lhstyg) <-
 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
 275 |
 276 |          defs <- get Ctxt
 277 |          let lhsenv = letToLam env
 278 |          -- we used to fully normalise the LHS, to make sure fromInteger
 279 |          -- patterns were allowed, but now they're fully normalised anyway
 280 |          -- so we only need to do the holes. If there's a lot of type level
 281 |          -- computation, this is a huge saving!
 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
 286 |
 287 |          log "declare.def.lhs" 5 $ "Linearity of names in " ++ show n ++ ": " ++
 288 |                  show linvars_in
 289 |
 290 |          linvars <- combineLinear fc linvars_in
 291 |          let lhstm_lin = setLinear linvars lhstm
 292 |          let lhsty_lin = setLinear linvars lhsty
 293 |
 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)
 297 |
 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'
 301 |
 302 |          lhstm' <- if trans || not (isErased mult)
 303 |                       then pure lhstm'
 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
 307 |                               pure res
 308 |
 309 |          pure (lhs, (vars' ** (sub', env', nest', lhstm', lhsty')))
 310 |
 311 | -- Return whether any of the pattern variables are in a trivially empty
 312 | -- type, where trivally empty means one of:
 313 | --  * No constructors
 314 | --  * Every constructor of the family has a return type which conflicts with
 315 | --    the given constructor's type
 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
 323 |
 324 | -- For checking with blocks as nested names
 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))
 334 |
 335 | -- Check a pattern clause, returning the component of the 'Case' expression it
 336 | -- represents, or Nothing if it's an impossible clause
 337 | export
 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
 350 |          handleUnify
 351 |            (do autoimp <- isUnboundImplicits
 352 |                setUnboundImplicits True
 353 |                (_, lhs) <- bindNames False lhs_raw
 354 |                setUnboundImplicits autoimp
 355 |
 356 |                -- Add `{}` to the lhs for bind all arguments
 357 |                let lhs = INamedApp fc lhs (UN Underscore) (Implicit fc True)
 358 |
 359 |                log "declare.def.clause.impossible" 5 $ "Checking " ++ show lhs
 360 |                logEnv "declare.def.clause.impossible" 5 "In env" env
 361 |                (lhstm, lhstyg) <-
 362 |                            elabTerm n (InLHS mult) opts nest env
 363 |                                       (IBindHere fc COVERAGE lhs) Nothing
 364 |                defs <- get Ctxt
 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)))
 369 |            (\err =>
 370 |               case err of
 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'
 382 |
 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')
 386 |          clearHoleLHS
 387 |
 388 |          logTerm "declare.def.clause" 3 "RHS term" rhstm
 389 |          when hashit $
 390 |            do addHashWithNames lhstm'
 391 |               addHashWithNames rhstm
 392 |               log "module.hash" 15 "Adding hash for def."
 393 |
 394 |          -- If the rhs is a hole, record the lhs in the metadata because we
 395 |          -- might want to split it interactively
 396 |          case rhstm of
 397 |               Meta {} =>
 398 |                  addLHS (getFC lhs_in) (length env) env' lhstm'
 399 |               _ => pure ()
 400 |
 401 |          pure (Right (MkClause env' lhstm' rhstm))
 402 | -- TODO: (to decide) With is complicated. Move this into its own module?
 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
 407 |          let wmode
 408 |                = if isErased mult || isErased rig then InType else InExpr
 409 |
 410 |          (wval, gwvalTy) <- wrapErrorC opts (InRHS ifc !(getFullName (Resolved n))) $
 411 |                 elabTermSub n wmode opts nest' env' env sub' wval_raw Nothing
 412 |          clearHoleLHS
 413 |
 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
 417 |          defs <- get Ctxt
 418 |          wval <- normaliseHoles defs env' wval
 419 |          wvalTy <- normaliseHoles defs env' wvalTy
 420 |
 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
 424 |
 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")
 429 |          -- Should the env be normalised too? If the following 'impossible'
 430 |          -- error is ever thrown, that might be the cause!
 431 |          let Just wvalEnv = shrinkEnv env' withSub
 432 |              | Nothing => throw (InternalError "Impossible happened: With abstraction failure #3")
 433 |
 434 |          -- Abstracting over 'wval' in the scope of bNotReq in order
 435 |          -- to get the 'magic with' behaviour
 436 |          (wargs ** (scenv, var, binder)) <- bindWithArgs rig wvalTy ((,wval) <$> mprf) wvalEnv
 437 |
 438 |          let bnr = bindNotReq vfc 0 env' withSub [] reqty
 439 |          let notreqns = fst bnr
 440 |          let notreqty = snd bnr
 441 |
 442 |          rdefs <- if Syntactic `elem` flags
 443 |                      then clearDefs defs
 444 |                      else pure defs
 445 |          wtyScope <- replace rdefs scenv !(nf rdefs scenv (weakenNs (mkSizeOf wargs) wval))
 446 |                             var
 447 |                             !(nf rdefs scenv
 448 |                                  (weakenNs (mkSizeOf wargs) notreqty))
 449 |          let bNotReq = binder wtyScope
 450 |
 451 |          -- The environment has some implicit and some explcit args, potentially,
 452 |          -- which is inconvenient since we have to know which is which when
 453 |          -- elaborating the application of the rhs function. So it's easier
 454 |          -- if we just make them all explicit - this type isn't visible to
 455 |          -- users anyway!
 456 |          let env' = mkExplicit env'
 457 |
 458 |          let Just (reqns, envns, wtype) = bindReq vfc env' withSub [] bNotReq
 459 |              | Nothing => throw (InternalError "Impossible happened: With abstraction failure #4")
 460 |
 461 |          -- list of argument names - 'Just' means we need to match the name
 462 |          -- in the with clauses to find out what the pattern should be.
 463 |          -- 'Nothing' means it's the with pattern (so wargn)
 464 |          let wargNames
 465 |                  = map Just reqns ++
 466 |                    Nothing :: map Just notreqns
 467 |
 468 |          logTerm "declare.def.clause.with" 3 "With function type" wtype
 469 |          log "declare.def.clause.with" 5 $ "Argument names " ++ show wargNames
 470 |
 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))
 475 |
 476 |          let toWarg : Maybe (PiInfo RawImp, Name) -> List (Maybe Name, RawImp)
 477 |                := flip maybe (\pn => [(Nothing, IVar vfc (snd pn))]) $
 478 |                     (Nothing, wval_raw) ::
 479 |                     case mprf of
 480 |                       Nothing => []
 481 |                       Just _  =>
 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)]
 485 |
 486 |          let rhs_in = gapply (IVar vfc wname)
 487 |                     $ map (\ nm => (Nothing, IVar vfc nm)) envns
 488 |                    ++ concatMap toWarg wargNames
 489 |
 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
 493 |                           (gnf env' reqty)
 494 |
 495 |          -- Generate new clauses by rewriting the matched arguments
 496 |          cs' <- traverse (mkClauseWith 1 wname wargNames lhs) cs
 497 |          log "declare.def.clause.with" 3 $ "With clauses: " ++ show cs'
 498 |
 499 |          -- Elaborate the new definition here
 500 |          nestname <- applyEnv env wname
 501 |          let nest'' = { names $= (nestname ::) } nest
 502 |
 503 |          let wdef = IDef ifc wname cs'
 504 |          processDecl [] nest'' env wdef
 505 |
 506 |          pure (Right (MkClause env' lhspat rhs))
 507 |   where
 508 |     vfc : FC
 509 |     vfc = virtualiseFC ifc
 510 |
 511 |     bindWithArgs :
 512 |        (rig : RigCount) -> (wvalTy : Term xs) -> Maybe ((RigCount, Name), Term xs) ->
 513 |        (wvalEnv : Env Term xs) ->
 514 |        Core (ext : Scope
 515 |          ** ( Env Term (ext ++ xs)
 516 |             , Term (ext ++ xs)
 517 |             , (Term (ext ++ xs) -> Term xs)
 518 |             ))
 519 |     bindWithArgs {xs} rig wvalTy Nothing wvalEnv =
 520 |       let wargn : Name
 521 |           wargn = MN "warg" 0
 522 |           wargs : Scope
 523 |           wargs = [wargn]
 524 |
 525 |           scenv : Env Term (wargs ++ xs)
 526 |                 := Pi vfc top Explicit wvalTy :: wvalEnv
 527 |
 528 |           var : Term (wargs ++ xs)
 529 |               := Local vfc (Just False) Z First
 530 |
 531 |           binder : Term (wargs ++ xs) -> Term xs
 532 |                  := Bind vfc wargn (Pi vfc rig Explicit wvalTy)
 533 |
 534 |       in pure (wargs ** (scenv, var, binder))
 535 |
 536 |     bindWithArgs {xs} rig wvalTy (Just ((rigPrf, name), wval)) wvalEnv = do
 537 |       defs <- get Ctxt
 538 |
 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)
 543 |
 544 |       let wargn : Name
 545 |           wargn = MN "warg" 0
 546 |           wargs : Scope
 547 |           wargs = [name, wargn]
 548 |
 549 |           wvalTy' := weaken wvalTy
 550 |           eqTy : Term (MN "warg" 0 :: xs)
 551 |                := apply vfc eqTyCon
 552 |                            [ wvalTy'
 553 |                            , wvalTy'
 554 |                            , weaken wval
 555 |                            , Local vfc (Just False) Z First
 556 |                            ]
 557 |
 558 |           scenv : Env Term (wargs ++ xs)
 559 |                 := Pi vfc top Implicit eqTy
 560 |                 :: Pi vfc top Explicit wvalTy
 561 |                 :: wvalEnv
 562 |
 563 |           var : Term (wargs ++ xs)
 564 |               := Local vfc (Just False) (S Z) (Later First)
 565 |
 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
 569 |
 570 |       pure (wargs ** (scenv, var, binder))
 571 |
 572 |     -- If it's 'Keep/Refl' in 'outprf', that means it was in the outer
 573 |     -- environment so we need to keep it in the same place in the 'with'
 574 |     -- function. Hence, turn it to Keep whatever
 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
 582 |               (_ ** Drop rest)
 583 |     keepOldEnv (Drop p) (Keep p')
 584 |         = let (_ ** rest) = keepOldEnv p p' in
 585 |               (_ ** Keep rest)
 586 |     keepOldEnv (Keep p) (Drop p')
 587 |         = let (_ ** rest) = keepOldEnv p p' in
 588 |               (_ ** Keep rest)
 589 |     keepOldEnv (Keep p) (Keep p')
 590 |         = let (_ ** rest) = keepOldEnv p p' in
 591 |               (_ ** Keep rest)
 592 |
 593 |     -- Rewrite the clauses in the block to use an updated LHS.
 594 |     -- 'drop' is the number of additional with arguments we expect
 595 |     -- (i.e. the things to drop from the end before matching LHSs)
 596 |     mkClauseWith : (drop : Nat) -> Name ->
 597 |                    List (Maybe (PiInfo RawImp, Name)) ->
 598 |                    RawImp -> ImpClause ->
 599 |                    Core 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)
 615 |
 616 | -- Calculate references for the given name, and recursively if they haven't
 617 | -- been calculated already
 618 | calcRefs : {auto c : Ref Ctxt Defs} ->
 619 |            (runtime : Bool) -> (aTotal : Name) -> (fn : Name) -> Core ()
 620 | calcRefs rt at fn
 621 |     = do defs <- get Ctxt
 622 |          Just gdef <- lookupCtxtExact fn (gamma defs)
 623 |               | _ => pure ()
 624 |          let PMDef r cargs tree_ct tree_rt pats = definition gdef
 625 |               | _ => pure () -- not a function definition
 626 |          let refs : Maybe (NameMap Bool)
 627 |                   = if rt then refersToRuntimeM gdef else refersToM gdef
 628 |          let Nothing = refs
 629 |               | Just _ => pure () -- already done
 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)
 636 |                     (pure 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)
 641 |   where
 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)
 651 |
 652 | -- Compile run time case trees for the given name
 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 ()
 659 | mkRunTime fc n
 660 |     = do logC "compile.casetree" 5 $ do pure $ "Making run time definition for " ++ show !(toFullNames n)
 661 |          defs <- get Ctxt
 662 |          Just gdef <- lookupCtxtExact n (gamma defs)
 663 |               | _ => pure ()
 664 |          let cov = gdef.totality.isCovering
 665 |          -- If it's erased at run time, don't build the tree
 666 |          when (not (isErased $ multiplicity gdef)) $ do
 667 |            let PMDef r cargs tree_ct _ pats = definition gdef
 668 |                 | _ => pure () -- not a function definition
 669 |            let ty = type gdef
 670 |            -- Prepare RHS of definitions, by erasing 0-multiplicities, and
 671 |            -- finding any applications to specialise (partially evaluate)
 672 |            pats' <- traverse (toErased (location gdef) (getSpec (flags gdef)))
 673 |                              pats
 674 |
 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
 680 |
 681 |            (rargs ** (tree_rt, _)) <- getPMDef (location gdef) RunTime n ty clauses
 682 |            logC "compile.casetree" 5 $ do
 683 |              tree_rt <- toFullNames tree_rt
 684 |              pure $ unlines
 685 |                [ show cov ++ ":"
 686 |                , "Runtime tree for " ++ show (fullname gdef) ++ ":"
 687 |                , show (indent 2 $ prettyTree tree_rt)
 688 |                ]
 689 |            log "compile.casetree" 10 $ show tree_rt
 690 |            log "compile.casetree.measure" 15 $ show (measure tree_rt)
 691 |
 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
 696 |                        } gdef
 697 |            -- If it's a case block, and not already set as inlinable or forced
 698 |            -- to not be inlinable, check if it's safe to inline
 699 |            when (caseName !(toFullNames n) && noInline (flags gdef)) $
 700 |              do inl <- canInlineCaseBlock n
 701 |                 when inl $ do
 702 |                   logC "compiler.inline.eval" 5 $ do pure "Marking \{show !(toFullNames n)} for inlining in runtime case tree."
 703 |                   setFlag fc n Inline
 704 |   where
 705 |     -- check if the flags contain explicit inline or noinline directives:
 706 |     noInline : List DefFlag -> Bool
 707 |     noInline (Inline :: _)   = False
 708 |     noInline (NoInline :: _) = False
 709 |     noInline (x :: xs) = noInline xs
 710 |     noInline _ = True
 711 |
 712 |     caseName : Name -> Bool
 713 |     caseName (CaseBlock {}) = True
 714 |     caseName (NS _ n) = caseName n
 715 |     caseName _ = False
 716 |
 717 |     mkCrash : {vars : _} -> String -> Term vars
 718 |     mkCrash msg
 719 |        = apply fc (Ref fc Func (UN $ Basic "prim__crash"))
 720 |                [Erased fc Placeholder, PrimVal fc (Str msg)]
 721 |
 722 |     matchAny : Term vars -> Term vars
 723 |     matchAny (App fc f a) = App fc (matchAny f) (Erased fc Placeholder)
 724 |     matchAny tm = tm
 725 |
 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))
 730 |
 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
 736 |
 737 |     getSpec : List DefFlag -> Maybe (List (Name, Nat))
 738 |     getSpec [] = Nothing
 739 |     getSpec (PartialEval n :: _) = Just n
 740 |     getSpec (x :: xs) = getSpec xs
 741 |
 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
 747 |              -- Partially evaluate RHS here, where appropriate
 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))
 752 |
 753 |     toClause : FC -> (vars ** (Env Term vars, Term vars, Term vars)) -> Clause
 754 |     toClause fc (_ ** (env, lhs, rhs))
 755 |         = MkClause env lhs rhs
 756 |
 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)
 767 |
 768 |          update Ctxt { toCompileCase := [] }
 769 |
 770 | toPats : Clause -> (vs ** (Env Term vs, Term vs, Term vs))
 771 | toPats (MkClause {vars} env lhs rhs)
 772 |     = (_ ** (env, lhs, rhs))
 773 |
 774 | warnUnreachable : {auto c : Ref Ctxt Defs} ->
 775 |                   Clause -> Core ()
 776 | warnUnreachable (MkClause env lhs rhs)
 777 |     = recordWarning (UnreachableClause (getLoc lhs) env lhs)
 778 |
 779 | isAlias : RawImp -> Maybe ((FC, Name)              -- head symbol
 780 |                           , List (FC, (FC, Name))) -- pattern variables
 781 | isAlias lhs
 782 |   = do let (hd, apps) = getFnArgs lhs []
 783 |        hd <- isIVar hd
 784 |        args <- traverse (isExplicit >=> bitraverse pure isIBindVar) apps
 785 |        pure (hd, args)
 786 |
 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)
 800 |        -- No prior declaration:
 801 |        --   1) check whether it has the shape of an alias
 802 |        let Just (hd, args) = isAlias lhs
 803 |          | Nothing => pure Nothing
 804 |        --   2) check whether it could be a misspelling
 805 |        log "declare.def" 5 $
 806 |          "Missing type declaration for the alias "
 807 |          ++ show n
 808 |          ++ ". Checking first whether it is a misspelling."
 809 |        [] <- do -- get the candidates
 810 |                 Just (str, kept) <- getSimilarNames n
 811 |                    | Nothing => pure []
 812 |                 -- only keep the ones that haven't been defined yet
 813 |                 decls <- for kept $ \ (cand, vis, weight) => do
 814 |                     Just gdef <- lookupCtxtExact cand (gamma defs)
 815 |                       | Nothing => pure Nothing -- should be impossible
 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))
 821 |        --   3) declare an alias
 822 |        log "declare.def" 5 "Not a misspelling: go ahead and declare it!"
 823 |        processType eopts nest env fc top Public []
 824 |           -- See #3409
 825 |           $ Mk [fc, MkFCVal fc n] $ holeyType (map snd args)
 826 |        defs <- get Ctxt
 827 |        lookupCtxtExact n (gamma defs)
 828 |
 829 |   where
 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)
 835 |       $ holeyType xs
 836 |
 837 | lookupOrAddAlias _ _ _ fc n _
 838 |   = do defs <- get Ctxt
 839 |        lookupCtxtExact n (gamma defs)
 840 |
 841 | export
 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
 853 |          defs <- get Ctxt
 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)
 858 |          let ty = type gdef
 859 |          -- a module's interface hash (what determines when the module has changed)
 860 |          -- should include the definition (RHS) of anything that is public (available
 861 |          -- at compile time for elaboration) _or_ inlined (dropped into destination definitions
 862 |          -- during compilation).
 863 |          let hashit = (collapseDefault $ visibility gdef) == Public || (Inline `elem` gdef.flags)
 864 |          let mult = if isErased (multiplicity gdef)
 865 |                        then erased
 866 |                        else linear
 867 |          nidx <- resolveName n
 868 |
 869 |          -- Dynamically rebind default totality requirement to this function's totality requirement
 870 |          -- and use this requirement when processing `with` blocks
 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
 876 |
 877 |          let pats = map toPats (rights cs)
 878 |
 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)
 882 |
 883 |          traverse_ warnUnreachable unreachable
 884 |
 885 |          logC "declare.def" 2 $
 886 |                  do t <- toFullNames tree_ct
 887 |                     pure ("Case tree for " ++ show n ++ ": " ++ show t)
 888 |
 889 |          -- check whether the name was declared in a different source file
 890 |          defs <- get Ctxt
 891 |          let pi = case lookup n (userHoles defs) of
 892 |                         Nothing => defaultPI
 893 |                         Just e => { externalDecl := e } defaultPI
 894 |          -- Add compile time tree as a placeholder for the runtime tree,
 895 |          -- but we'll rebuild that in a later pass once all the case
 896 |          -- blocks etc are resolved
 897 |          ignore $ addDef (Resolved nidx)
 898 |                   ({ definition := PMDef pi cargs tree_ct tree_ct pats
 899 |                    } gdef)
 900 |
 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)
 908 |          addToSave n
 909 |
 910 |          -- Flag this name as one which needs compiling
 911 |          update Ctxt { toCompileCase $= (n ::) }
 912 |
 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
 920 |
 921 |          md <- get MD -- don't need the metadata collected on the coverage check
 922 |
 923 |          cov <- logTime 3 ("Checking Coverage " ++ show n) $ checkCoverage nidx ty mult cs
 924 |          setCovering fc n cov
 925 |          put MD md
 926 |
 927 |          -- If we're not in a case tree, compile all the outstanding case
 928 |          -- trees.
 929 |          when (not (elem InCase opts)) $
 930 |               compileRunTime fc atotal
 931 |   where
 932 |     -- Move `withTotality` to Core.Context if we need it elsewhere
 933 |     ||| Temporarily rebind the default totality requirement (%default total/partial/covering).
 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
 939 |                                     throw error)
 940 |          setDefaultTotalityOption defaultTotality
 941 |          pure x
 942 |
 943 |
 944 |     simplePat : forall vars . Term vars -> Bool
 945 |     simplePat (Local {}) = True
 946 |     simplePat (Erased {}) = True
 947 |     simplePat (As _ _ _ p) = simplePat p
 948 |     simplePat _ = False
 949 |
 950 |     -- Is the clause returned from 'checkClause' a catch all clause, i.e.
 951 |     -- one where all the arguments are variables? If so, no need to do the
 952 |     -- (potentially expensive) coverage check
 953 |     catchAll : Clause -> Bool
 954 |     catchAll (MkClause env lhs _)
 955 |        = all simplePat (getArgs lhs)
 956 |
 957 |     -- Return 'Nothing' if the clause is impossible, otherwise return the
 958 |     -- checked clause (with implicits filled in, so that we can see if they
 959 |     -- match any of the given clauses)
 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
 965 |              handleUnify
 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
 974 |                    defs <- get Ctxt
 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"
 978 |                               put Ctxt ctxt
 979 |                               pure Nothing
 980 |                       else do log "declare.def.impossible" 5 "No empty pat"
 981 |                               empty <- clearDefs ctxt
 982 |                               rtm <- closeEnv empty !(nf empty Env.empty lhs)
 983 |                               put Ctxt ctxt
 984 |                               pure (Just rtm))
 985 |                (\err => do defs <- get Ctxt
 986 |                            if !(impossibleErrOK defs err)
 987 |                               then do
 988 |                                 log "declare.def.impossible" 5 "impossible because \{show err}"
 989 |                                 pure Nothing
 990 |                               else pure (Just tm))
 991 |       where
 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
 996 |
 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)
1004 |                           pure Nothing)
1005 |     getClause (Right c) = pure (Just c)
1006 |
1007 |     checkCoverage : Int -> ClosedTerm -> RigCount ->
1008 |                     List (Either RawImp Clause) ->
1009 |                     Core Covering
1010 |     checkCoverage n ty mult cs
1011 |         = do covcs' <- traverse getClause cs -- Make stand in LHS for impossible clauses
1012 |              log "declare.def" 5 $ unlines
1013 |                $ "Using clauses :"
1014 |                :: map (("  " ++) . show) !(traverse toFullNames covcs')
1015 |              let covcs = mapMaybe id covcs'
1016 |              (_ ** (ctree, _)) <-
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))}"
1021 |                                     pure []
1022 |                             else getMissing fc (Resolved n) ty ctree
1023 |              logC "declare.def" 3 $
1024 |                      do mc <- traverse toFullNames missCase
1025 |                         pure ("Initially missing in " ++
1026 |                                  show !(getFullName (Resolved n)) ++ ":\n" ++
1027 |                                 showSep "\n" (map show mc))
1028 |              -- Filter out the ones which are impossible
1029 |              missImp <- traverse (checkImpossible n mult) missCase
1030 |              -- Filter out the ones which are actually matched (perhaps having
1031 |              -- come up due to some overlapping patterns)
1032 |              missMatch <- traverse (checkMatched (not $ isErased mult) covcs) (mapMaybe id missImp)
1033 |                                               -- ^ Do not check coverage for erased arguments
1034 |                                               -- only in non-erased functions (Issues #1998, #3357)
1035 |              let miss = catMaybes missMatch
1036 |              if isNil miss
1037 |                 then do [] <- getNonCoveringRefs fc (Resolved n)
1038 |                            | ns => toFullNames (NonCoveringCall ns)
1039 |                         pure IsCovering
1040 |                 else pure (MissingCases miss)
1041 |