0 | module Core.Context
   1 |
   2 | import        Core.Case.CaseTree
   3 | import        Core.CompileExpr
   4 | import public Core.Context.Context
   5 | import public Core.Core
   6 | import        Core.Env
   7 | import        Core.Hash
   8 | import public Core.Name
   9 | import        Core.Options
  10 | import public Core.Options.Log
  11 | import public Core.TT
  12 |
  13 | import Libraries.Utils.Binary
  14 | import Libraries.Utils.Path
  15 | import Libraries.Utils.Scheme
  16 | import Libraries.Text.PrettyPrint.Prettyprinter
  17 |
  18 | import Idris.Syntax.Pragmas
  19 |
  20 | import Data.Either
  21 | import Data.IOArray
  22 | import Data.List1
  23 | import Data.Nat
  24 | import Data.String
  25 | import Data.SortedSet
  26 | import Libraries.Data.IntMap
  27 | import Libraries.Data.NameMap
  28 | import Libraries.Data.NatSet
  29 | import Libraries.Data.StringMap
  30 | import Libraries.Data.UserNameMap
  31 | import Libraries.Data.WithDefault
  32 | import Libraries.Text.Distance.Levenshtein
  33 |
  34 | import System.Clock
  35 | import System.Directory
  36 |
  37 | %default covering
  38 |
  39 | export
  40 | getContent : Context -> Ref Arr (IOArray ContextEntry)
  41 | getContent = content
  42 |
  43 | export
  44 | namesResolvedAs : Context -> NameMap Name
  45 | namesResolvedAs ctxt = map Resolved ctxt.resolvedAs
  46 |
  47 | -- Implemented later, once we can convert to and from full names
  48 | -- Defined in Core.TTC
  49 | export
  50 | decode : Context -> Int -> (update : Bool) -> ContextEntry -> Core GlobalDef
  51 |
  52 | initSize : Int
  53 | initSize = 10000
  54 |
  55 | Grow : Int
  56 | Grow = initSize
  57 |
  58 | export
  59 | initCtxtS : Int -> Core Context
  60 | initCtxtS s
  61 |     = do arr <- coreLift $ newArray s
  62 |          aref <- newRef Arr arr
  63 |          pure $ MkContext
  64 |             { firstEntry = 0
  65 |             , nextEntry = 0
  66 |             , resolvedAs = empty
  67 |             , possibles = empty
  68 |             , content = aref
  69 |             , branchDepth = 0
  70 |             , staging = empty
  71 |             , visibleNS = [partialEvalNS]
  72 |             , allPublic = False
  73 |             , inlineOnly = False
  74 |             , hidden = empty
  75 |             , uconstraints = []
  76 |             }
  77 |
  78 | export
  79 | initCtxt : Core Context
  80 | initCtxt = initCtxtS initSize
  81 |
  82 | addPossible : Name -> Int ->
  83 |               UserNameMap (List PossibleName) -> UserNameMap (List PossibleName)
  84 | addPossible n i ps
  85 |     = case userNameRoot n of
  86 |            Nothing => ps
  87 |            Just nr =>
  88 |               case lookup nr ps of
  89 |                    Nothing => insert nr [Direct n i] ps
  90 |                    Just nis => insert nr (Direct n i :: nis) ps
  91 |
  92 | addAlias : Name -> Name -> Int ->
  93 |            UserNameMap (List PossibleName) -> UserNameMap (List PossibleName)
  94 | addAlias alias full i ps
  95 |     = case userNameRoot alias of
  96 |            Nothing => ps
  97 |            Just nr =>
  98 |               case lookup nr ps of
  99 |                    Nothing => insert nr [Alias alias full i] ps
 100 |                    Just nis => insert nr (Alias alias full i :: nis) ps
 101 |
 102 | export
 103 | newEntry : Name -> Context -> Core (Int, Context)
 104 | newEntry n ctxt
 105 |     = do let idx = nextEntry ctxt
 106 |          let a = content ctxt
 107 |          arr <- get Arr
 108 |          when (idx >= max arr) $
 109 |                  do arr' <- coreLift $ newArrayCopy (max arr + Grow) arr
 110 |                     put Arr arr'
 111 |          pure (idx, { nextEntry := idx + 1,
 112 |                       resolvedAs $= insert n idx,
 113 |                       possibles $= addPossible n idx
 114 |                     } ctxt)
 115 |
 116 | -- Get the position of the next entry in the context array, growing the
 117 | -- array if it's out of bounds.
 118 | -- Updates the context with the mapping from name to index
 119 | export
 120 | getPosition : Name -> Context -> Core (Int, Context)
 121 | getPosition (Resolved idx) ctxt = pure (idx, ctxt)
 122 | getPosition n ctxt
 123 |     = case lookup n (resolvedAs ctxt) of
 124 |            Just idx =>
 125 |               do pure (idx, ctxt)
 126 |            Nothing => newEntry n ctxt
 127 |
 128 | newAlias : Name -> Name -> Context -> Core Context
 129 | newAlias alias full ctxt
 130 |     = do (idx, ctxt) <- getPosition full ctxt
 131 |          pure $ { possibles $= addAlias alias full idx } ctxt
 132 |
 133 | export
 134 | getNameID : Name -> Context -> Maybe Int
 135 | getNameID (Resolved idx) ctxt = Just idx
 136 | getNameID n ctxt = lookup n (resolvedAs ctxt)
 137 |
 138 | -- Add the name to the context, or update the existing entry if it's already
 139 | -- there.
 140 | -- If we're not at the top level, add it to the staging area
 141 | export
 142 | addCtxt : Name -> GlobalDef -> Context -> Core (Int, Context)
 143 | addCtxt n val ctxt_in
 144 |     = if branchDepth ctxt_in == 0
 145 |          then do (idx, ctxt) <- getPosition n ctxt_in
 146 |                  let a = content ctxt
 147 |                  arr <- get Arr
 148 |                  coreLift_ $ writeArray arr idx (Decoded val)
 149 |                  pure (idx, ctxt)
 150 |          else do (idx, ctxt) <- getPosition n ctxt_in
 151 |                  pure (idx, { staging $= insert idx (Decoded val) } ctxt)
 152 |
 153 | export
 154 | addEntry : Name -> ContextEntry -> Context -> Core (Int, Context)
 155 | addEntry n entry ctxt_in
 156 |     = if branchDepth ctxt_in == 0
 157 |          then do (idx, ctxt) <- getPosition n ctxt_in
 158 |                  let a = content ctxt
 159 |                  arr <- get Arr
 160 |                  coreLift_ $ writeArray arr idx entry
 161 |                  pure (idx, ctxt)
 162 |          else do (idx, ctxt) <- getPosition n ctxt_in
 163 |                  pure (idx, { staging $= insert idx entry } ctxt)
 164 |
 165 | returnDef : Bool -> Int -> GlobalDef -> Maybe (Int, GlobalDef)
 166 | returnDef False idx def = Just (idx, def)
 167 | returnDef True idx def
 168 |     = case definition def of
 169 |            PMDef pi _ _ _ _ =>
 170 |                  if alwaysReduce pi
 171 |                     then Just (idx, def)
 172 |                     else Nothing
 173 |            _ => Nothing
 174 |
 175 | export
 176 | lookupCtxtExactI : Name -> Context -> Core (Maybe (Int, GlobalDef))
 177 | lookupCtxtExactI (Resolved idx) ctxt
 178 |     = case lookup idx (staging ctxt) of
 179 |            Just val =>
 180 |                  pure $ returnDef (inlineOnly ctxt) idx !(decode ctxt idx True val)
 181 |            Nothing =>
 182 |               do arr <- get Arr @{content ctxt}
 183 |                  Just def <- coreLift (readArray arr idx)
 184 |                       | Nothing => pure Nothing
 185 |                  pure $ returnDef (inlineOnly ctxt) idx !(decode ctxt idx True def)
 186 | lookupCtxtExactI n ctxt
 187 |     = do let Just idx = lookup n (resolvedAs ctxt)
 188 |                   | Nothing => pure Nothing
 189 |          lookupCtxtExactI (Resolved idx) ctxt
 190 |
 191 | export
 192 | lookupCtxtExact : Name -> Context -> Core (Maybe GlobalDef)
 193 | lookupCtxtExact (Resolved idx) ctxt
 194 |     = case lookup idx (staging ctxt) of
 195 |            Just res =>
 196 |                 do def <- decode ctxt idx True res
 197 |                    pure $ map (\(_, def) => def) $
 198 |                      returnDef (inlineOnly ctxt) idx def
 199 |            Nothing =>
 200 |               do arr <- get Arr @{content ctxt}
 201 |                  Just res <- coreLift (readArray arr idx)
 202 |                       | Nothing => pure Nothing
 203 |                  def <- decode ctxt idx True res
 204 |                  pure $ map (\(_, def) => def) $
 205 |                    returnDef (inlineOnly ctxt) idx def
 206 | lookupCtxtExact n ctxt
 207 |     = do Just (i, def) <- lookupCtxtExactI n ctxt
 208 |               | Nothing => pure Nothing
 209 |          pure (Just def)
 210 |
 211 | export
 212 | lookupContextEntry : Name -> Context -> Core (Maybe (Int, ContextEntry))
 213 | lookupContextEntry (Resolved idx) ctxt
 214 |     = case lookup idx (staging ctxt) of
 215 |            Just res => pure (Just (idx, res))
 216 |            Nothing =>
 217 |               do let a = content ctxt
 218 |                  arr <- get Arr
 219 |                  Just res <- coreLift (readArray arr idx)
 220 |                       | Nothing => pure Nothing
 221 |                  pure (Just (idx, res))
 222 | lookupContextEntry n ctxt
 223 |     = do let Just idx = lookup n (resolvedAs ctxt)
 224 |                   | Nothing => pure Nothing
 225 |          lookupContextEntry (Resolved idx) ctxt
 226 |
 227 | ||| Check if the given name has been hidden by the `%hide` directive.
 228 | export
 229 | isHidden : Name -> Context -> Bool
 230 | isHidden fulln ctxt = isJust $ lookup fulln (hidden ctxt)
 231 |
 232 | ||| Look up a possibly hidden name in the context. The first (boolean) argument
 233 | ||| controls whether names hidden by `%hide` are returned too (True=yes, False=no).
 234 | export
 235 | lookupCtxtName' : Bool -> Name -> Context -> Core (List (Name, Int, GlobalDef))
 236 | lookupCtxtName' allowHidden n ctxt
 237 |     = case userNameRoot n of
 238 |            Nothing => do Just (i, res) <- lookupCtxtExactI n ctxt
 239 |                               | Nothing => pure []
 240 |                          pure [(n, i, res)]
 241 |            Just r =>
 242 |               do let Just ps = lookup r (possibles ctxt)
 243 |                       | Nothing => pure []
 244 |                  lookupPossibles [] ps
 245 |   where
 246 |
 247 |     resn : (Name, Int, GlobalDef) -> Int
 248 |     resn (_, i, _) = i
 249 |
 250 |     hlookup : Name -> NameMap () -> Maybe ()
 251 |     hlookup fulln hiddens = if allowHidden
 252 |       then Nothing
 253 |       else lookup fulln hiddens
 254 |
 255 |     lookupPossibles : List (Name, Int, GlobalDef) -> -- accumulator
 256 |                       List PossibleName ->
 257 |                       Core (List (Name, Int, GlobalDef))
 258 |     lookupPossibles acc [] = pure (reverse acc)
 259 |     lookupPossibles acc (Direct fulln i :: ps)
 260 |        = case (hlookup fulln (hidden ctxt)) of
 261 |               Nothing =>
 262 |                 do Just res <- lookupCtxtExact (Resolved i) ctxt
 263 |                         | Nothing => lookupPossibles acc ps
 264 |                    if matches n fulln && not (i `elem` map resn acc)
 265 |                       then lookupPossibles ((fulln, i, res) :: acc) ps
 266 |                       else lookupPossibles acc ps
 267 |               _ => lookupPossibles acc ps
 268 |     lookupPossibles acc (Alias asn fulln i :: ps)
 269 |        = case (hlookup fulln (hidden ctxt)) of
 270 |               Nothing =>
 271 |                 do Just res <- lookupCtxtExact (Resolved i) ctxt
 272 |                         | Nothing => lookupPossibles acc ps
 273 |                    if (matches n asn) && not (i `elem` map resn acc)
 274 |                       then lookupPossibles ((fulln, i, res) :: acc) ps
 275 |                       else lookupPossibles acc ps
 276 |               _ => lookupPossibles acc ps
 277 |
 278 | ||| Look up a name in the context, ignoring names hidden by `%hide`.
 279 | export
 280 | lookupCtxtName : Name -> Context -> Core (List (Name, Int, GlobalDef))
 281 | lookupCtxtName = lookupCtxtName' False
 282 |
 283 | ||| Look up a (possible hidden) name in the context.
 284 | export
 285 | lookupHiddenCtxtName : Name -> Context -> Core (List (Name, Int, GlobalDef))
 286 | lookupHiddenCtxtName = lookupCtxtName' True
 287 |
 288 | hideName : Name -> Context -> Context
 289 | hideName n ctxt = { hidden $= insert n () } ctxt
 290 |
 291 | unhideName : Name -> Context -> Context
 292 | unhideName n ctxt = { hidden $= delete n } ctxt
 293 |
 294 | branchCtxt : Context -> Core Context
 295 | branchCtxt ctxt = pure ({ branchDepth $= S } ctxt)
 296 |
 297 | commitCtxt : Context -> Core Context
 298 | commitCtxt ctxt
 299 |     = case branchDepth ctxt of
 300 |            Z => pure ctxt
 301 |            S Z => -- add all the things from 'staging' to the real array
 302 |                   do let a = content ctxt
 303 |                      arr <- get Arr
 304 |                      coreLift $ commitStaged (toList (staging ctxt)) arr
 305 |                      pure ({ staging := empty,
 306 |                              branchDepth := Z } ctxt)
 307 |            S k => pure ({ branchDepth := k } ctxt)
 308 |   where
 309 |     -- We know the array must be big enough, because it will have been resized
 310 |     -- if necessary in the branch to fit the index we've been given here
 311 |     commitStaged : List (Int, ContextEntry) -> IOArray ContextEntry -> IO ()
 312 |     commitStaged [] arr = pure ()
 313 |     commitStaged ((idx, val) :: rest) arr
 314 |         = do ignore $ writeArray arr idx val
 315 |              commitStaged rest arr
 316 |
 317 | ||| Produce a new global definition with a lot of default values
 318 | ||| @fc   definition site
 319 | ||| @n    name
 320 | ||| @rig  quantity annotation
 321 | ||| @vars local variables
 322 | ||| @ty   (closed) type
 323 | ||| @vis  Visibility, defaulting to private
 324 | ||| @def  actual definition
 325 | export
 326 | newDef : (fc : FC) -> (n : Name) -> (rig : RigCount) -> (vars : Scope) ->
 327 |          (ty : ClosedTerm) -> (vis : WithDefault Visibility Private) -> (def : Def) -> GlobalDef
 328 | newDef fc n rig vars ty vis def
 329 |     = MkGlobalDef
 330 |         { location = fc
 331 |         , fullname = n
 332 |         , type = ty
 333 |         , eraseArgs = NatSet.empty
 334 |         , safeErase = NatSet.empty
 335 |         , specArgs = NatSet.empty
 336 |         , inferrable = NatSet.empty
 337 |         , multiplicity = rig
 338 |         , localVars = vars
 339 |         , visibility = vis
 340 |         , totality = unchecked
 341 |         , isEscapeHatch = False
 342 |         , flags = []
 343 |         , refersToM = Nothing
 344 |         , refersToRuntimeM = Nothing
 345 |         , invertible = False
 346 |         , noCycles = False
 347 |         , linearChecked = False
 348 |         , definition = def
 349 |         , compexpr = Nothing
 350 |         , namedcompexpr = Nothing
 351 |         , sizeChange = []
 352 |         , schemeExpr = Nothing
 353 |         }
 354 |
 355 | -- Rewrite rules, applied after type checking, for runtime code only
 356 | -- LHS and RHS must have the same type, but we don't (currently) require that
 357 | -- the result still type checks (which might happen e.g. if transforming to a
 358 | -- faster implementation with different behaviour)
 359 | -- (Q: Do we need the 'Env' here? Usually we end up needing an 'Env' with a
 360 | -- 'NF but we're working with terms rather than values...)
 361 | public export
 362 | data Transform : Type where
 363 |      MkTransform : {vars : _} ->
 364 |                    Name -> -- name for identifying the rule
 365 |                    Env Term vars -> Term vars -> Term vars -> Transform
 366 |
 367 | ||| Types that are transformed into a faster representation
 368 | ||| during codegen.
 369 | public export
 370 | data BuiltinType : Type where
 371 |     BuiltinNatural : BuiltinType
 372 |     NaturalToInteger : BuiltinType
 373 |     IntegerToNatural : BuiltinType
 374 |
 375 | export
 376 | Show BuiltinType where
 377 |     show BuiltinNatural = "Natural"
 378 |     show NaturalToInteger = "NaturalToInteger"
 379 |     show IntegerToNatural = "IntegerToNatural"
 380 |
 381 | export
 382 | getFnName : Transform -> Maybe Name
 383 | getFnName (MkTransform _ _ app _)
 384 |     = case getFn app of
 385 |            Ref _ _ fn => Just fn
 386 |            _ => Nothing
 387 |
 388 | -- TODO: refactor via a single function
 389 | -- onNames : (Context -> Name -> Core Name) ->
 390 | --           (Context -> a    -> Core a)
 391 | -- ?
 392 | public export
 393 | interface HasNames a where
 394 |   full : Context -> a -> Core a
 395 |   resolved : Context -> a -> Core a
 396 |
 397 | export
 398 | HasNames Name where
 399 |   full gam (Resolved i)
 400 |       = do Just gdef <- lookupCtxtExact (Resolved i) gam
 401 |                   -- May occasionally happen when working with metadata.
 402 |                   -- It's harmless, so just silently return the resolved name.
 403 |                 | Nothing => pure (Resolved i)
 404 |            pure (fullname gdef)
 405 |   full gam n = pure n
 406 |
 407 |   resolved gam (Resolved i)
 408 |       = pure (Resolved i)
 409 |   resolved gam n
 410 |       = do let Just i = getNameID n gam
 411 |                     | Nothing => pure n
 412 |            pure (Resolved i)
 413 |
 414 | export
 415 | HasNames UConstraint where
 416 |   full gam (ULT x y)
 417 |       = do x' <- full gam x; y' <- full gam y
 418 |            pure (ULT x' y')
 419 |   full gam (ULE x y)
 420 |       = do x' <- full gam x; y' <- full gam y
 421 |            pure (ULE x' y')
 422 |
 423 |   resolved gam (ULT x y)
 424 |       = do x' <- resolved gam x; y' <- resolved gam y
 425 |            pure (ULT x' y')
 426 |   resolved gam (ULE x y)
 427 |       = do x' <- resolved gam x; y' <- resolved gam y
 428 |            pure (ULE x' y')
 429 |
 430 | export
 431 | HasNames (Term vars) where
 432 |   full gam (Ref fc x (Resolved i))
 433 |       = do Just gdef <- lookupCtxtExact (Resolved i) gam
 434 |                 | Nothing => pure (Ref fc x (Resolved i))
 435 |            pure (Ref fc x (fullname gdef))
 436 |   full gam (Meta fc x i xs)
 437 |       = do xs <- traverse (full gam) xs
 438 |            pure $ case !(lookupCtxtExact (Resolved i) gam) of
 439 |              Nothing => Meta fc x i xs
 440 |              Just gdef => Meta fc (fullname gdef) i xs
 441 |   full gam (Bind fc x b scope)
 442 |       = pure (Bind fc x !(traverse (full gam) b) !(full gam scope))
 443 |   full gam (App fc fn arg)
 444 |       = pure (App fc !(full gam fn) !(full gam arg))
 445 |   full gam (As fc s p tm)
 446 |       = pure (As fc s !(full gam p) !(full gam tm))
 447 |   full gam (TDelayed fc x y)
 448 |       = pure (TDelayed fc x !(full gam y))
 449 |   full gam (TDelay fc x t y)
 450 |       = pure (TDelay fc x !(full gam t) !(full gam y))
 451 |   full gam (TForce fc r y)
 452 |       = pure (TForce fc r !(full gam y))
 453 |   full gam (TType fc (Resolved i))
 454 |       = do Just gdef <- lookupCtxtExact (Resolved i) gam
 455 |                 | Nothing => pure (TType fc (Resolved i))
 456 |            pure (TType fc (fullname gdef))
 457 |   full gam (Erased fc (Dotted t))
 458 |       = pure (Erased fc (Dotted !(full gam t)))
 459 |   full gam tm = pure tm
 460 |
 461 |   resolved gam (Ref fc x n)
 462 |       = do let Just i = getNameID n gam
 463 |                 | Nothing => pure (Ref fc x n)
 464 |            pure (Ref fc x (Resolved i))
 465 |   resolved gam (Meta fc x y xs)
 466 |       = do xs' <- traverse (resolved gam) xs
 467 |            let Just i = getNameID x gam
 468 |                | Nothing => pure (Meta fc x y xs')
 469 |            pure (Meta fc x i xs')
 470 |   resolved gam (Bind fc x b scope)
 471 |       = pure (Bind fc x !(traverse (resolved gam) b) !(resolved gam scope))
 472 |   resolved gam (App fc fn arg)
 473 |       = pure (App fc !(resolved gam fn) !(resolved gam arg))
 474 |   resolved gam (As fc s p tm)
 475 |       = pure (As fc s !(resolved gam p) !(resolved gam tm))
 476 |   resolved gam (TDelayed fc x y)
 477 |       = pure (TDelayed fc x !(resolved gam y))
 478 |   resolved gam (TDelay fc x t y)
 479 |       = pure (TDelay fc x !(resolved gam t) !(resolved gam y))
 480 |   resolved gam (TForce fc r y)
 481 |       = pure (TForce fc r !(resolved gam y))
 482 |   resolved gam (TType fc n)
 483 |       = do let Just i = getNameID n gam
 484 |                 | Nothing => pure (TType fc n)
 485 |            pure (TType fc (Resolved i))
 486 |   resolved gam (Erased fc (Dotted t))
 487 |       = pure (Erased fc (Dotted !(resolved gam t)))
 488 |   resolved gam tm = pure tm
 489 |
 490 | export
 491 | HasNames Pat where
 492 |   full gam (PAs fc n p)
 493 |      = [| PAs (pure fc) (full gam n) (full gam p) |]
 494 |   full gam (PCon fc n i ar ps)
 495 |      = [| PCon (pure fc) (full gam n) (pure i) (pure ar) (traverse (full gam) ps) |]
 496 |   full gam (PTyCon fc n ar ps)
 497 |      = [| PTyCon (pure fc) (full gam n) (pure ar) (traverse (full gam) ps) |]
 498 |   full gam p@(PConst {}) = pure p
 499 |   full gam (PArrow fc x p q)
 500 |      = [| PArrow (pure fc) (full gam x) (full gam p) (full gam q) |]
 501 |   full gam (PDelay fc laz p q)
 502 |      = [| PDelay (pure fc) (pure laz) (full gam p) (full gam q) |]
 503 |   full gam (PLoc fc n) = PLoc fc <$> full gam n
 504 |   full gam (PUnmatchable fc t) = PUnmatchable fc <$> full gam t
 505 |
 506 |   resolved gam (PAs fc n p)
 507 |      = [| PAs (pure fc) (resolved gam n) (resolved gam p) |]
 508 |   resolved gam (PCon fc n i ar ps)
 509 |      = [| PCon (pure fc) (resolved gam n) (pure i) (pure ar) (traverse (resolved gam) ps) |]
 510 |   resolved gam (PTyCon fc n ar ps)
 511 |      = [| PTyCon (pure fc) (resolved gam n) (pure ar) (traverse (resolved gam) ps) |]
 512 |   resolved gam p@(PConst {}) = pure p
 513 |   resolved gam (PArrow fc x p q)
 514 |      = [| PArrow (pure fc) (resolved gam x) (resolved gam p) (resolved gam q) |]
 515 |   resolved gam (PDelay fc laz p q)
 516 |      = [| PDelay (pure fc) (pure laz) (resolved gam p) (resolved gam q) |]
 517 |   resolved gam (PLoc fc n) = PLoc fc <$> resolved gam n
 518 |   resolved gam (PUnmatchable fc t) = PUnmatchable fc <$> resolved gam t
 519 |
 520 | mutual
 521 |   export
 522 |   HasNames (CaseTree vars) where
 523 |     full gam (Case i v ty alts)
 524 |         = pure $ Case i v !(full gam ty) !(traverse (full gam) alts)
 525 |     full gam (STerm i tm)
 526 |         = pure $ STerm i !(full gam tm)
 527 |     full gam t = pure t
 528 |
 529 |     resolved gam (Case i v ty alts)
 530 |         = pure $ Case i v !(resolved gam ty) !(traverse (resolved gam) alts)
 531 |     resolved gam (STerm i tm)
 532 |         = pure $ STerm i !(resolved gam tm)
 533 |     resolved gam t = pure t
 534 |
 535 |   export
 536 |   HasNames (CaseAlt vars) where
 537 |     full gam (ConCase n t args sc)
 538 |         = do sc' <- full gam sc
 539 |              Just gdef <- lookupCtxtExact n gam
 540 |                 | Nothing => pure (ConCase n t args sc')
 541 |              pure $ ConCase (fullname gdef) t args sc'
 542 |     full gam (DelayCase ty arg sc)
 543 |         = pure $ DelayCase ty arg !(full gam sc)
 544 |     full gam (ConstCase c sc)
 545 |         = pure $ ConstCase c !(full gam sc)
 546 |     full gam (DefaultCase sc)
 547 |         = pure $ DefaultCase !(full gam sc)
 548 |
 549 |     resolved gam (ConCase n t args sc)
 550 |         = do sc' <- resolved gam sc
 551 |              let Just i = getNameID n gam
 552 |                 | Nothing => pure (ConCase n t args sc')
 553 |              pure $ ConCase (Resolved i) t args sc'
 554 |     resolved gam (DelayCase ty arg sc)
 555 |         = pure $ DelayCase ty arg !(resolved gam sc)
 556 |     resolved gam (ConstCase c sc)
 557 |         = pure $ ConstCase c !(resolved gam sc)
 558 |     resolved gam (DefaultCase sc)
 559 |         = pure $ DefaultCase !(resolved gam sc)
 560 |
 561 | export
 562 | HasNames (Env Term vars) where
 563 |   full gam [] = pure Env.empty
 564 |   full gam (b :: bs)
 565 |       = pure $ !(traverse (full gam) b) :: !(full gam bs)
 566 |
 567 |   resolved gam [] = pure Env.empty
 568 |   resolved gam (b :: bs)
 569 |       = pure $ !(traverse (resolved gam) b) :: !(resolved gam bs)
 570 |
 571 | export
 572 | HasNames Clause where
 573 |   full gam (MkClause env lhs rhs)
 574 |      = pure $ MkClause !(full gam env) !(full gam lhs) !(full gam rhs)
 575 |
 576 |   resolved gam (MkClause env lhs rhs)
 577 |     = [| MkClause (resolved gam env) (resolved gam lhs) (resolved gam rhs) |]
 578 |
 579 |
 580 | export
 581 | HasNames Def where
 582 |   full gam (PMDef r args ct rt pats)
 583 |       = pure $ PMDef r args !(full gam ct) !(full gam rt)
 584 |                      !(traverse fullNamesPat pats)
 585 |     where
 586 |       fullNamesPat : (vs ** (Env Term vs, Term vs, Term vs)) ->
 587 |                      Core (vs ** (Env Term vs, Term vs, Term vs))
 588 |       fullNamesPat (_ ** (env, lhs, rhs))
 589 |           = pure $ (_ ** (!(full gam env),
 590 |                           !(full gam lhs), !(full gam rhs)))
 591 |   full gam (TCon a ps ds u ms mcs det)
 592 |       = pure $ TCon a ps ds u !(traverse (full gam) ms)
 593 |                                 !(traverseOpt (traverse (full gam)) mcs) det
 594 |   full gam (BySearch c d def)
 595 |       = pure $ BySearch c d !(full gam def)
 596 |   full gam (Guess tm b cs)
 597 |       = pure $ Guess !(full gam tm) b cs
 598 |   full gam t = pure t
 599 |
 600 |   resolved gam (PMDef r args ct rt pats)
 601 |       = pure $ PMDef r args !(resolved gam ct) !(resolved gam rt)
 602 |                      !(traverse resolvedNamesPat pats)
 603 |     where
 604 |       resolvedNamesPat : (vs ** (Env Term vs, Term vs, Term vs)) ->
 605 |                          Core (vs ** (Env Term vs, Term vs, Term vs))
 606 |       resolvedNamesPat (_ ** (env, lhs, rhs))
 607 |           = pure $ (_ ** (!(resolved gam env),
 608 |                           !(resolved gam lhs), !(resolved gam rhs)))
 609 |   resolved gam (TCon a ps ds u ms mcs det)
 610 |       = pure $ TCon a ps ds u !(traverse (resolved gam) ms)
 611 |                                 !(traverseOpt (traverse (full gam)) mcs) det
 612 |   resolved gam (BySearch c d def)
 613 |       = pure $ BySearch c d !(resolved gam def)
 614 |   resolved gam (Guess tm b cs)
 615 |       = pure $ Guess !(resolved gam tm) b cs
 616 |   resolved gam t = pure t
 617 |
 618 | export
 619 | StripNamespace Def where
 620 |   trimNS ns (PMDef i args ct rt pats)
 621 |       = PMDef i args (trimNS ns ct) rt (map trimNSpat pats)
 622 |     where
 623 |       trimNSpat : (vs ** (Env Term vs, Term vs, Term vs)) ->
 624 |                   (vs ** (Env Term vs, Term vs, Term vs))
 625 |       trimNSpat (vs ** (env, lhs, rhs))
 626 |           = (vs ** (env, trimNS ns lhs, trimNS ns rhs))
 627 |   trimNS ns d = d
 628 |
 629 |   restoreNS ns (PMDef i args ct rt pats)
 630 |       = PMDef i args (restoreNS ns ct) rt (map restoreNSpat pats)
 631 |     where
 632 |       restoreNSpat : (vs ** (Env Term vs, Term vs, Term vs)) ->
 633 |                   (vs ** (Env Term vs, Term vs, Term vs))
 634 |       restoreNSpat (vs ** (env, lhs, rhs))
 635 |           = (vs ** (env, restoreNS ns lhs, restoreNS ns rhs))
 636 |   restoreNS ns d = d
 637 |
 638 | export
 639 | StripNamespace GlobalDef where
 640 |   trimNS ns def = { definition $= trimNS ns } def
 641 |   restoreNS ns def = { definition $= restoreNS ns } def
 642 |
 643 | HasNames (NameMap a) where
 644 |   full gam nmap
 645 |       = insertAll empty (toList nmap)
 646 |     where
 647 |       insertAll : NameMap a -> List (Name, a) -> Core (NameMap a)
 648 |       insertAll ms [] = pure ms
 649 |       insertAll ms ((k, v) :: ns)
 650 |           = insertAll (insert !(full gam k) v ms) ns
 651 |
 652 |   resolved gam nmap
 653 |       = insertAll empty (toList nmap)
 654 |     where
 655 |       insertAll : NameMap a -> List (Name, a) -> Core (NameMap a)
 656 |       insertAll ms [] = pure ms
 657 |       insertAll ms ((k, v) :: ns)
 658 |           = insertAll (insert !(resolved gam k) v ms) ns
 659 |
 660 | export
 661 | HasNames PartialReason where
 662 |   full gam NotStrictlyPositive = pure NotStrictlyPositive
 663 |   full gam (BadCall ns) = pure $ BadCall !(traverse (full gam) ns)
 664 |   full gam (BadPath init n) = pure $ BadPath !(traverse (traversePair (full gam)) init) !(full gam n)
 665 |   full gam (RecPath loop) = pure $ RecPath !(traverse (traversePair (full gam)) loop)
 666 |
 667 |   resolved gam NotStrictlyPositive = pure NotStrictlyPositive
 668 |   resolved gam (BadCall ns) = pure $ BadCall !(traverse (resolved gam) ns)
 669 |   resolved gam (BadPath init n) = pure $ BadPath !(traverse (traversePair (resolved gam)) init) !(resolved gam n)
 670 |   resolved gam (RecPath loop) = pure $ RecPath !(traverse (traversePair (resolved gam)) loop)
 671 |
 672 | export
 673 | HasNames Terminating where
 674 |   full gam (NotTerminating p) = pure $ NotTerminating !(full gam p)
 675 |   full gam t = pure t
 676 |
 677 |   resolved gam (NotTerminating p) = pure $ NotTerminating !(resolved gam p)
 678 |   resolved gam t = pure t
 679 |
 680 | export
 681 | HasNames Covering where
 682 |   full gam IsCovering = pure IsCovering
 683 |   full gam (MissingCases ts)
 684 |       = pure $ MissingCases !(traverse (full gam) ts)
 685 |   full gam (NonCoveringCall ns)
 686 |       = pure $ NonCoveringCall !(traverse (full gam) ns)
 687 |
 688 |   resolved gam IsCovering = pure IsCovering
 689 |   resolved gam (MissingCases ts)
 690 |       = pure $ MissingCases !(traverse (resolved gam) ts)
 691 |   resolved gam (NonCoveringCall ns)
 692 |       = pure $ NonCoveringCall !(traverse (resolved gam) ns)
 693 |
 694 | export
 695 | HasNames CaseError where
 696 |   full gam DifferingArgNumbers = pure DifferingArgNumbers
 697 |   full gam DifferingTypes = pure DifferingTypes
 698 |   full gam (MatchErased (vs ** (rho, t))) = do
 699 |     rho <- full gam rho
 700 |     t <- full gam t
 701 |     pure (MatchErased (vs ** (rho, t)))
 702 |   full gam (NotFullyApplied n) = NotFullyApplied <$> full gam n
 703 |   full gam UnknownType = pure UnknownType
 704 |
 705 |   resolved gam DifferingArgNumbers = pure DifferingArgNumbers
 706 |   resolved gam DifferingTypes = pure DifferingTypes
 707 |   resolved gam (MatchErased (vs ** (rho, t))) = do
 708 |     rho <- resolved gam rho
 709 |     t <- resolved gam t
 710 |     pure (MatchErased (vs ** (rho, t)))
 711 |   resolved gam (NotFullyApplied n) = NotFullyApplied <$> resolved gam n
 712 |   resolved gam UnknownType = pure UnknownType
 713 |
 714 |
 715 | export
 716 | HasNames Warning where
 717 |   full gam (ParserWarning fc x) = pure (ParserWarning fc x)
 718 |   full gam (UnreachableClause fc rho s) = UnreachableClause fc <$> full gam rho <*> full gam s
 719 |   full gam (ShadowingGlobalDefs fc xs)
 720 |     = ShadowingGlobalDefs fc <$> traverseList1 (traversePair (traverseList1 (full gam))) xs
 721 |   full gam (IncompatibleVisibility fc x y n) = IncompatibleVisibility fc x y <$> full gam n
 722 |   full gam w@(ShadowingLocalBindings {}) = pure w
 723 |   full gam (Deprecated fc x y) = Deprecated fc x <$> traverseOpt (traversePair (full gam)) y
 724 |   full gam (GenericWarn fc x) = pure (GenericWarn fc x)
 725 |
 726 |   resolved gam (ParserWarning fc x) = pure (ParserWarning fc x)
 727 |   resolved gam (UnreachableClause fc rho s) = UnreachableClause fc <$> resolved gam rho <*> resolved gam s
 728 |   resolved gam (ShadowingGlobalDefs fc xs)
 729 |     = ShadowingGlobalDefs fc <$> traverseList1 (traversePair (traverseList1 (resolved gam))) xs
 730 |   resolved gam (IncompatibleVisibility fc x y n) = IncompatibleVisibility fc x y <$> resolved gam n
 731 |   resolved gam w@(ShadowingLocalBindings {}) = pure w
 732 |   resolved gam (Deprecated fc x y) = Deprecated fc x <$> traverseOpt (traversePair (resolved gam)) y
 733 |   resolved gam (GenericWarn fc x) = pure (GenericWarn fc x)
 734 |
 735 | export
 736 | HasNames Error where
 737 |   full gam (Fatal err) = Fatal <$> full gam err
 738 |   full _ (CantConvert fc gam rho s t)
 739 |     = CantConvert fc gam <$> full gam rho <*> full gam s <*> full gam t
 740 |   full _ (CantSolveEq fc gam rho s t)
 741 |     = CantSolveEq fc gam <$> full gam rho <*> full gam s <*> full gam t
 742 |   full gam (PatternVariableUnifies fc fct rho n s)
 743 |     = PatternVariableUnifies fc fct <$> full gam rho <*> full gam n <*> full gam s
 744 |   full gam (CyclicMeta fc rho n s)
 745 |     = CyclicMeta fc <$> full gam rho <*> full gam n <*> full gam s
 746 |   full _ (WhenUnifying fc gam rho s t err)
 747 |     = WhenUnifying fc gam <$> full gam rho <*> full gam s <*> full gam t <*> full gam err
 748 |   full gam (ValidCase fc rho x)
 749 |     = ValidCase fc <$> full gam rho <*> either (map Left . full gam) (map Right . full gam) x
 750 |   full gam (UndefinedName fc n) = UndefinedName fc <$> full gam n
 751 |   full gam (InvisibleName fc n mns) = InvisibleName fc <$> full gam n <*> pure mns
 752 |   full gam (BadTypeConType fc n) = BadTypeConType fc <$> full gam n
 753 |   full gam (BadDataConType fc n n') = BadDataConType fc <$> full gam n <*> full gam n'
 754 |   full gam (NotCovering fc n cov) = NotCovering fc <$> full gam n <*> full gam cov
 755 |   full gam (NotTotal fc n pr) = NotTotal fc <$> full gam n <*> full gam pr
 756 |   full gam ImpossibleCase = pure ImpossibleCase
 757 |   full gam (LinearUsed fc k n) = LinearUsed fc k <$> full gam n
 758 |   full gam (LinearMisuse fc n x y) = LinearMisuse fc <$> full gam n <*> pure x <*> pure y
 759 |   full gam (BorrowPartial fc rho s t) = BorrowPartial fc <$> full gam rho <*> full gam s <*> full gam t
 760 |   full gam (BorrowPartialType fc rho s) = BorrowPartialType fc <$> full gam rho <*> full gam s
 761 |   full gam (AmbiguousName fc xs) = AmbiguousName fc <$> traverse (full gam) xs
 762 |   full gam (AmbiguousElab fc rho xs)
 763 |     = AmbiguousElab fc <$> full gam rho <*> traverse (\ (gam, t) => (gam,) <$> full gam t) xs
 764 |   full gam (AmbiguousSearch fc rho s xs)
 765 |     = AmbiguousSearch fc <$> full gam rho <*> full gam s <*> traverse (full gam) xs
 766 |   full gam (AmbiguityTooDeep fc n xs) = AmbiguityTooDeep fc <$> full gam n <*> traverse (full gam) xs
 767 |   full gam (AllFailed xs)
 768 |      = map AllFailed $ for xs $ \ (mn, err) =>
 769 |          (,) <$> traverseOpt (full gam) mn <*> full gam err
 770 |   full gam (RecordTypeNeeded fc rho) = RecordTypeNeeded fc <$> full gam rho
 771 |   full gam (DuplicatedRecordUpdatePath fc xs) = pure (DuplicatedRecordUpdatePath fc xs)
 772 |   full gam (NotRecordField fc x mn) = NotRecordField fc x <$> traverseOpt (full gam) mn
 773 |   full gam (NotRecordType fc n) = NotRecordType fc <$> full gam n
 774 |   full gam (IncompatibleFieldUpdate fc xs) = pure (IncompatibleFieldUpdate fc xs)
 775 |   full gam (InvalidArgs fc rho xs s) = InvalidArgs fc <$> full gam rho <*> traverse (full gam) xs <*> full gam s
 776 |   full gam (TryWithImplicits fc rho xs)
 777 |     = TryWithImplicits fc <$> full gam rho
 778 |        <*> for xs (\ (n, t) => (,) <$> full gam n <*> full gam t)
 779 |   full gam (BadUnboundImplicit fc rho n s) = BadUnboundImplicit fc <$> full gam rho <*> full gam n <*> full gam s
 780 |   full _ (CantSolveGoal fc gam rho s merr)
 781 |     = CantSolveGoal fc gam <$> full gam rho <*> full gam s <*> traverseOpt (full gam) merr
 782 |   full gam (DeterminingArg fc n x rho s)
 783 |     = DeterminingArg fc <$> full gam n <*> pure x <*> full gam rho <*> full gam s
 784 |   full gam (UnsolvedHoles xs) = UnsolvedHoles <$> traverse (traversePair (full gam)) xs
 785 |   full gam (CantInferArgType fc rho n n1 s)
 786 |     = CantInferArgType fc <$> full gam rho <*> full gam n <*> full gam n1 <*> full gam s
 787 |   full gam (SolvedNamedHole fc rho n s) = SolvedNamedHole fc <$> full gam rho <*> full gam n <*> full gam s
 788 |   full gam (VisibilityError fc x n y n1) = VisibilityError fc x <$> full gam n <*> pure y <*> full gam n1
 789 |   full gam (NonLinearPattern fc n) = NonLinearPattern fc <$> full gam  n
 790 |   full gam (BadPattern fc n) = BadPattern fc <$> full gam n
 791 |   full gam (NoDeclaration fc n) = NoDeclaration fc <$> full gam n
 792 |   full gam (AlreadyDefined fc n) = AlreadyDefined fc <$> full gam n
 793 |   full gam (NotFunctionType fc rho s) = NotFunctionType fc <$> full gam rho <*> full gam s
 794 |   full gam (RewriteNoChange fc rho s t) = RewriteNoChange fc <$> full gam rho <*> full gam s <*> full gam t
 795 |   full gam (NotRewriteRule fc rho s) = NotRewriteRule fc <$> full gam rho <*> full gam s
 796 |   full gam (CaseCompile fc n x) = CaseCompile fc <$> full gam n <*> full gam x
 797 |   full gam (MatchTooSpecific fc rho s) = MatchTooSpecific fc <$> full gam rho <*> full gam s
 798 |   full gam (BadDotPattern fc rho x s t)
 799 |     = BadDotPattern fc <$> full gam rho <*> pure x <*> full gam s <*> full gam t
 800 |   full gam (BadImplicit fc x) = pure (BadImplicit fc x)
 801 |   full gam (BadRunElab fc rho s desc) = BadRunElab fc <$> full gam rho <*> full gam s <*> pure desc
 802 |   full gam (RunElabFail e) = RunElabFail <$> full gam e
 803 |   full gam (GenericMsg fc x) = pure (GenericMsg fc x)
 804 |   full gam (GenericMsgSol fc x y z) = pure (GenericMsgSol fc x y z)
 805 |   full gam (TTCError x) = pure (TTCError x)
 806 |   full gam (FileErr x y) = pure (FileErr x y)
 807 |   full gam (CantFindPackage x) = pure (CantFindPackage x)
 808 |   full gam (LazyImplicitFunction fc) = pure (LazyImplicitFunction fc)
 809 |   full gam (LazyPatternVar fc) = pure (LazyPatternVar fc)
 810 |   full gam (LitFail fc) = pure (LitFail fc)
 811 |   full gam (LexFail fc x) = pure (LexFail fc x)
 812 |   full gam (ParseFail xs) = pure (ParseFail xs)
 813 |   full gam (ModuleNotFound fc x) = pure (ModuleNotFound fc x)
 814 |   full gam (CyclicImports xs) = pure (CyclicImports xs)
 815 |   full gam ForceNeeded = pure ForceNeeded
 816 |   full gam (InternalError x) = pure (InternalError x)
 817 |   full gam (UserError x) = pure (UserError x)
 818 |   full gam (NoForeignCC fc xs) = pure (NoForeignCC fc xs)
 819 |   full gam (BadMultiline fc x) = pure (BadMultiline fc x)
 820 |   full gam (Timeout x) = pure (Timeout x)
 821 |   full gam (FailingDidNotFail fc) = pure (FailingDidNotFail fc)
 822 |   full gam (FailingWrongError fc x err) = FailingWrongError fc x <$> traverseList1 (full gam) err
 823 |   full gam (InType fc n err) = InType fc <$> full gam n <*> full gam err
 824 |   full gam (InCon n err) = InCon <$> traverse (full gam) n <*> full gam err
 825 |   full gam (InLHS fc n err) = InLHS fc <$> full gam n <*> full gam err
 826 |   full gam (InRHS fc n err) = InRHS fc <$> full gam n <*> full gam err
 827 |   full gam (MaybeMisspelling err xs) = MaybeMisspelling <$> full gam err <*> pure xs
 828 |   full gam (WarningAsError wrn) = WarningAsError <$> full gam wrn
 829 |   full gam (OperatorBindingMismatch {print} fc expected actual (Left opName) rhs candidates)
 830 |       = OperatorBindingMismatch {print} fc expected actual
 831 |           <$> (Left <$> full gam opName) <*> pure rhs <*> pure candidates
 832 |   full gam (OperatorBindingMismatch {print} fc expected actual (Right opName) rhs candidates)
 833 |       = OperatorBindingMismatch {print} fc expected actual
 834 |           <$> (Right <$> full gam opName) <*> pure rhs <*> pure candidates
 835 |
 836 |   resolved gam (Fatal err) = Fatal <$> resolved gam err
 837 |   resolved _ (CantConvert fc gam rho s t)
 838 |     = CantConvert fc gam <$> resolved gam rho <*> resolved gam s <*> resolved gam t
 839 |   resolved _ (CantSolveEq fc gam rho s t)
 840 |     = CantSolveEq fc gam <$> resolved gam rho <*> resolved gam s <*> resolved gam t
 841 |   resolved gam (PatternVariableUnifies fc fct rho n s)
 842 |     = PatternVariableUnifies fc fct <$> resolved gam rho <*> resolved gam n <*> resolved gam s
 843 |   resolved gam (CyclicMeta fc rho n s)
 844 |     = CyclicMeta fc <$> resolved gam rho <*> resolved gam n <*> resolved gam s
 845 |   resolved _ (WhenUnifying fc gam rho s t err)
 846 |     = WhenUnifying fc gam <$> resolved gam rho <*> resolved gam s <*> resolved gam t <*> resolved gam err
 847 |   resolved gam (ValidCase fc rho x)
 848 |     = ValidCase fc <$> resolved gam rho <*> either (map Left . resolved gam) (map Right . resolved gam) x
 849 |   resolved gam (UndefinedName fc n) = UndefinedName fc <$> resolved gam n
 850 |   resolved gam (InvisibleName fc n mns) = InvisibleName fc <$> resolved gam n <*> pure mns
 851 |   resolved gam (BadTypeConType fc n) = BadTypeConType fc <$> resolved gam n
 852 |   resolved gam (BadDataConType fc n n') = BadDataConType fc <$> resolved gam n <*> resolved gam n'
 853 |   resolved gam (NotCovering fc n cov) = NotCovering fc <$> resolved gam n <*> resolved gam cov
 854 |   resolved gam (NotTotal fc n pr) = NotTotal fc <$> resolved gam n <*> resolved gam pr
 855 |   resolved gam ImpossibleCase = pure ImpossibleCase
 856 |   resolved gam (LinearUsed fc k n) = LinearUsed fc k <$> resolved gam n
 857 |   resolved gam (LinearMisuse fc n x y) = LinearMisuse fc <$> resolved gam n <*> pure x <*> pure y
 858 |   resolved gam (BorrowPartial fc rho s t) = BorrowPartial fc <$> resolved gam rho <*> resolved gam s <*> resolved gam t
 859 |   resolved gam (BorrowPartialType fc rho s) = BorrowPartialType fc <$> resolved gam rho <*> resolved gam s
 860 |   resolved gam (AmbiguousName fc xs) = AmbiguousName fc <$> traverse (resolved gam) xs
 861 |   resolved gam (AmbiguousElab fc rho xs)
 862 |     = AmbiguousElab fc <$> resolved gam rho <*> traverse (\ (gam, t) => (gam,) <$> resolved gam t) xs
 863 |   resolved gam (AmbiguousSearch fc rho s xs)
 864 |     = AmbiguousSearch fc <$> resolved gam rho <*> resolved gam s <*> traverse (resolved gam) xs
 865 |   resolved gam (AmbiguityTooDeep fc n xs) = AmbiguityTooDeep fc <$> resolved gam n <*> traverse (resolved gam) xs
 866 |   resolved gam (AllFailed xs)
 867 |      = map AllFailed $ for xs $ \ (mn, err) =>
 868 |          (,) <$> traverseOpt (resolved gam) mn <*> resolved gam err
 869 |   resolved gam (RecordTypeNeeded fc rho) = RecordTypeNeeded fc <$> resolved gam rho
 870 |   resolved gam (DuplicatedRecordUpdatePath fc xs) = pure (DuplicatedRecordUpdatePath fc xs)
 871 |   resolved gam (NotRecordField fc x mn) = NotRecordField fc x <$> traverseOpt (resolved gam) mn
 872 |   resolved gam (NotRecordType fc n) = NotRecordType fc <$> resolved gam n
 873 |   resolved gam (IncompatibleFieldUpdate fc xs) = pure (IncompatibleFieldUpdate fc xs)
 874 |   resolved gam (InvalidArgs fc rho xs s) = InvalidArgs fc <$> resolved gam rho <*> traverse (resolved gam) xs <*> resolved gam s
 875 |   resolved gam (TryWithImplicits fc rho xs)
 876 |     = TryWithImplicits fc <$> resolved gam rho
 877 |        <*> for xs (\ (n, t) => (,) <$> resolved gam n <*> resolved gam t)
 878 |   resolved gam (BadUnboundImplicit fc rho n s) = BadUnboundImplicit fc <$> resolved gam rho <*> resolved gam n <*> resolved gam s
 879 |   resolved _ (CantSolveGoal fc gam rho s merr)
 880 |     = CantSolveGoal fc gam <$> resolved gam rho <*> resolved gam s <*> traverseOpt (resolved gam) merr
 881 |   resolved gam (DeterminingArg fc n x rho s)
 882 |     = DeterminingArg fc <$> resolved gam n <*> pure x <*> resolved gam rho <*> resolved gam s
 883 |   resolved gam (UnsolvedHoles xs) = UnsolvedHoles <$> traverse (traversePair (resolved gam)) xs
 884 |   resolved gam (CantInferArgType fc rho n n1 s)
 885 |     = CantInferArgType fc <$> resolved gam rho <*> resolved gam n <*> resolved gam n1 <*> resolved gam s
 886 |   resolved gam (SolvedNamedHole fc rho n s) = SolvedNamedHole fc <$> resolved gam rho <*> resolved gam n <*> resolved gam s
 887 |   resolved gam (VisibilityError fc x n y n1) = VisibilityError fc x <$> resolved gam n <*> pure y <*> resolved gam n1
 888 |   resolved gam (NonLinearPattern fc n) = NonLinearPattern fc <$> resolved gam  n
 889 |   resolved gam (BadPattern fc n) = BadPattern fc <$> resolved gam n
 890 |   resolved gam (NoDeclaration fc n) = NoDeclaration fc <$> resolved gam n
 891 |   resolved gam (AlreadyDefined fc n) = AlreadyDefined fc <$> resolved gam n
 892 |   resolved gam (NotFunctionType fc rho s) = NotFunctionType fc <$> resolved gam rho <*> resolved gam s
 893 |   resolved gam (RewriteNoChange fc rho s t) = RewriteNoChange fc <$> resolved gam rho <*> resolved gam s <*> resolved gam t
 894 |   resolved gam (NotRewriteRule fc rho s) = NotRewriteRule fc <$> resolved gam rho <*> resolved gam s
 895 |   resolved gam (CaseCompile fc n x) = CaseCompile fc <$> resolved gam n <*> resolved gam x
 896 |   resolved gam (MatchTooSpecific fc rho s) = MatchTooSpecific fc <$> resolved gam rho <*> resolved gam s
 897 |   resolved gam (BadDotPattern fc rho x s t)
 898 |     = BadDotPattern fc <$> resolved gam rho <*> pure x <*> resolved gam s <*> resolved gam t
 899 |   resolved gam (BadImplicit fc x) = pure (BadImplicit fc x)
 900 |   resolved gam (BadRunElab fc rho s desc) = BadRunElab fc <$> resolved gam rho <*> resolved gam s <*> pure desc
 901 |   resolved gam (RunElabFail e) = RunElabFail <$> resolved gam e
 902 |   resolved gam (GenericMsg fc x) = pure (GenericMsg fc x)
 903 |   resolved gam (GenericMsgSol fc x y z) = pure (GenericMsgSol fc x y z)
 904 |   resolved gam (TTCError x) = pure (TTCError x)
 905 |   resolved gam (FileErr x y) = pure (FileErr x y)
 906 |   resolved gam (CantFindPackage x) = pure (CantFindPackage x)
 907 |   resolved gam (LazyImplicitFunction fc) = pure (LazyImplicitFunction fc)
 908 |   resolved gam (LazyPatternVar fc) = pure (LazyPatternVar fc)
 909 |   resolved gam (LitFail fc) = pure (LitFail fc)
 910 |   resolved gam (LexFail fc x) = pure (LexFail fc x)
 911 |   resolved gam (ParseFail xs) = pure (ParseFail xs)
 912 |   resolved gam (ModuleNotFound fc x) = pure (ModuleNotFound fc x)
 913 |   resolved gam (CyclicImports xs) = pure (CyclicImports xs)
 914 |   resolved gam ForceNeeded = pure ForceNeeded
 915 |   resolved gam (InternalError x) = pure (InternalError x)
 916 |   resolved gam (UserError x) = pure (UserError x)
 917 |   resolved gam (NoForeignCC fc xs) = pure (NoForeignCC fc xs)
 918 |   resolved gam (BadMultiline fc x) = pure (BadMultiline fc x)
 919 |   resolved gam (Timeout x) = pure (Timeout x)
 920 |   resolved gam (FailingDidNotFail fc) = pure (FailingDidNotFail fc)
 921 |   resolved gam (FailingWrongError fc x err) = FailingWrongError fc x <$> traverseList1 (resolved gam) err
 922 |   resolved gam (InType fc n err) = InType fc <$> resolved gam n <*> resolved gam err
 923 |   resolved gam (InCon n err) = InCon <$> traverse (resolved gam) n <*> resolved gam err
 924 |   resolved gam (InLHS fc n err) = InLHS fc <$> resolved gam n <*> resolved gam err
 925 |   resolved gam (InRHS fc n err) = InRHS fc <$> resolved gam n <*> resolved gam err
 926 |   resolved gam (MaybeMisspelling err xs) = MaybeMisspelling <$> resolved gam err <*> pure xs
 927 |   resolved gam (WarningAsError wrn) = WarningAsError <$> resolved gam wrn
 928 |   resolved gam (OperatorBindingMismatch {print} fc expected actual (Left opName) rhs candidates)
 929 |       = OperatorBindingMismatch {print} fc expected actual
 930 |           <$> (Left <$> resolved gam opName) <*> pure rhs <*> pure candidates
 931 |   resolved gam (OperatorBindingMismatch {print} fc expected actual (Right opName) rhs candidates)
 932 |       = OperatorBindingMismatch {print} fc expected actual
 933 |           <$> (Right <$> resolved gam opName) <*> pure rhs <*> pure candidates
 934 |
 935 | export
 936 | HasNames Totality where
 937 |   full gam (MkTotality t c) = pure $ MkTotality !(full gam t) !(full gam c)
 938 |   resolved gam (MkTotality t c) = pure $ MkTotality !(resolved gam t) !(resolved gam c)
 939 |
 940 | export
 941 | HasNames SCCall where
 942 |   full gam sc = pure $ { fnCall := !(full gam (fnCall sc)) } sc
 943 |   resolved gam sc = pure $ { fnCall := !(resolved gam (fnCall sc)) } sc
 944 |
 945 | export
 946 | HasNames a => HasNames (Maybe a) where
 947 |   full gam Nothing = pure Nothing
 948 |   full gam (Just x) = pure $ Just !(full gam x)
 949 |   resolved gam Nothing = pure Nothing
 950 |   resolved gam (Just x) = pure $ Just !(resolved gam x)
 951 |
 952 | export
 953 | HasNames GlobalDef where
 954 |   full gam def
 955 |       = do
 956 | --            ts <- full gam (type def)
 957 | --            d <- full gam (definition def)
 958 | --            coreLift $ printLn (fullname def, ts)
 959 | --            coreLift $ printLn (fullname def, d)
 960 |            pure $ { type := !(full gam (type def)),
 961 |                     definition := !(full gam (definition def)),
 962 |                     totality := !(full gam (totality def)),
 963 |                     refersToM := !(full gam (refersToM def)),
 964 |                     refersToRuntimeM := !(full gam (refersToRuntimeM def)),
 965 |                     sizeChange := !(traverse (full gam) (sizeChange def))
 966 |                   } def
 967 |   resolved gam def
 968 |       = pure $ { type := !(resolved gam (type def)),
 969 |                  definition := !(resolved gam (definition def)),
 970 |                  totality := !(resolved gam (totality def)),
 971 |                  refersToM := !(resolved gam (refersToM def)),
 972 |                  refersToRuntimeM := !(resolved gam (refersToRuntimeM def)),
 973 |                  sizeChange := !(traverse (resolved gam) (sizeChange def))
 974 |                } def
 975 |
 976 | export
 977 | HasNames Transform where
 978 |   full gam (MkTransform n env lhs rhs)
 979 |       = pure $ MkTransform !(full gam n) !(full gam env)
 980 |                            !(full gam lhs) !(full gam rhs)
 981 |
 982 |   resolved gam (MkTransform n env lhs rhs)
 983 |       = pure $ MkTransform !(resolved gam n) !(resolved gam env)
 984 |                            !(resolved gam lhs) !(resolved gam rhs)
 985 |
 986 | -- Return all the currently defined names
 987 | export
 988 | allNames : Context -> Core (List Name)
 989 | allNames ctxt = traverse (full ctxt) $ map Resolved [1..nextEntry ctxt - 1]
 990 |
 991 | public export
 992 | record Defs where
 993 |   constructor MkDefs
 994 |   gamma : Context
 995 |   mutData : List Name -- Currently declared but undefined data types
 996 |   currentNS : Namespace -- namespace for current definitions
 997 |   nestedNS : List Namespace -- other nested namespaces we can look in
 998 |   options : Options
 999 |   toSave : NameMap ()
1000 |   typeHints : NameMap (List (Name, Bool))
1001 |      -- ^ a mapping from type names to hints (and a flag setting whether it's
1002 |      -- a "direct" hint). Direct hints are searched first (as part of a group)
1003 |      -- the indirect hints. Indirect hints, in practice, are used to find
1004 |      -- instances of parent interfaces, and we don't search these until we've
1005 |      -- tried to find a direct result via a constructor or a top level hint.
1006 |   autoHints : NameMap Bool
1007 |      -- ^ global search hints. A mapping from the hint name, to whether it is
1008 |      -- a "default hint". A default hint is used only if all other attempts
1009 |      -- to search fail (this flag is really only intended as a mechanism
1010 |      -- for defaulting of literals)
1011 |   openHints : NameMap ()
1012 |      -- ^ currently open global hints; just for the rest of this module (not exported)
1013 |      -- and prioritised
1014 |   localHints : NameMap ()
1015 |      -- ^ Hints defined in the current environment
1016 |   saveTypeHints : List (Name, Name, Bool)
1017 |      -- We don't look up anything in here, it's merely for saving out to TTC.
1018 |      -- We save the hints in the 'GlobalDef' itself for faster lookup.
1019 |   saveAutoHints : List (Name, Bool)
1020 |   transforms : NameMap (List Transform)
1021 |      -- ^ A mapping from names to transformation rules which update applications
1022 |      -- of that name
1023 |   saveTransforms : List (Name, Transform)
1024 |   pendingTransforms : List (Name, Transform)
1025 |      -- ^ rules read from TTCs, not yet resolved and not yet in 'transforms'
1026 |      -- (resolveTransforms)
1027 |   namedirectives : NameMap (List String)
1028 |   ifaceHash : Int
1029 |   importHashes : List (Namespace, Int)
1030 |      -- ^ interface hashes of imported modules
1031 |   imported : List (ModuleIdent, Bool, Namespace)
1032 |      -- ^ imported modules, whether to rexport, as namespace
1033 |   allImported : List (String, (ModuleIdent, Bool, Namespace))
1034 |      -- ^ all imported filenames/namespaces, just to avoid loading something
1035 |      -- twice unnecessarily (this is a record of all the things we've
1036 |      -- called 'readFromTTC' with, in practice)
1037 |   cgdirectives : SortedSet (CG, String)
1038 |      -- ^ Code generator directives, which are free form text and thus to
1039 |      -- be interpreted however the specific code generator requires
1040 |   toCompileCase : List Name
1041 |      -- ^ Names which need to be compiled to run time case trees
1042 |   incData : List (CG, String, List String)
1043 |      -- ^ What we've compiled incrementally for this module: codegen,
1044 |      -- object file, any additional CG dependent data (e.g. linker flags)
1045 |   allIncData : List (CG, List String, List String)
1046 |      -- ^ Incrementally compiled files for all imports. Only lists CGs for
1047 |      -- while all modules have associated incremental compile data
1048 |   toIR : NameMap ()
1049 |      -- ^ Names which need to be compiled to IR at the end of processing
1050 |      -- the current module
1051 |   userHoles : NameMap Bool
1052 |      -- ^ Metavariables the user still has to fill in. In practice, that's
1053 |      -- everything with a user accessible name and a definition of Hole.
1054 |      -- The Bool says whether it was introduced in another module.
1055 |   peFailures : NameMap ()
1056 |      -- ^ Partial evaluation names which have failed, so don't bother trying
1057 |      -- again
1058 |   timings : StringMap (Bool, Integer)
1059 |      -- ^ record of timings from logTimeRecord
1060 |   timer : Maybe (Integer, String)
1061 |      -- ^ for timing and checking timeouts; the maximum time after which a
1062 |      -- timeout should be thrown
1063 |   warnings : List Warning
1064 |      -- ^ as yet unreported warnings
1065 |   schemeEvalLoaded : Bool
1066 |   foreignExports : NameMap (List (String, String))
1067 |        -- ^ For functions which are callable from a foreign language. This
1068 |        -- maps names to a pair of the back end and the exported function name
1069 |   defsStack : SnocList Name -- stack of the definition names being processed
1070 |
1071 | -- Label for context references
1072 | export
1073 | data Ctxt : Type where
1074 |
1075 |
1076 | export
1077 | clearDefs : Defs -> Core Defs
1078 | clearDefs defs
1079 |     = pure ({ gamma->inlineOnly := True } defs)
1080 |
1081 | export
1082 | initDefs : Core Defs
1083 | initDefs
1084 |     = do gam <- initCtxt
1085 |          opts <- defaults
1086 |          pure $ MkDefs
1087 |            { gamma = gam
1088 |            , mutData = []
1089 |            , currentNS = mainNS
1090 |            , nestedNS = []
1091 |            , options = opts
1092 |            , toSave = empty
1093 |            , typeHints = empty
1094 |            , autoHints = empty
1095 |            , openHints = empty
1096 |            , localHints = empty
1097 |            , saveTypeHints = []
1098 |            , saveAutoHints = []
1099 |            , transforms = empty
1100 |            , saveTransforms = []
1101 |            , pendingTransforms = []
1102 |            , namedirectives = empty
1103 |            , ifaceHash = 5381
1104 |            , importHashes = []
1105 |            , imported = []
1106 |            , allImported = []
1107 |            , cgdirectives = SortedSet.empty
1108 |            , toCompileCase = []
1109 |            , incData = []
1110 |            , allIncData = []
1111 |            , toIR = empty
1112 |            , userHoles = empty
1113 |            , peFailures = empty
1114 |            , timings = empty
1115 |            , timer = Nothing
1116 |            , warnings = []
1117 |            , schemeEvalLoaded = False
1118 |            , foreignExports = empty
1119 |            , defsStack = [<]
1120 |            }
1121 |
1122 | -- Reset the context, except for the options
1123 | export
1124 | clearCtxt : {auto c : Ref Ctxt Defs} ->
1125 |             Core ()
1126 | clearCtxt
1127 |     = do defs <- get Ctxt
1128 |          put Ctxt ({ options := resetElab (options defs),
1129 |                      timings := timings defs } !initDefs)
1130 |   where
1131 |     resetElab : Options -> Options
1132 |     resetElab opts =
1133 |       let tot = totalReq (session opts) in
1134 |       { elabDirectives := { totality := tot } defaultElab } opts
1135 |
1136 | export
1137 | getFieldNames : Context -> Namespace -> List Name
1138 | getFieldNames ctxt recNS
1139 |   = let nms = resolvedAs ctxt in
1140 |     keys $ flip filterBy nms $ \ n =>
1141 |       case isRF n of
1142 |         Nothing => False
1143 |         Just (ns, field) => ns == recNS
1144 |
1145 | -- Find similar looking names in the context
1146 | export
1147 | getSimilarNames : {auto c : Ref Ctxt Defs} ->
1148 |                   -- Predicate run to customise the behavior of looking for similar names
1149 |                   -- Sometime we might want to hide names that we know make no sense.
1150 |                   {default Nothing keepPredicate : Maybe ((Name, GlobalDef) -> Core Bool)} ->
1151 |                   Name -> Core (Maybe (String, List (Name, Visibility, Nat)))
1152 | getSimilarNames nm = case show <$> userNameRoot nm of
1153 |   Nothing => pure Nothing
1154 |   Just str => if length str <= 1 then pure (Just (str, [])) else
1155 |     do defs <- get Ctxt
1156 |        let threshold : Nat := max 1 (assert_total (divNat (length str) 3))
1157 |        let test : Name -> Core (Maybe (Visibility, Nat)) := \ nm => do
1158 |                let (Just str') = show <$> userNameRoot nm
1159 |                    | _ => pure Nothing
1160 |                dist <- coreLift $ Levenshtein.compute str str'
1161 |                let True = dist <= threshold
1162 |                    | False => pure Nothing
1163 |                Just def <- lookupCtxtExact nm (gamma defs)
1164 |                    | Nothing => pure Nothing -- should be impossible
1165 |                let predicate = fromMaybe (\_ => pure True) keepPredicate
1166 |                True <- predicate (nm, def)
1167 |                    | False => pure Nothing
1168 |                pure (Just (collapseDefault $ visibility def, dist))
1169 |        kept <- NameMap.mapMaybeM @{CORE} test (resolvedAs (gamma defs))
1170 |        pure $ Just (str, toList kept)
1171 |
1172 | export
1173 | showSimilarNames : Namespace -> Name -> String ->
1174 |                    List (Name, Visibility, Nat) -> List String
1175 | showSimilarNames ns nm str kept
1176 |   = let (loc, priv) := partitionEithers $ kept <&> \ (nm', vis, n) =>
1177 |                          let False = fst (splitNS nm') `isParentOf` ns
1178 |                                | _ => Left (nm', n)
1179 |                              Private = vis
1180 |                                | _ => Left (nm', n)
1181 |                          in Right (nm', n)
1182 |         sorted      := sortBy (compare `on` snd)
1183 |         roots1      := mapMaybe (showNames nm str False . fst) (sorted loc)
1184 |         roots2      := mapMaybe (showNames nm str True  . fst) (sorted priv)
1185 |     in nub roots1 ++ nub roots2
1186 |
1187 |   where
1188 |
1189 |   showNames : Name -> String -> Bool -> Name -> Maybe String
1190 |   showNames target str priv nm = do
1191 |     let adj  = if priv then " (not exported)" else ""
1192 |     let root = nameRoot nm
1193 |     let True = str == root
1194 |       | _ => pure (root ++ adj)
1195 |     let full = show (pretty nm)
1196 |     let True = (str == full || show target == full) && not priv
1197 |       | _ => pure (full ++ adj)
1198 |     Nothing
1199 |
1200 |
1201 | getVisibility : {auto c : Ref Ctxt Defs} ->
1202 |                 FC -> Name -> Core (WithDefault Visibility Private)
1203 | getVisibility fc n
1204 |     = do defs <- get Ctxt
1205 |          Just def <- lookupCtxtExact n (gamma defs)
1206 |               | Nothing => throw (UndefinedName fc n)
1207 |          pure $ visibility def
1208 |
1209 | maybeMisspelling : {auto c : Ref Ctxt Defs} ->
1210 |                    Error -> Name -> Core a
1211 | maybeMisspelling err nm = do
1212 |   ns <- currentNS <$> get Ctxt
1213 |   Just (str, kept) <- getSimilarNames nm
1214 |     | Nothing => throw err
1215 |   let candidates = showSimilarNames ns nm str kept
1216 |   case candidates of
1217 |     [] => throw err
1218 |     (x::xs) => throw (MaybeMisspelling err (x ::: xs))
1219 |
1220 | -- Throw an UndefinedName exception. But try to find similar names first.
1221 | export
1222 | undefinedName : {auto c : Ref Ctxt Defs} ->
1223 |                 FC -> Name -> Core a
1224 | undefinedName loc nm = maybeMisspelling (UndefinedName loc nm) nm
1225 |
1226 | -- Throw a NoDeclaration exception. But try to find similar names first.
1227 | export
1228 | noDeclaration : {auto c : Ref Ctxt Defs} ->
1229 |                 FC -> Name -> Core a
1230 | noDeclaration loc nm = maybeMisspelling (NoDeclaration loc nm) nm
1231 |
1232 | export
1233 | ambiguousName : {auto c : Ref Ctxt Defs} -> FC
1234 |              -> Name -> List Name
1235 |              -> Core a
1236 | ambiguousName fc n ns = do
1237 |   ns <- filterM (\x => pure $ !(collapseDefault <$> getVisibility fc x) /= Private) ns
1238 |   case ns of
1239 |     [] =>         undefinedName fc n
1240 |     ns => throw $ AmbiguousName fc ns
1241 |
1242 | -- Get the canonical name of something that might have been aliased via
1243 | -- import as
1244 | export
1245 | canonicalName : {auto c : Ref Ctxt Defs} ->
1246 |                 FC -> Name -> Core Name
1247 | canonicalName fc n
1248 |     = do defs <- get Ctxt
1249 |          case !(lookupCtxtName n (gamma defs)) of
1250 |               [(n, _, _)] => pure n
1251 |               ns => ambiguousName fc n (map fst ns)
1252 |
1253 | -- If the name is aliased, get the alias
1254 | export
1255 | aliasName : {auto c : Ref Ctxt Defs} ->
1256 |             Name -> Core Name
1257 | aliasName fulln
1258 |     = do defs <- get Ctxt
1259 |          let Just r = userNameRoot fulln
1260 |                 | Nothing => pure fulln
1261 |          let Just ps = lookup r (possibles (gamma defs))
1262 |                 | Nothing => pure fulln
1263 |          findAlias ps
1264 |   where
1265 |     findAlias : List PossibleName -> Core Name
1266 |     findAlias [] = pure fulln
1267 |     findAlias (Alias as full i :: ps)
1268 |         = if full == fulln
1269 |              then pure as
1270 |              else findAlias ps
1271 |     findAlias (_ :: ps) = findAlias ps
1272 |
1273 | -- Beware: if your hashable thing contains (potentially resolved) names,
1274 | -- it'll be better to use addHashWithNames to make the hash independent
1275 | -- of the internal numbering of names.
1276 | export
1277 | addHash : {auto c : Ref Ctxt Defs} -> Hashable a => a -> Core ()
1278 | addHash x = update Ctxt { ifaceHash $= flip hashWithSalt x }
1279 |
1280 | export
1281 | initHash : {auto c : Ref Ctxt Defs} -> Core ()
1282 | initHash = update Ctxt { ifaceHash := 5381 }
1283 |
1284 | export
1285 | addUserHole : {auto c : Ref Ctxt Defs} ->
1286 |               Bool -> -- defined in another module?
1287 |               Name -> -- hole name
1288 |               Core ()
1289 | addUserHole ext n = update Ctxt { userHoles $= insert n ext }
1290 |
1291 | export
1292 | clearUserHole : {auto c : Ref Ctxt Defs} -> Name -> Core ()
1293 | clearUserHole n = update Ctxt { userHoles $= delete n }
1294 |
1295 | export
1296 | getUserHoles : {auto c : Ref Ctxt Defs} ->
1297 |                Core (List Name)
1298 | getUserHoles
1299 |     = do defs <- get Ctxt
1300 |          let hs = sort (keys (userHoles defs))
1301 |          filterM (isHole defs) hs
1302 |   where
1303 |     -- If a hole is declared in one file and defined in another, its
1304 |     -- name won't have been cleared unless we've already looked up its
1305 |     -- definition (as addDef needs to be called to clear it). So here
1306 |     -- check that it's really a hole
1307 |     isHole : Defs -> Name -> Core Bool
1308 |     isHole defs n
1309 |         = do Just def <- lookupCtxtExact n (gamma defs)
1310 |                   | Nothing => pure True
1311 |              pure $ case definition def of
1312 |                   None => True
1313 |                   Hole {} => True
1314 |                   _ => False
1315 |
1316 | export
1317 | addDef : {auto c : Ref Ctxt Defs} ->
1318 |          Name -> GlobalDef -> Core Int
1319 | addDef n def
1320 |     = do defs <- get Ctxt
1321 |          (idx, gam') <- addCtxt n def (gamma defs)
1322 |          put Ctxt ({ gamma := gam' } defs)
1323 |          case definition def of
1324 |               None => pure ()
1325 |               Hole {} => pure ()
1326 |               _ => clearUserHole (fullname def)
1327 |          pure idx
1328 |
1329 | export
1330 | addContextEntry : {auto c : Ref Ctxt Defs} ->
1331 |                   Namespace -> Name -> Binary -> Core Int
1332 | addContextEntry ns n def
1333 |     = do defs <- get Ctxt
1334 |          (idx, gam') <- addEntry n (Coded ns def) (gamma defs)
1335 |          put Ctxt ({ gamma := gam' } defs)
1336 |          pure idx
1337 |
1338 | export
1339 | addContextAlias : {auto c : Ref Ctxt Defs} ->
1340 |                   Name -> Name -> Core ()
1341 | addContextAlias alias full
1342 |     = do defs <- get Ctxt
1343 |          Nothing <- lookupCtxtExact alias (gamma defs)
1344 |              | _ => pure () -- Don't add the alias if the name exists already
1345 |          gam' <- newAlias alias full (gamma defs)
1346 |          put Ctxt ({ gamma := gam' } defs)
1347 |
1348 | export
1349 | addBuiltin : {arity : _} ->
1350 |              {auto x : Ref Ctxt Defs} ->
1351 |              Name -> ClosedTerm -> Totality ->
1352 |              PrimFn arity -> Core ()
1353 | addBuiltin n ty tot op
1354 |    = do ignore $
1355 |        addDef n $ MkGlobalDef
1356 |          { location = emptyFC
1357 |          , fullname = n
1358 |          , type = ty
1359 |          , eraseArgs = NatSet.empty
1360 |          , safeErase = NatSet.empty
1361 |          , specArgs = NatSet.empty
1362 |          , inferrable = NatSet.empty
1363 |          , multiplicity = top
1364 |          , localVars = Scope.empty
1365 |          , visibility = specified Public
1366 |          , totality = tot
1367 |          , isEscapeHatch = False
1368 |          , flags = [Inline]
1369 |          , refersToM = Nothing
1370 |          , refersToRuntimeM = Nothing
1371 |          , invertible = False
1372 |          , noCycles = False
1373 |          , linearChecked = True
1374 |          , definition = Builtin op
1375 |          , compexpr = Nothing
1376 |          , namedcompexpr = Nothing
1377 |          , sizeChange = []
1378 |          , schemeExpr = Nothing
1379 |          }
1380 |
1381 | export
1382 | updateDef : {auto c : Ref Ctxt Defs} ->
1383 |             Name -> (Def -> Maybe Def) -> Core ()
1384 | updateDef n fdef
1385 |     = do defs <- get Ctxt
1386 |          Just gdef <- lookupCtxtExact n (gamma defs)
1387 |              | Nothing => pure ()
1388 |          case fdef (definition gdef) of
1389 |               Nothing => pure ()
1390 |               Just def' => ignore $ addDef n ({ definition := def',
1391 |                                                 schemeExpr := Nothing } gdef)
1392 |
1393 | export
1394 | updateTy : {auto c : Ref Ctxt Defs} ->
1395 |            Int -> ClosedTerm -> Core ()
1396 | updateTy i ty
1397 |     = do defs <- get Ctxt
1398 |          Just gdef <- lookupCtxtExact (Resolved i) (gamma defs)
1399 |               | Nothing => pure ()
1400 |          ignore $ addDef (Resolved i) ({ type := ty } gdef)
1401 |
1402 | export
1403 | setCompiled : {auto c : Ref Ctxt Defs} ->
1404 |               Name -> CDef -> Core ()
1405 | setCompiled n cexp
1406 |     = do defs <- get Ctxt
1407 |          Just gdef <- lookupCtxtExact n (gamma defs)
1408 |               | Nothing => pure ()
1409 |          ignore $ addDef n ({ compexpr := Just cexp } gdef)
1410 |
1411 | -- Record that the name has been linearity checked so we don't need to do
1412 | -- it again
1413 | export
1414 | setLinearCheck : {auto c : Ref Ctxt Defs} ->
1415 |                  Int -> Bool -> Core ()
1416 | setLinearCheck i chk
1417 |     = do defs <- get Ctxt
1418 |          Just gdef <- lookupCtxtExact (Resolved i) (gamma defs)
1419 |               | Nothing => pure ()
1420 |          ignore $ addDef (Resolved i) ({ linearChecked := chk } gdef)
1421 |
1422 | export
1423 | setCtxt : {auto c : Ref Ctxt Defs} -> Context -> Core ()
1424 | setCtxt gam = update Ctxt { gamma := gam }
1425 |
1426 | export
1427 | resolveName : {auto c : Ref Ctxt Defs} ->
1428 |             Name -> Core Int
1429 | resolveName (Resolved idx) = pure idx
1430 | resolveName n
1431 |   = do defs <- get Ctxt
1432 |        (i, gam') <- getPosition n (gamma defs)
1433 |        setCtxt gam'
1434 |        pure i
1435 |
1436 | export
1437 | addName : {auto c : Ref Ctxt Defs} ->
1438 |           Name -> Core Int
1439 | addName (Resolved idx) = pure idx
1440 | addName n
1441 |   = do defs <- get Ctxt
1442 |        (i, gam') <- newEntry n (gamma defs)
1443 |        setCtxt gam'
1444 |        pure i
1445 |
1446 | -- Call this before trying alternative elaborations, so that updates to the
1447 | -- context are put in the staging area rather than writing over the mutable
1448 | -- array of definitions.
1449 | -- Returns the old context (the one we'll go back to if the branch fails)
1450 | export
1451 | branch : {auto c : Ref Ctxt Defs} ->
1452 |        Core Defs
1453 | branch
1454 |   = do ctxt <- get Ctxt
1455 |        gam' <- branchCtxt (gamma ctxt)
1456 |        setCtxt gam'
1457 |        pure ctxt
1458 |
1459 | -- Call this after trying an elaboration to commit any changes to the mutable
1460 | -- array of definitions once we know they're correct. Only actually commits
1461 | -- when we're right back at the top level
1462 | export
1463 | commit : {auto c : Ref Ctxt Defs} ->
1464 |        Core ()
1465 | commit
1466 |   = do defs <- get Ctxt
1467 |        gam' <- commitCtxt (gamma defs)
1468 |        setCtxt gam'
1469 |
1470 | export
1471 | depth : {auto c : Ref Ctxt Defs} ->
1472 |       Core Nat
1473 | depth
1474 |   = do defs <- get Ctxt
1475 |        pure (branchDepth (gamma defs))
1476 |
1477 | export
1478 | dumpStaging : {auto c : Ref Ctxt Defs} ->
1479 |               Core ()
1480 | dumpStaging
1481 |     = do defs <- get Ctxt
1482 |          coreLift $ putStrLn $ "Staging area: " ++ show (keys (staging (gamma defs)))
1483 |
1484 | -- Explicitly note that the name should be saved when writing out a .ttc
1485 | export
1486 | addToSave : {auto c : Ref Ctxt Defs} ->
1487 |           Name -> Core ()
1488 | addToSave n_in
1489 |   = do defs <- get Ctxt
1490 |        n <- full (gamma defs) n_in
1491 |        put Ctxt ({ toSave $= insert n (),
1492 |                    toIR $= insert n ()
1493 |                  } defs)
1494 |
1495 | -- Specific lookup functions
1496 | export
1497 | lookupExactBy : (GlobalDef -> a) -> Name -> Context ->
1498 |               Core (Maybe a)
1499 | lookupExactBy fn n gam
1500 |   = do Just gdef <- lookupCtxtExact n gam
1501 |             | Nothing => pure Nothing
1502 |        pure (Just (fn gdef))
1503 |
1504 | export
1505 | lookupNameBy : (GlobalDef -> a) -> Name -> Context ->
1506 |              Core (List (Name, Int, a))
1507 | lookupNameBy fn n gam
1508 |   = do gdef <- lookupCtxtName n gam
1509 |        pure (map (\ (n, i, gd) => (n, i, fn gd)) gdef)
1510 |
1511 | export
1512 | lookupDefExact : Name -> Context -> Core (Maybe Def)
1513 | lookupDefExact = lookupExactBy definition
1514 |
1515 | export
1516 | lookupDefName : Name -> Context -> Core (List (Name, Int, Def))
1517 | lookupDefName = lookupNameBy definition
1518 |
1519 | export
1520 | lookupTyExact : Name -> Context -> Core (Maybe ClosedTerm)
1521 | lookupTyExact = lookupExactBy type
1522 |
1523 | export
1524 | lookupTyName : Name -> Context -> Core (List (Name, Int, ClosedTerm))
1525 | lookupTyName = lookupNameBy type
1526 |
1527 | export
1528 | lookupDefTyExact : Name -> Context -> Core (Maybe (Def, ClosedTerm))
1529 | lookupDefTyExact = lookupExactBy (\g => (definition g, type g))
1530 |
1531 | -- private names are only visible in this namespace if their namespace
1532 | -- is the current namespace (or an outer one)
1533 | -- that is: the namespace of 'n' is a parent of nspace
1534 | export
1535 | visibleIn : Namespace -> Name -> Visibility -> Bool
1536 | visibleIn nspace (NS ns n) Private = isParentOf ns nspace
1537 | -- Public and Export names are always visible
1538 | visibleIn nspace n _ = True
1539 |
1540 | export
1541 | visibleInAny : List Namespace -> Name -> Visibility -> Bool
1542 | visibleInAny nss n vis = any (\ns => visibleIn ns n vis) nss
1543 |
1544 | reducibleIn : Namespace -> Name -> Visibility -> Bool
1545 | reducibleIn nspace (NS ns (UN n)) Export = isParentOf ns nspace
1546 | reducibleIn nspace (NS ns (UN n)) Private = isParentOf ns nspace
1547 | reducibleIn nspace n _ = True
1548 |
1549 | export
1550 | reducibleInAny : List Namespace -> Name -> Visibility -> Bool
1551 | reducibleInAny nss n vis = any (\ns => reducibleIn ns n vis) nss
1552 |
1553 | export
1554 | toFullNames : {auto c : Ref Ctxt Defs} ->
1555 |               HasNames a => a -> Core a
1556 | toFullNames t
1557 |     = do defs <- get Ctxt
1558 |          full (gamma defs) t
1559 |
1560 | export
1561 | toResolvedNames : {auto c : Ref Ctxt Defs} ->
1562 |                   HasNames a => a -> Core a
1563 | toResolvedNames t
1564 |     = do defs <- get Ctxt
1565 |          resolved (gamma defs) t
1566 |
1567 | -- Make the name look nicer for user display
1568 | export
1569 | prettyName : {auto c : Ref Ctxt Defs} ->
1570 |              Name -> Core String
1571 | prettyName (Nested (i, _) n)
1572 |     = do i' <- toFullNames (Resolved i)
1573 |          pure (!(prettyName i') ++ "," ++
1574 |                !(prettyName n))
1575 | prettyName (CaseBlock outer idx)
1576 |     = pure ("case block in " ++ outer)
1577 | prettyName (WithBlock outer idx)
1578 |     = pure ("with block in " ++ outer)
1579 | prettyName (NS ns n) = prettyName n
1580 | prettyName n = pure (show n)
1581 |
1582 | -- Add a hash of a thing that contains names,
1583 | -- but convert the internal numbers to full names first.
1584 | -- This makes the hash not depend on the internal numbering,
1585 | -- which is unstable.
1586 | export
1587 | addHashWithNames : {auto c : Ref Ctxt Defs} ->
1588 |   Hashable a => HasNames a => a -> Core ()
1589 | addHashWithNames x = toFullNames x >>= addHash
1590 |
1591 | export
1592 | setIsEscapeHatch : {auto c : Ref Ctxt Defs} ->
1593 |   FC -> Name -> Core ()
1594 | setIsEscapeHatch fc n
1595 |     = do defs <- get Ctxt
1596 |          Just def <- lookupCtxtExact n (gamma defs)
1597 |               | Nothing => undefinedName fc n
1598 |          ignore $ addDef n ({ isEscapeHatch := True } def)
1599 |
1600 | export
1601 | setFlag : {auto c : Ref Ctxt Defs} ->
1602 |         FC -> Name -> DefFlag -> Core ()
1603 | setFlag fc n fl
1604 |     = do defs <- get Ctxt
1605 |          Just def <- lookupCtxtExact n (gamma defs)
1606 |               | Nothing => undefinedName fc n
1607 |          let flags' = fl :: filter (/= fl) (flags def)
1608 |          ignore $ addDef n ({ flags := flags' } def)
1609 |
1610 | export
1611 | setNameFlag : {auto c : Ref Ctxt Defs} ->
1612 |               FC -> Name -> DefFlag -> Core ()
1613 | setNameFlag fc n fl
1614 |     = do defs <- get Ctxt
1615 |          [(n', i, def)] <- lookupCtxtName n (gamma defs)
1616 |               | res => ambiguousName fc n (map fst res)
1617 |          let flags' = fl :: filter (/= fl) (flags def)
1618 |          ignore $ addDef (Resolved i) ({ flags := flags' } def)
1619 |
1620 | export
1621 | unsetFlag : {auto c : Ref Ctxt Defs} ->
1622 |             FC -> Name -> DefFlag -> Core ()
1623 | unsetFlag fc n fl
1624 |     = do defs <- get Ctxt
1625 |          Just def <- lookupCtxtExact n (gamma defs)
1626 |               | Nothing => undefinedName fc n
1627 |          let flags' = filter (/= fl) (flags def)
1628 |          ignore $ addDef n ({ flags := flags' } def)
1629 |
1630 | export
1631 | hasFlag : {auto c : Ref Ctxt Defs} ->
1632 |           FC -> Name -> DefFlag -> Core Bool
1633 | hasFlag fc n fl
1634 |     = do defs <- get Ctxt
1635 |          Just def <- lookupCtxtExact n (gamma defs)
1636 |               | Nothing => undefinedName fc n
1637 |          pure (fl `elem` flags def)
1638 |
1639 | export
1640 | hasSetTotal : {auto c : Ref Ctxt Defs} -> FC -> Name -> Core Bool
1641 | hasSetTotal fc n
1642 |     = do defs <- get Ctxt
1643 |          Just def <- lookupCtxtExact n (gamma defs)
1644 |              | Nothing => undefinedName fc n
1645 |          pure $ isJust $ findSetTotal def.flags
1646 |
1647 | export
1648 | setSizeChange : {auto c : Ref Ctxt Defs} ->
1649 |                 FC -> Name -> List SCCall -> Core ()
1650 | setSizeChange loc n sc
1651 |     = do defs <- get Ctxt
1652 |          Just def <- lookupCtxtExact n (gamma defs)
1653 |               | Nothing => undefinedName loc n
1654 |          ignore $ addDef n ({ sizeChange := sc } def)
1655 |
1656 | export
1657 | setTotality : {auto c : Ref Ctxt Defs} ->
1658 |               FC -> Name -> Totality -> Core ()
1659 | setTotality loc n tot
1660 |     = do defs <- get Ctxt
1661 |          Just def <- lookupCtxtExact n (gamma defs)
1662 |               | Nothing => undefinedName loc n
1663 |          ignore $ addDef n ({ totality := tot } def)
1664 |
1665 | export
1666 | setCovering : {auto c : Ref Ctxt Defs} ->
1667 |               FC -> Name -> Covering -> Core ()
1668 | setCovering loc n tot
1669 |     = do defs <- get Ctxt
1670 |          Just def <- lookupCtxtExact n (gamma defs)
1671 |               | Nothing => undefinedName loc n
1672 |          ignore $ addDef n ({ totality->isCovering := tot } def)
1673 |
1674 | export
1675 | setTerminating : {auto c : Ref Ctxt Defs} ->
1676 |                  FC -> Name -> Terminating -> Core ()
1677 | setTerminating loc n tot
1678 |     = do defs <- get Ctxt
1679 |          Just def <- lookupCtxtExact n (gamma defs)
1680 |               | Nothing => undefinedName loc n
1681 |          ignore $ addDef n ({ totality->isTerminating := tot } def)
1682 |
1683 | export
1684 | getTotality : {auto c : Ref Ctxt Defs} ->
1685 |               FC -> Name -> Core Totality
1686 | getTotality loc n
1687 |     = do defs <- get Ctxt
1688 |          Just def <- lookupCtxtExact n (gamma defs)
1689 |               | Nothing => undefinedName loc n
1690 |          pure $ totality def
1691 |
1692 | export
1693 | getSizeChange : {auto c : Ref Ctxt Defs} ->
1694 |                 FC -> Name -> Core (List SCCall)
1695 | getSizeChange loc n
1696 |     = do defs <- get Ctxt
1697 |          Just def <- lookupCtxtExact n (gamma defs)
1698 |               | Nothing => undefinedName loc n
1699 |          pure $ sizeChange def
1700 |
1701 | export
1702 | setVisibility : {auto c : Ref Ctxt Defs} ->
1703 |                 FC -> Name -> Visibility -> Core ()
1704 | setVisibility fc n vis
1705 |     = do defs <- get Ctxt
1706 |          Just def <- lookupCtxtExact n (gamma defs)
1707 |               | Nothing => undefinedName fc n
1708 |          ignore $ addDef n ({ visibility := specified vis } def)
1709 |
1710 | export
1711 | withDefStacked : {auto c : Ref Ctxt Defs} ->
1712 |                  Name -> Core a -> Core a
1713 | withDefStacked n act
1714 |     = do defs <- get Ctxt
1715 |          let ds = defs.defsStack
1716 |          put Ctxt $ {defsStack $= (:< n)} defs
1717 |          act <* update Ctxt {defsStack := ds}
1718 |
1719 | public export
1720 | record SearchData where
1721 |   constructor MkSearchData
1722 |   ||| determining argument positions
1723 |   detArgs : NatSet
1724 |   ||| Name of functions to use as hints, and whether ambiguity is allowed
1725 |   |||
1726 |   ||| In proof search, for every group of names
1727 |   |||  * If exactly one succeeds, use it
1728 |   |||  * If more than one succeeds, report an ambiguity error
1729 |   |||  * If none succeed, move on to the next group
1730 |   |||
1731 |   ||| This allows us to prioritise some names (e.g. to declare 'open' hints,
1732 |   ||| which we might us to open an implementation working as a module, or to
1733 |   ||| declare a named implementation to be used globally), and to have names
1734 |   ||| which are only used if all else fails (e.g. as a defaulting mechanism),
1735 |   ||| while the proof search mechanism doesn't need to know about any of the
1736 |   ||| details.
1737 |   hintGroups : List (Bool, List Name)
1738 |
1739 | ||| Get the auto search data for a name.
1740 | export
1741 | getSearchData : {auto c : Ref Ctxt Defs} ->
1742 |                 FC -> (defaults : Bool) -> Name ->
1743 |                 Core SearchData
1744 | getSearchData fc defaults target
1745 |     = do defs <- get Ctxt
1746 |          Just (TCon _ _ dets u _ _ _) <- lookupDefExact target (gamma defs)
1747 |               | _ => undefinedName fc target
1748 |          hs <- case lookup !(toFullNames target) (typeHints defs) of
1749 |                        Just hs => filterM (\x => notHidden x (gamma defs)) hs
1750 |                        Nothing => pure []
1751 |          if defaults
1752 |             then let defns = map fst !(filterM (\x => pure $ isDefault x
1753 |                                                  && !(notHidden x (gamma defs)))
1754 |                                              (toList (autoHints defs))) in
1755 |                      pure (MkSearchData NatSet.empty [(False, defns)])
1756 |             else let opens = map fst !(filterM (\x => notHidden x (gamma defs))
1757 |                                              (toList (openHints defs)))
1758 |                      autos = map fst !(filterM (\x => pure $ not (isDefault x)
1759 |                                                  && !(notHidden x (gamma defs)))
1760 |                                              (toList (autoHints defs)))
1761 |                      tyhs = map fst (filter direct hs)
1762 |                      chasers = map fst (filter (not . direct) hs) in
1763 |                      pure (MkSearchData dets (filter (isCons . snd)
1764 |                                [(False, opens),
1765 |                                 (False, autos),
1766 |                                 (not (uniqueAuto u), tyhs),
1767 |                                 (True, chasers)]))
1768 |   where
1769 |     ||| We don't want hidden (by `%hide`) names to appear in the search.
1770 |     ||| Lookup has to be done by a full qualified name, not a resolved ID.
1771 |     notHidden : forall a. (Name, a) -> Context -> Core Bool
1772 |     notHidden (n, _) ctxt = do
1773 |       fulln <- toFullNames n
1774 |       pure $ not (isHidden fulln ctxt)
1775 |
1776 |     isDefault : (Name, Bool) -> Bool
1777 |     isDefault = snd
1778 |
1779 |     direct : (Name, Bool) -> Bool
1780 |     direct = snd
1781 |
1782 | export
1783 | setMutWith : {auto c : Ref Ctxt Defs} ->
1784 |              FC -> Name -> List Name -> Core ()
1785 | setMutWith fc tn tns
1786 |     = do defs <- get Ctxt
1787 |          Just g <- lookupCtxtExact tn (gamma defs)
1788 |               | _ => undefinedName fc tn
1789 |          let TCon a ps dets u _ cons det = definition g
1790 |               | _ => throw (GenericMsg fc (show (fullname g) ++ " is not a type constructor [setMutWith]"))
1791 |          updateDef tn (const (Just (TCon a ps dets u tns cons det)))
1792 |
1793 | export
1794 | addMutData : {auto c : Ref Ctxt Defs} ->
1795 |              Name -> Core ()
1796 | addMutData n = update Ctxt { mutData $= (n ::) }
1797 |
1798 | export
1799 | dropMutData : {auto c : Ref Ctxt Defs} ->
1800 |               Name -> Core ()
1801 | dropMutData n = update Ctxt { mutData $= filter (/= n) }
1802 |
1803 | export
1804 | setDetermining : {auto c : Ref Ctxt Defs} ->
1805 |                  FC -> Name -> List1 Name -> Core ()
1806 | setDetermining fc tyn args
1807 |     = do defs <- get Ctxt
1808 |          Just g <- lookupCtxtExact tyn (gamma defs)
1809 |               | _ => undefinedName fc tyn
1810 |          let TCon a ps _ u cons ms det = definition g
1811 |               | _ => throw (GenericMsg fc (show (fullname g) ++ " is not a type constructor [setDetermining]"))
1812 |          apos <- getPos 0 (forget args) (type g)
1813 |          updateDef tyn (const (Just (TCon a ps apos u cons ms det)))
1814 |   where
1815 |     -- Type isn't normalised, but the argument names refer to those given
1816 |     -- explicitly in the type, so there's no need.
1817 |     getPos : Nat -> List Name -> Term vs -> Core NatSet
1818 |     getPos i ns (Bind _ x (Pi {}) sc)
1819 |         = if x `elem` ns
1820 |              then do rest <- getPos (1 + i) (filter (/=x) ns) sc
1821 |                      pure $ insert i rest
1822 |              else getPos (1 + i) ns sc
1823 |     getPos _ [] _ = pure NatSet.empty
1824 |     getPos _ ns ty = throw (GenericMsg fc ("Unknown determining arguments: "
1825 |                            ++ showSep ", " (map show ns)))
1826 |
1827 | export
1828 | setDetags : {auto c : Ref Ctxt Defs} ->
1829 |             FC -> Name -> Maybe NatSet -> Core ()
1830 | setDetags fc tyn args
1831 |     = do defs <- get Ctxt
1832 |          Just g <- lookupCtxtExact tyn (gamma defs)
1833 |               | _ => undefinedName fc tyn
1834 |          let TCon a ps det u cons ms _ = definition g
1835 |               | _ => throw (GenericMsg fc (show (fullname g) ++ " is not a type constructor [setDetermining]"))
1836 |          updateDef tyn (const (Just (TCon a ps det u cons ms args)))
1837 |
1838 | export
1839 | setUniqueSearch : {auto c : Ref Ctxt Defs} ->
1840 |                   FC -> Name -> Bool -> Core ()
1841 | setUniqueSearch fc tyn u
1842 |     = do defs <- get Ctxt
1843 |          Just g <- lookupCtxtExact tyn (gamma defs)
1844 |               | _ => undefinedName fc tyn
1845 |          let TCon a ps ds fl cons ms det = definition g
1846 |               | _ => throw (GenericMsg fc (show (fullname g) ++ " is not a type constructor [setDetermining]"))
1847 |          let fl' = { uniqueAuto := u } fl
1848 |          updateDef tyn (const (Just (TCon a ps ds fl' cons ms det)))
1849 |
1850 | export
1851 | setExternal : {auto c : Ref Ctxt Defs} ->
1852 |               FC -> Name -> Bool -> Core ()
1853 | setExternal fc tyn u
1854 |     = do defs <- get Ctxt
1855 |          Just g <- lookupCtxtExact tyn (gamma defs)
1856 |               | _ => undefinedName fc tyn
1857 |          let TCon a ps ds fl cons ms det = definition g
1858 |               | _ => throw (GenericMsg fc (show (fullname g) ++ " is not a type constructor [setDetermining]"))
1859 |          let fl' = { external := u } fl
1860 |          updateDef tyn (const (Just (TCon a ps ds fl' cons ms det)))
1861 |
1862 | export
1863 | addHintFor : {auto c : Ref Ctxt Defs} ->
1864 |              FC -> Name -> Name -> Bool -> Bool -> Core ()
1865 | addHintFor fc tyn_in hintn_in direct loading
1866 |     = do defs <- get Ctxt
1867 |          tyn <- toFullNames tyn_in
1868 |           -- ^ We have to index by full name because of the order we load -
1869 |           -- the name may not be resolved yet when we load the hints.
1870 |           -- Revisit if this turns out to be a bottleneck (it seems unlikely)
1871 |          hintn <- toResolvedNames hintn_in
1872 |
1873 |          let hs = case lookup tyn (typeHints defs) of
1874 |                        Just hs => hs
1875 |                        Nothing => []
1876 |          if loading
1877 |             then put Ctxt
1878 |                      ({ typeHints $= insert tyn ((hintn, direct) :: hs)
1879 |                       } defs)
1880 |             else put Ctxt
1881 |                      ({ typeHints $= insert tyn ((hintn, direct) :: hs),
1882 |                         saveTypeHints $= ((tyn, hintn, direct) :: )
1883 |                       } defs)
1884 |
1885 | export
1886 | addGlobalHint : {auto c : Ref Ctxt Defs} ->
1887 |                 Name -> Bool -> Core ()
1888 | addGlobalHint hintn_in isdef
1889 |     = do hintn <- toResolvedNames hintn_in
1890 |          update Ctxt { autoHints $= insert hintn isdef,
1891 |                        saveAutoHints $= ((hintn, isdef) ::) }
1892 |
1893 | export
1894 | addLocalHint : {auto c : Ref Ctxt Defs} ->
1895 |                Name -> Core ()
1896 | addLocalHint hintn_in
1897 |     = do hintn <- toResolvedNames hintn_in
1898 |          update Ctxt { localHints $= insert hintn () }
1899 |
1900 | export
1901 | addOpenHint : {auto c : Ref Ctxt Defs} -> Name -> Core ()
1902 | addOpenHint hintn_in
1903 |     = do hintn <- toResolvedNames hintn_in
1904 |          update Ctxt { openHints $= insert hintn () }
1905 |
1906 | export
1907 | dropOpenHint : {auto c : Ref Ctxt Defs} -> Name -> Core ()
1908 | dropOpenHint hintn_in
1909 |     = do hintn <- toResolvedNames hintn_in
1910 |          update Ctxt { openHints $= delete hintn }
1911 |
1912 | export
1913 | setOpenHints : {auto c : Ref Ctxt Defs} -> NameMap () -> Core ()
1914 | setOpenHints hs = update Ctxt { openHints := hs }
1915 |
1916 | -- The latest rule for a function is tried first
1917 | insertTransform : Name -> Transform ->
1918 |                   NameMap (List Transform) -> NameMap (List Transform)
1919 | insertTransform fn t ts = insert fn (maybe [t] (t ::) (lookup fn ts)) ts
1920 |
1921 | -- A rule read from a TTC is kept unresolved until a rule is used or added: it
1922 | -- may name a function whose module was not loaded yet when its own module was
1923 | -- read (the Prelude's modules load in reverse import order), and a name that
1924 | -- cannot be resolved then would never match an elaborated term. Every reader
1925 | -- of 'transforms' calls this first, so the map holds what resolving the rules
1926 | -- at load time would have, in the same order.
1927 | export
1928 | resolveTransforms : {auto c : Ref Ctxt Defs} -> Core ()
1929 | resolveTransforms
1930 |     = do defs <- get Ctxt
1931 |          case pendingTransforms defs of
1932 |               [] => pure ()
1933 |               ps => do put Ctxt ({ pendingTransforms := [] } defs)
1934 |                        traverse_ add ps
1935 |   where
1936 |     add : (Name, Transform) -> Core ()
1937 |     add (n, t)
1938 |         = do n' <- toResolvedNames n
1939 |              t' <- toResolvedNames t
1940 |              update Ctxt { transforms $= insertTransform n' t' }
1941 |
1942 | export
1943 | addTransform : {auto c : Ref Ctxt Defs} ->
1944 |                FC -> Transform -> Core ()
1945 | addTransform fc t_in
1946 |     = do resolveTransforms
1947 |          let Just fn_in = getFnName t_in
1948 |              | Nothing =>
1949 |                   throw (GenericMsg fc "LHS of a transformation must be a function application")
1950 |          fn <- toResolvedNames fn_in
1951 |          t <- toResolvedNames t_in
1952 |          fn_full <- toFullNames fn_in
1953 |          t_full <- toFullNames t_in
1954 |          update Ctxt { transforms $= insertTransform fn t,
1955 |                        saveTransforms $= ((fn_full, t_full) ::) }
1956 |
1957 | export
1958 | clearSavedHints : {auto c : Ref Ctxt Defs} -> Core ()
1959 | clearSavedHints = update Ctxt { saveTypeHints := [], saveAutoHints := [] }
1960 |
1961 | -- Set the default namespace for new definitions
1962 | export
1963 | setNS : {auto c : Ref Ctxt Defs} -> Namespace -> Core ()
1964 | setNS ns = update Ctxt { currentNS := ns }
1965 |
1966 | -- Set the nested namespaces we're allowed to look inside
1967 | export
1968 | setNestedNS : {auto c : Ref Ctxt Defs} ->
1969 |               List Namespace -> Core ()
1970 | setNestedNS ns = update Ctxt { nestedNS := ns }
1971 |
1972 | -- Get the default namespace for new definitions
1973 | export
1974 | getNS : {auto c : Ref Ctxt Defs} ->
1975 |         Core Namespace
1976 | getNS
1977 |     = do defs <- get Ctxt
1978 |          pure (currentNS defs)
1979 |
1980 | -- Get the nested namespaces we're allowed to look inside
1981 | export
1982 | getNestedNS : {auto c : Ref Ctxt Defs} ->
1983 |               Core (List Namespace)
1984 | getNestedNS
1985 |     = do defs <- get Ctxt
1986 |          pure (nestedNS defs)
1987 |
1988 | -- Add the module name, and namespace, of an imported module
1989 | -- (i.e. for "import X as Y", it's (X, Y)
1990 | -- "import public X" is, when rexported, the same as
1991 | -- "import X as [current namespace]")
1992 | export
1993 | addImported : {auto c : Ref Ctxt Defs} ->
1994 |               (ModuleIdent, Bool, Namespace) -> Core ()
1995 | addImported mod = update Ctxt { imported $= (mod ::) }
1996 |
1997 | export
1998 | getImported : {auto c : Ref Ctxt Defs} ->
1999 |               Core (List (ModuleIdent, Bool, Namespace))
2000 | getImported
2001 |     = do defs <- get Ctxt
2002 |          pure (imported defs)
2003 |
2004 | export
2005 | addDirective : {auto c : Ref Ctxt Defs} ->
2006 |                String -> String -> Core ()
2007 | addDirective c str
2008 |     = do defs <- get Ctxt
2009 |          case getCG (options defs) c of
2010 |               Nothing => put Ctxt ({ cgdirectives $= insert (Other (toLower c), str) } defs)
2011 |               Just cg => put Ctxt ({ cgdirectives $= insert (cg, str) } defs)
2012 |
2013 | export
2014 | getDirectives : {auto c : Ref Ctxt Defs} ->
2015 |                 CG -> Core (List String)
2016 | getDirectives cg
2017 |     = do defs <- get Ctxt
2018 |          pure $ defs.options.session.directives ++
2019 |                  mapMaybe getDir (Prelude.toList $ cgdirectives defs)
2020 |   where
2021 |     getDir : (CG, String) -> Maybe String
2022 |     getDir (x', str) = if cg == x' then Just str else Nothing
2023 |
2024 | -- Add a new nested namespace to the current namespace for new definitions
2025 | -- e.g. extendNS ["Data"] when namespace is "Prelude.List" leads to
2026 | -- current namespace of "Prelude.List.Data"
2027 | -- Inner namespaces go first, for ease of name lookup
2028 | export
2029 | extendNS : {auto c : Ref Ctxt Defs} -> Namespace -> Core ()
2030 | extendNS ns = update Ctxt { currentNS $= (<.> ns) }
2031 |
2032 | export
2033 | withExtendedNS : {auto c : Ref Ctxt Defs} ->
2034 |                  Namespace -> Core a -> Core a
2035 | withExtendedNS ns act
2036 |     = do defs <- get Ctxt
2037 |          let cns = currentNS defs
2038 |          let nns = nestedNS defs
2039 |          put Ctxt ({ currentNS := cns <.> ns } defs)
2040 |          ma <- catch (Right <$> act) (pure . Left)
2041 |          defs <- get Ctxt
2042 |          put Ctxt ({ currentNS := cns, nestedNS := nns } defs)
2043 |          case ma of
2044 |            Left err => throw err
2045 |            Right a  => pure a
2046 |
2047 | -- Get the name as it would be defined in the current namespace
2048 | -- i.e. if it doesn't have an explicit namespace already, add it,
2049 | -- otherwise leave it alone
2050 | export
2051 | inCurrentNS : {auto c : Ref Ctxt Defs} ->
2052 |               Name -> Core Name
2053 | inCurrentNS (UN n)
2054 |     = do defs <- get Ctxt
2055 |          pure (NS (currentNS defs) (UN n))
2056 | inCurrentNS n@(CaseBlock {})
2057 |     = do defs <- get Ctxt
2058 |          pure (NS (currentNS defs) n)
2059 | inCurrentNS n@(WithBlock {})
2060 |     = do defs <- get Ctxt
2061 |          pure (NS (currentNS defs) n)
2062 | inCurrentNS n@(Nested {})
2063 |     = do defs <- get Ctxt
2064 |          pure (NS (currentNS defs) n)
2065 | inCurrentNS n@(MN {})
2066 |     = do defs <- get Ctxt
2067 |          pure (NS (currentNS defs) n)
2068 | inCurrentNS n@(DN {})
2069 |     = do defs <- get Ctxt
2070 |          pure (NS (currentNS defs) n)
2071 | inCurrentNS n = pure n
2072 |
2073 | export
2074 | setVisible : {auto c : Ref Ctxt Defs} ->
2075 |              Namespace -> Core ()
2076 | setVisible nspace = update Ctxt { gamma->visibleNS $= (nspace ::) }
2077 |
2078 | export
2079 | getVisible : {auto c : Ref Ctxt Defs} ->
2080 |              Core (List Namespace)
2081 | getVisible
2082 |     = do defs <- get Ctxt
2083 |          pure (visibleNS (gamma defs))
2084 |
2085 | -- set whether all names should be viewed as public. Be careful with this,
2086 | -- it's not intended for when checking user code! It's meant for allowing
2087 | -- easy checking of partially evaluated definitions.
2088 | export
2089 | setAllPublic : {auto c : Ref Ctxt Defs} ->
2090 |                (pub : Bool) -> Core ()
2091 | setAllPublic pub = update Ctxt { gamma->allPublic := pub }
2092 |
2093 | export
2094 | isAllPublic : {auto c : Ref Ctxt Defs} ->
2095 |               Core Bool
2096 | isAllPublic
2097 |     = do defs <- get Ctxt
2098 |          pure (allPublic (gamma defs))
2099 |
2100 | -- Return True if the given namespace is visible in the context (meaning
2101 | -- the namespace itself, and any namespace it's nested inside)
2102 | export
2103 | isVisible : {auto c : Ref Ctxt Defs} ->
2104 |             Namespace -> Core Bool
2105 | isVisible nspace
2106 |     = do defs <- get Ctxt
2107 |          pure (any visible (allParents (currentNS defs) ++
2108 |                             nestedNS defs ++
2109 |                             visibleNS (gamma defs)))
2110 |
2111 |   where
2112 |     -- Visible if any visible namespace is a parent of the namespace we're
2113 |     -- asking about
2114 |     visible : Namespace -> Bool
2115 |     visible visns = isParentOf visns nspace
2116 |
2117 | -- Get the next entry id in the context (this is for recording where to go
2118 | -- back to when backtracking in the elaborator)
2119 | export
2120 | getNextEntry : {auto c : Ref Ctxt Defs} ->
2121 |                Core Int
2122 | getNextEntry
2123 |     = do defs <- get Ctxt
2124 |          pure (nextEntry (gamma defs))
2125 |
2126 | export
2127 | setNextEntry : {auto c : Ref Ctxt Defs} ->
2128 |                Int -> Core ()
2129 | setNextEntry i = update Ctxt { gamma->nextEntry := i }
2130 |
2131 | -- Set the 'first entry' index (i.e. the first entry in the current file)
2132 | -- to the place we currently are in the context
2133 | export
2134 | resetFirstEntry : {auto c : Ref Ctxt Defs} ->
2135 |                   Core ()
2136 | resetFirstEntry
2137 |     = do defs <- get Ctxt
2138 |          put Ctxt ({ gamma->firstEntry := nextEntry (gamma defs) } defs)
2139 |
2140 | export
2141 | getFullName : {auto c : Ref Ctxt Defs} ->
2142 |               Name -> Core Name
2143 | getFullName (Resolved i)
2144 |     = do defs <- get Ctxt
2145 |          Just gdef <- lookupCtxtExact (Resolved i) (gamma defs)
2146 |               | Nothing => pure (Resolved i)
2147 |          pure (fullname gdef)
2148 | getFullName n = pure n
2149 |
2150 | -- Getting and setting various options
2151 |
2152 | export
2153 | getPPrint : {auto c : Ref Ctxt Defs} ->
2154 |             Core PPrinter
2155 | getPPrint
2156 |     = do defs <- get Ctxt
2157 |          pure (printing (options defs))
2158 |
2159 | export
2160 | setPPrint : {auto c : Ref Ctxt Defs} -> PPrinter -> Core ()
2161 | setPPrint ppopts = update Ctxt { options->printing := ppopts }
2162 |
2163 | export
2164 | updatePPrint : {auto c : Ref Ctxt Defs} -> (PPrinter -> PPrinter) -> Core ()
2165 | updatePPrint f = update Ctxt { options->printing $= f }
2166 |
2167 | export
2168 | setCG : {auto c : Ref Ctxt Defs} -> CG -> Core ()
2169 | setCG cg = update Ctxt { options->session->codegen := cg }
2170 |
2171 | export
2172 | getDirs : {auto c : Ref Ctxt Defs} -> Core Dirs
2173 | getDirs
2174 |     = do defs <- get Ctxt
2175 |          pure (dirs (options defs))
2176 |
2177 | export
2178 | addExtraDir : {auto c : Ref Ctxt Defs} -> String -> Core ()
2179 | addExtraDir dir = update Ctxt { options->dirs->extra_dirs $= ((::) dir) . filter (/= dir) }
2180 |
2181 | export
2182 | addPackageDir: {auto c : Ref Ctxt Defs} -> String -> Core ()
2183 | addPackageDir dir = update Ctxt { options->dirs->package_dirs $= ((::) dir) . filter (/= dir) }
2184 |
2185 | export
2186 | addPackageSearchPath: {auto c : Ref Ctxt Defs} -> String -> Core ()
2187 | addPackageSearchPath dir =
2188 |   let newPath = parse dir
2189 |    in update Ctxt { options->dirs->package_search_paths $= ((::) newPath) . filter (/= newPath) }
2190 |
2191 | export
2192 | addDataDir : {auto c : Ref Ctxt Defs} -> String -> Core ()
2193 | addDataDir dir = update Ctxt { options->dirs->data_dirs $= (++ [dir]) }
2194 |
2195 | export
2196 | addLibDir : {auto c : Ref Ctxt Defs} -> String -> Core ()
2197 | addLibDir dir = update Ctxt { options->dirs->lib_dirs $= (++ [dir]) }
2198 |
2199 | export
2200 | setBuildDir : {auto c : Ref Ctxt Defs} -> String -> Core ()
2201 | setBuildDir dir = update Ctxt { options->dirs->build_dir := dir }
2202 |
2203 | export
2204 | setDependsDir : {auto c : Ref Ctxt Defs} -> String -> Core ()
2205 | setDependsDir dir = update Ctxt { options->dirs->depends_dir := dir }
2206 |
2207 | export
2208 | setOutputDir : {auto c : Ref Ctxt Defs} -> Maybe String -> Core ()
2209 | setOutputDir dir = update Ctxt { options->dirs->output_dir := dir }
2210 |
2211 | export
2212 | setSourceDir : {auto c : Ref Ctxt Defs} -> Maybe String -> Core ()
2213 | setSourceDir mdir = update Ctxt { options->dirs->source_dir := mdir }
2214 |
2215 | export
2216 | setWorkingDir : {auto c : Ref Ctxt Defs} -> String -> Core ()
2217 | setWorkingDir dir
2218 |     = do coreLift_ $ changeDir dir
2219 |          Just cdir <- coreLift $ currentDir
2220 |               | Nothing => throw (InternalError "Can't get current directory")
2221 |          update Ctxt { options->dirs->working_dir := cdir }
2222 |
2223 | export
2224 | getWorkingDir : Core String
2225 | getWorkingDir
2226 |     = do Just d <- coreLift $ currentDir
2227 |               | Nothing => throw (InternalError "Can't get current directory")
2228 |          pure d
2229 |
2230 | export
2231 | setExtraDirs : {auto c : Ref Ctxt Defs} -> List String -> Core ()
2232 | setExtraDirs dirs = update Ctxt { options->dirs->extra_dirs := dirs }
2233 |
2234 | export
2235 | setPackageDirs : {auto c : Ref Ctxt Defs} -> List String -> Core ()
2236 | setPackageDirs dirs = update Ctxt { options->dirs->package_dirs := dirs }
2237 |
2238 | export
2239 | withCtxt : {auto c : Ref Ctxt Defs} -> Core a -> Core a
2240 | withCtxt = wrapRef Ctxt resetCtxt
2241 |   where
2242 |     resetCtxt : Defs -> Core ()
2243 |     resetCtxt defs = do let dir = defs.options.dirs.working_dir
2244 |                         coreLift_ $ changeDir dir
2245 |
2246 | export
2247 | setPrefix : {auto c : Ref Ctxt Defs} -> String -> Core ()
2248 | setPrefix dir = update Ctxt { options->dirs->prefix_dir := dir }
2249 |
2250 | export
2251 | setExtension : {auto c : Ref Ctxt Defs} -> LangExt -> Core ()
2252 | setExtension e = update Ctxt { options $= setExtension e }
2253 |
2254 | export
2255 | isExtension : LangExt -> Defs -> Bool
2256 | isExtension e defs = isExtension e (options defs)
2257 |
2258 | export
2259 | checkUnambig : {auto c : Ref Ctxt Defs} ->
2260 |                FC -> Name -> Core Name
2261 | checkUnambig fc n
2262 |     = do defs <- get Ctxt
2263 |          case !(lookupDefName n (gamma defs)) of
2264 |               [(fulln, i, _)] => pure (Resolved i)
2265 |               ns => ambiguousName fc n (map fst ns)
2266 |
2267 | export
2268 | lazyActive : {auto c : Ref Ctxt Defs} -> Bool -> Core ()
2269 | lazyActive a = update Ctxt { options->elabDirectives->lazyActive := a }
2270 |
2271 | export
2272 | setUnboundImplicits : {auto c : Ref Ctxt Defs} -> Bool -> Core ()
2273 | setUnboundImplicits a = update Ctxt { options->elabDirectives->unboundImplicits := a }
2274 |
2275 | export
2276 | setPrefixRecordProjections : {auto c : Ref Ctxt Defs} -> Bool -> Core ()
2277 | setPrefixRecordProjections b = update Ctxt { options->elabDirectives->prefixRecordProjections := b }
2278 |
2279 | export
2280 | setDefaultTotalityOption : {auto c : Ref Ctxt Defs} ->
2281 |                            TotalReq -> Core ()
2282 | setDefaultTotalityOption tot = update Ctxt { options->elabDirectives->totality := tot }
2283 |
2284 | export
2285 | setAmbigLimit : {auto c : Ref Ctxt Defs} ->
2286 |                 Nat -> Core ()
2287 | setAmbigLimit max = update Ctxt { options->elabDirectives->ambigLimit := max }
2288 |
2289 | export
2290 | setTotalLimit : {auto c : Ref Ctxt Defs} ->
2291 |                 Nat -> Core ()
2292 | setTotalLimit max = update Ctxt { options->elabDirectives->totalLimit := max }
2293 |
2294 | export
2295 | setAutoImplicitLimit : {auto c : Ref Ctxt Defs} ->
2296 |                        Nat -> Core ()
2297 | setAutoImplicitLimit max = update Ctxt { options->elabDirectives->autoImplicitLimit := max }
2298 |
2299 | export
2300 | setNFThreshold : {auto c : Ref Ctxt Defs} ->
2301 |                  Nat -> Core ()
2302 | setNFThreshold max = update Ctxt { options->elabDirectives->nfThreshold := max }
2303 |
2304 | export
2305 | setSearchTimeout : {auto c : Ref Ctxt Defs} ->
2306 |                    Integer -> Core ()
2307 | setSearchTimeout t = update Ctxt { options->session->searchTimeout := t }
2308 |
2309 | export
2310 | isLazyActive : {auto c : Ref Ctxt Defs} ->
2311 |                Core Bool
2312 | isLazyActive
2313 |     = do defs <- get Ctxt
2314 |          pure (lazyActive (elabDirectives (options defs)))
2315 |
2316 | export
2317 | isUnboundImplicits : {auto c : Ref Ctxt Defs} ->
2318 |                   Core Bool
2319 | isUnboundImplicits
2320 |     = do defs <- get Ctxt
2321 |          pure (unboundImplicits (elabDirectives (options defs)))
2322 |
2323 | export
2324 | isPrefixRecordProjections : {auto c : Ref Ctxt Defs} -> Core Bool
2325 | isPrefixRecordProjections =
2326 |   prefixRecordProjections . elabDirectives . options <$> get Ctxt
2327 |
2328 | export
2329 | getDefaultTotalityOption : {auto c : Ref Ctxt Defs} ->
2330 |                            Core TotalReq
2331 | getDefaultTotalityOption
2332 |     = do defs <- get Ctxt
2333 |          pure (totality (elabDirectives (options defs)))
2334 |
2335 | export
2336 | getAmbigLimit : {auto c : Ref Ctxt Defs} ->
2337 |                 Core Nat
2338 | getAmbigLimit
2339 |     = do defs <- get Ctxt
2340 |          pure (ambigLimit (elabDirectives (options defs)))
2341 |
2342 | export
2343 | getAutoImplicitLimit : {auto c : Ref Ctxt Defs} ->
2344 |                        Core Nat
2345 | getAutoImplicitLimit
2346 |     = do defs <- get Ctxt
2347 |          pure (autoImplicitLimit (elabDirectives (options defs)))
2348 |
2349 | export
2350 | addForeignImpl : {auto c : Ref Ctxt Defs} ->
2351 |           FC -> (fullName : Name) -> (def : String) -> Core ()
2352 | addForeignImpl fc name def
2353 |    = do name <- toFullNames name
2354 |         update Ctxt { options $= addForeignImpl name def }
2355 |
2356 | export
2357 | setPair : {auto c : Ref Ctxt Defs} ->
2358 |           FC -> (pairType : Name) -> (fstn : Name) -> (sndn : Name) ->
2359 |           Core ()
2360 | setPair fc ty f s
2361 |     = do ty' <- checkUnambig fc ty
2362 |          f' <- checkUnambig fc f
2363 |          s' <- checkUnambig fc s
2364 |          update Ctxt { options $= setPair ty' f' s' }
2365 |
2366 | export
2367 | setRewrite : {auto c : Ref Ctxt Defs} ->
2368 |              FC -> (eq : Name) -> (rwlemma : Name) -> Core ()
2369 | setRewrite fc eq rw
2370 |     = do rw' <- checkUnambig fc rw
2371 |          eq' <- checkUnambig fc eq
2372 |          update Ctxt { options $= setRewrite eq' rw' }
2373 |
2374 | -- Don't check for ambiguity here; they're all meant to be overloadable
2375 | export
2376 | setFromInteger : {auto c : Ref Ctxt Defs} ->
2377 |                  Name -> Core ()
2378 | setFromInteger n = update Ctxt { options $= setFromInteger n }
2379 |
2380 | export
2381 | setFromString : {auto c : Ref Ctxt Defs} ->
2382 |                 Name -> Core ()
2383 | setFromString n = update Ctxt { options $= setFromString n }
2384 |
2385 | export
2386 | setFromChar : {auto c : Ref Ctxt Defs} ->
2387 |               Name -> Core ()
2388 | setFromChar n = update Ctxt { options $= setFromChar n }
2389 |
2390 | export
2391 | setFromDouble : {auto c : Ref Ctxt Defs} ->
2392 |               Name -> Core ()
2393 | setFromDouble n = update Ctxt { options $= setFromDouble n }
2394 |
2395 | export
2396 | setFromTTImp : {auto c : Ref Ctxt Defs} ->
2397 |                Name -> Core ()
2398 | setFromTTImp n = update Ctxt { options $= setFromTTImp n }
2399 |
2400 | export
2401 | setFromName : {auto c : Ref Ctxt Defs} ->
2402 |               Name -> Core ()
2403 | setFromName n = update Ctxt { options $= setFromName n }
2404 |
2405 | export
2406 | setFromDecls : {auto c : Ref Ctxt Defs} ->
2407 |                Name -> Core ()
2408 | setFromDecls n = update Ctxt { options $= setFromDecls n }
2409 |
2410 | export
2411 | addNameDirective : {auto c : Ref Ctxt Defs} ->
2412 |                    FC -> Name -> List String -> Core ()
2413 | addNameDirective fc n ns
2414 |     = do n' <- checkUnambig fc n
2415 |          update Ctxt { namedirectives $= insert n' ns  }
2416 |
2417 | -- Checking special names from Options
2418 |
2419 | export
2420 | isPairType : {auto c : Ref Ctxt Defs} ->
2421 |              Name -> Core Bool
2422 | isPairType n
2423 |     = do defs <- get Ctxt
2424 |          case pairnames (options defs) of
2425 |               Nothing => pure False
2426 |               Just l => pure $ !(getFullName n) == !(getFullName (pairType l))
2427 |
2428 | export
2429 | fstName : {auto c : Ref Ctxt Defs} ->
2430 |           Core (Maybe Name)
2431 | fstName
2432 |     = do defs <- get Ctxt
2433 |          pure $ maybe Nothing (Just . fstName) (pairnames (options defs))
2434 |
2435 | export
2436 | sndName : {auto c : Ref Ctxt Defs} ->
2437 |           Core (Maybe Name)
2438 | sndName
2439 |     = do defs <- get Ctxt
2440 |          pure $ maybe Nothing (Just . sndName) (pairnames (options defs))
2441 |
2442 | export
2443 | getRewrite :{auto c : Ref Ctxt Defs} ->
2444 |             Core (Maybe Name)
2445 | getRewrite
2446 |     = do defs <- get Ctxt
2447 |          pure $ maybe Nothing (Just . rewriteName) (rewritenames (options defs))
2448 |
2449 | export
2450 | isEqualTy : {auto c : Ref Ctxt Defs} ->
2451 |             Name -> Core Bool
2452 | isEqualTy n
2453 |     = do defs <- get Ctxt
2454 |          case rewritenames (options defs) of
2455 |               Nothing => pure False
2456 |               Just r => pure $ !(getFullName n) == !(getFullName (equalType r))
2457 |
2458 | export
2459 | fromIntegerName : {auto c : Ref Ctxt Defs} ->
2460 |                   Core (Maybe Name)
2461 | fromIntegerName
2462 |     = do defs <- get Ctxt
2463 |          pure $ fromIntegerName (primnames (options defs))
2464 |
2465 | export
2466 | fromStringName : {auto c : Ref Ctxt Defs} ->
2467 |                  Core (Maybe Name)
2468 | fromStringName
2469 |     = do defs <- get Ctxt
2470 |          pure $ fromStringName (primnames (options defs))
2471 |
2472 | export
2473 | fromCharName : {auto c : Ref Ctxt Defs} ->
2474 |                Core (Maybe Name)
2475 | fromCharName
2476 |     = do defs <- get Ctxt
2477 |          pure $ fromCharName (primnames (options defs))
2478 |
2479 | export
2480 | fromDoubleName : {auto c : Ref Ctxt Defs} ->
2481 |                Core (Maybe Name)
2482 | fromDoubleName
2483 |     = do defs <- get Ctxt
2484 |          pure $ fromDoubleName (primnames (options defs))
2485 |
2486 | export
2487 | fromTTImpName : {auto c : Ref Ctxt Defs} ->
2488 |                 Core (Maybe Name)
2489 | fromTTImpName
2490 |     = do defs <- get Ctxt
2491 |          pure $ fromTTImpName (primnames (options defs))
2492 |
2493 | export
2494 | fromNameName : {auto c : Ref Ctxt Defs} ->
2495 |                Core (Maybe Name)
2496 | fromNameName
2497 |     = do defs <- get Ctxt
2498 |          pure $ fromNameName (primnames (options defs))
2499 |
2500 | export
2501 | fromDeclsName : {auto c : Ref Ctxt Defs} ->
2502 |                 Core (Maybe Name)
2503 | fromDeclsName
2504 |     = do defs <- get Ctxt
2505 |          pure $ fromDeclsName (primnames (options defs))
2506 |
2507 | export
2508 | getPrimNames : {auto c : Ref Ctxt Defs} -> Core PrimNames
2509 | getPrimNames = [| MkPrimNs fromIntegerName
2510 |                            fromStringName
2511 |                            fromCharName
2512 |                            fromDoubleName
2513 |                            fromTTImpName
2514 |                            fromNameName
2515 |                            fromDeclsName |]
2516 |
2517 | export
2518 | getPrimitiveNames : {auto c : Ref Ctxt Defs} -> Core (List Name)
2519 | getPrimitiveNames = primNamesToList <$> getPrimNames
2520 |
2521 | export
2522 | isPrimName : List Name -> Name -> Bool
2523 | isPrimName prims given = let (ns, nm) = splitNS given in go ns nm prims where
2524 |
2525 |   go : Namespace -> Name -> List Name -> Bool
2526 |   go ns nm [] = False
2527 |   go ns nm (p :: ps)
2528 |     = let (ns', nm') = splitNS p in
2529 |       (nm' == nm && (ns' `isApproximationOf` ns))
2530 |       || go ns nm ps
2531 |
2532 | export
2533 | addLogLevel : {auto c : Ref Ctxt Defs} ->
2534 |               Maybe LogLevel -> Core ()
2535 | addLogLevel Nothing  = update Ctxt { options->session->logEnabled := False, options->session->logLevel := defaultLogLevel }
2536 | addLogLevel (Just l) = update Ctxt { options->session->logEnabled := True, options->session->logLevel $= insertLogLevel l }
2537 |
2538 | export
2539 | setLogLevel : {auto c : Ref Ctxt Defs} ->
2540 |               LogLevel -> Core ()
2541 | setLogLevel = addLogLevel . Just
2542 |
2543 | export
2544 | stopLogging : {auto c : Ref Ctxt Defs} -> Core ()
2545 | stopLogging = addLogLevel Nothing
2546 |
2547 | export
2548 | withLogLevel : {auto c : Ref Ctxt Defs} ->
2549 |                LogLevel -> Core a -> Core a
2550 | withLogLevel l comp = do
2551 |   defs <- get Ctxt
2552 |   let logs = logLevel (session (options defs))
2553 |   put Ctxt ({ options->session->logLevel := insertLogLevel l logs } defs)
2554 |   r <- comp
2555 |   defs <- get Ctxt
2556 |   put Ctxt ({ options->session->logLevel := logs } defs)
2557 |   pure r
2558 |
2559 | export
2560 | setLogTimings : {auto c : Ref Ctxt Defs} -> Nat -> Core ()
2561 | setLogTimings n = update Ctxt { options->session->logTimings := Just n }
2562 |
2563 | export
2564 | setDebugElabCheck : {auto c : Ref Ctxt Defs} -> Bool -> Core ()
2565 | setDebugElabCheck b = update Ctxt { options->session->debugElabCheck := b }
2566 |
2567 | export
2568 | getSession : {auto c : Ref Ctxt Defs} ->
2569 |              Core Session
2570 | getSession
2571 |     = do defs <- get Ctxt
2572 |          pure (session (options defs))
2573 |
2574 | export
2575 | setSession : {auto c : Ref Ctxt Defs} -> Session -> Core ()
2576 | setSession sopts = update Ctxt { options->session := sopts }
2577 |
2578 | %inline
2579 | export
2580 | updateSession : {auto c : Ref Ctxt Defs} ->
2581 |                 (Session -> Session) -> Core ()
2582 | updateSession f = setSession (f !getSession)
2583 |
2584 | export
2585 | recordWarning : {auto c : Ref Ctxt Defs} -> Warning -> Core ()
2586 | recordWarning w = update Ctxt { warnings $= (w ::) }
2587 |
2588 | export
2589 | getTime : Core Integer
2590 | getTime
2591 |     = do clock <- coreLift (clockTime Monotonic)
2592 |          pure (seconds clock * nano + nanoseconds clock)
2593 |   where
2594 |     nano : Integer
2595 |     nano = 1000000000
2596 |
2597 | -- A simple timeout mechanism. We can start a timer, clear it, or check
2598 | -- whether too much time has passed and throw an exception if so
2599 |
2600 | ||| Initialise the timer, setting the time in milliseconds after which a
2601 | ||| timeout should be thrown.
2602 | ||| Note: It's important to clear the timer when the operation that might
2603 | ||| timeout is complete, otherwise something else might throw a timeout
2604 | ||| error!
2605 | export
2606 | startTimer : {auto c : Ref Ctxt Defs} ->
2607 |              Integer -> String -> Core ()
2608 | startTimer tmax action
2609 |     = do t <- getTime
2610 |          update Ctxt { timer := Just (t + tmax * 1000000, action) }
2611 |
2612 | ||| Clear the timer
2613 | export
2614 | clearTimer : {auto c : Ref Ctxt Defs} -> Core ()
2615 | clearTimer = update Ctxt { timer := Nothing }
2616 |
2617 | ||| If the timer was started more than t milliseconds ago, throw an exception
2618 | export
2619 | checkTimer : {auto c : Ref Ctxt Defs} ->
2620 |              Core ()
2621 | checkTimer
2622 |     = do defs <- get Ctxt
2623 |          let Just (max, action) = timer defs
2624 |                 | Nothing => pure ()
2625 |          t <- getTime
2626 |          if (t > max)
2627 |             then throw (Timeout action)
2628 |             else pure ()
2629 |
2630 | -- Update the list of imported incremental compile data, if we're in
2631 | -- incremental mode for the current CG
2632 | export
2633 | addImportedInc : {auto c : Ref Ctxt Defs} ->
2634 |                  ModuleIdent -> List (CG, String, List String) -> Core ()
2635 | addImportedInc modNS inc
2636 |     = do s <- getSession
2637 |          let cg = s.codegen
2638 |          defs <- get Ctxt
2639 |          when (cg `elem` s.incrementalCGs) $
2640 |            case lookup cg inc of
2641 |                 Nothing =>
2642 |                   -- No incremental compile data for current CG, so we can't
2643 |                   -- compile incrementally
2644 |                   do recordWarning (GenericWarn emptyFC ("No incremental compile data for " ++ show modNS))
2645 |                      defs <- get Ctxt
2646 |                      put Ctxt ({ allIncData $= drop cg } defs)
2647 |                      -- Tell session that the codegen is no longer incremental
2648 |                      when (show modNS /= "") $
2649 |                         updateSession { incrementalCGs $= (delete cg) }
2650 |                 Just (mods, extra) =>
2651 |                      put Ctxt ({ allIncData $= addMod cg (mods, extra) }
2652 |                                       defs)
2653 |   where
2654 |     addMod : CG -> (String, List String) ->
2655 |              List (CG, (List String, List String)) ->
2656 |              List (CG, (List String, List String))
2657 |     addMod cg (mod, all) [] = [(cg, ([mod], all))]
2658 |     addMod cg (mod, all) ((cg', (mods, libs)) :: xs)
2659 |         = if cg == cg'
2660 |              then ((cg, (mod :: mods, libs ++ all)) :: xs)
2661 |              else ((cg', (mods, libs)) :: addMod cg (mod, all) xs)
2662 |
2663 |     drop : CG -> List (CG, a) -> List (CG, a)
2664 |     drop cg [] = []
2665 |     drop cg ((x, v) :: xs)
2666 |         = if cg == x
2667 |              then xs
2668 |              else ((x, v) :: drop cg xs)
2669 |
2670 | export
2671 | setIncData : {auto c : Ref Ctxt Defs} ->
2672 |              CG -> (String, List String) -> Core ()
2673 | setIncData cg res = update Ctxt { incData $= ((cg, res) :: )}
2674 |
2675 | -- Set a name as Private that was previously visible (and, if 'everywhere' is
2676 | -- set, hide in any modules imported by this one)
2677 | export
2678 | hide : {auto c : Ref Ctxt Defs} ->
2679 |        FC -> Name -> Core ()
2680 | hide fc n
2681 |     = do defs <- get Ctxt
2682 |          [(nsn, _)] <- lookupCtxtName n (gamma defs)
2683 |               | res => ambiguousName fc n (map fst res)
2684 |          put Ctxt ({ gamma $= hideName nsn } defs)
2685 |
2686 | -- Set a name as Public that was previously hidden
2687 | -- Note: this is here at the bottom only becuase `recordWarning` is defined just above.
2688 | export
2689 | unhide : {auto c : Ref Ctxt Defs} ->
2690 |        FC -> Name -> Core ()
2691 | unhide fc n
2692 |     = do defs <- get Ctxt
2693 |          [(nsn, _)] <- lookupHiddenCtxtName n (gamma defs)
2694 |               | res => ambiguousName fc n (map fst res)
2695 |          put Ctxt ({ gamma $= unhideName nsn } defs)
2696 |          unless (isHidden nsn (gamma defs)) $ do
2697 |            recordWarning $ GenericWarn fc $
2698 |              "Trying to %unhide `" ++ show nsn ++ "`, which was not hidden in the first place"
2699 |