{-# LANGUAGE CPP #-}
-- Turning off DeepSubsumption for
-- SPECIALIZE mapTCMT :: (forall a. IO a -> IO a) -> TCM a -> TCM a
-- with GHC 9.14
{-# LANGUAGE NoDeepSubsumption #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE UndecidableInstances #-}

module Mikan.TypeChecking.Monad.Base
  ( module Mikan.TypeChecking.Monad.Base
  , module Mikan.TypeChecking.Monad.Base.Types
  , module X
  , module Mikan.Utils.Lens
  , HasOptions (..)
  , RecordFieldWarning
  , UselessPublicReason(..)
  ) where

import Prelude hiding (null)

import Control.Applicative hiding (empty)
import Control.Concurrent (forkIO)
import Control.DeepSeq
import Control.Exception qualified as E

import Control.Monad.Catch qualified as Catch
import Control.Monad.Except ( MonadError(..), ExceptT(..), runExceptT )
import Control.Monad.IO.Class ( MonadIO(..) )
import Control.Monad.State ( MonadState(..), modify, StateT(..), runStateT, evalStateT )
import Control.Monad.Reader ( MonadReader(..), ReaderT(..), runReaderT )
import Control.Monad.Writer ( WriterT(..), runWriterT )
import Control.Monad.Trans.Control ( MonadTransControl(..), liftThrough )
import Control.Monad.Trans.Identity ( IdentityT(..), runIdentityT )
import Control.Monad.Trans.Maybe ( MaybeT(..) )

import Control.Parallel ( pseq )

import Data.Array (Ix)
import Data.Function (on)
import Data.Bits
import Data.Word
import Data.IntMap (IntMap)
import Data.IntMap qualified as IntMap
import Data.List qualified as List
import Data.Maybe
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Sequence (Seq)
import Data.Set (Set, toList, fromList)
import Data.Set qualified as Set
import Data.HashMap.Strict (HashMap)
import Data.HashMap.Strict qualified as HMap
import Data.HashSet qualified as HashSet
import Data.Hashable
import Data.HashSet (HashSet)
import Data.String
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Short (ShortText)
import Data.Text.Short qualified as TS
import Data.Semigroup (Sum, Max)

import GHC.Generics (Generic)
import GHC.Exts (oneShot, MutVar#, RealWorld)
import GHC.IORef (IORef(..))
import GHC.STRef (STRef(..))

import System.IO (hFlush, stdout)

import Mikan.Benchmarking (Phase)

import Mikan.Compiler.Backend.Base (Backend_boot, Backend'_boot)

import Mikan.Syntax.Common
import Mikan.Syntax.Common.Pretty
import Mikan.Syntax.Common.Pretty.ANSI (putDocTreeLn)
import Mikan.Syntax.Builtin (SomeBuiltin, BuiltinId, PrimitiveId)
import Mikan.Syntax.Concrete.Attribute qualified as C
import Mikan.Syntax.Concrete qualified as C
import Mikan.Syntax.Concrete.Definitions
  (NiceDeclaration, DeclarationWarning, declarationWarningName)
import Mikan.Syntax.Abstract qualified as A
import Mikan.Syntax.Internal as I
import Mikan.Syntax.Internal.MetaVars
import Mikan.Syntax.Internal.Generic (TermLike(..))
import Mikan.Syntax.Parser.Monad (ParseError, ParseWarning, parseWarningName)
import Mikan.Syntax.TopLevelModuleName
  (RawTopLevelModuleName)
import Mikan.Syntax.Notation
import Mikan.Syntax.Position
import Mikan.Syntax.Scope.Base
import Mikan.Syntax.Info ( MetaKind(InstanceMeta, UnificationMeta), MetaNameSuggestion, MutualInfo )

import {-# SOURCE #-} Mikan.TypeChecking.Monad.Diagnostic (EncodedDiagnostic, SomeDiagnostic, internalErrorDiagnostic)
import Mikan.TypeChecking.Monad.Base.Warning qualified as W
import Mikan.TypeChecking.Monad.Base.Warning (RecordFieldWarning, UselessPublicReason(..))
import Mikan.TypeChecking.Monad.Base.Types

import Mikan.TypeChecking.CompiledClause
import Mikan.TypeChecking.Coverage.SplitTree
import Mikan.TypeChecking.Positivity.Occurrence
import Mikan.TypeChecking.Positivity.Warnings qualified as W
import Mikan.TypeChecking.Free

import Mikan.TypeChecking.DiscrimTree.Types

import Mikan.Interaction.Options
import Mikan.Interaction.Options.Errors as X
  ( CannotQuoteTerm(..)
  , NotAValidLetBinding(..)
  , NotAValidLetExpression(..)
  , NotAllowedInDotPatterns(..)
  )
import Mikan.Interaction.Options.Warnings
import Mikan.Interaction.Response.Base (Response_boot(..))
import Mikan.Interaction.Highlighting.Precise (HighlightingInfo, NameKind)
import Mikan.Interaction.Library
import Mikan.Interaction.Library.Base ( ExeMap, LibCache, LibErrors )

import Mikan.Utils.Benchmark (MonadBench(..))
import Mikan.Utils.BiMap (BiMap, HasTag(..))
import Mikan.Utils.Boolean ( fromBool, toBool )
import Mikan.Utils.CallStack ( CallStack, HasCallStack, withCallerCallStack, showIOException )
import Mikan.Utils.ExpandCase
import Mikan.Utils.FileId ( GetFileId(getFileId), GetIdFile(getIdFile) )
import Mikan.Utils.FileId as X ( FileId, MonadFileId( idFromFile, fileFromId ) )
import Mikan.Utils.Functor
import Mikan.Utils.Hash
import Mikan.Utils.IORef.Strict qualified as Strict
import Mikan.Utils.Lens
import Mikan.Utils.List
import Mikan.Utils.List1 (List1)
import Mikan.Utils.List2 (List2)
import Mikan.Utils.ListT
import Mikan.Utils.Maybe.Strict qualified as Strict
import Mikan.Utils.Monad
import Mikan.Utils.Null
import Mikan.Utils.Permutation
import Mikan.Utils.Set1 (Set1)
import Mikan.Utils.SmallSet (SmallSet, SmallSetElement)
import Mikan.Utils.SmallSet qualified as SmallSet
import Mikan.Utils.Tuple (Pair)
import Mikan.Utils.Update
import Mikan.Utils.VarSet (VarSet)
import Mikan.Utils.Atomic
import Mikan.Utils.StrictReader qualified as Strict
import Mikan.Utils.StrictWriter qualified as Strict
import Mikan.Utils.StrictState qualified as Strict
import Mikan.Utils.Tuple.Strict qualified as Strict

import Mikan.Utils.Impossible

----------------------------------------------------------------------------------------------------
-- * Type checking state
----------------------------------------------------------------------------------------------------

data TCState = TCSt
  { TCState -> PersistentTCState
stPersistentState :: !PersistentTCState
    -- ^ State which persists while we build an Agda project (same main file).
  , TCState -> PreScopeState
stPreScopeState   :: !PreScopeState
    -- ^ The state which is frozen after scope checking.
  , TCState -> PostScopeState
stPostScopeState  :: !PostScopeState
    -- ^ The state which is modified after scope checking.
  }
  deriving (forall x. TCState -> Rep TCState x)
-> (forall x. Rep TCState x -> TCState) -> Generic TCState
forall x. Rep TCState x -> TCState
forall x. TCState -> Rep TCState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TCState -> Rep TCState x
from :: forall x. TCState -> Rep TCState x
$cto :: forall x. Rep TCState x -> TCState
to :: forall x. Rep TCState x -> TCState
Generic

-- | Class for monads which offer scoped access to the 'TCState', as
-- well as read-only access to the 'SessionState'.
class Monad m => ReadTCState m where
  -- | Read the current 'TCState'.
  getTCState :: m TCState

  -- | Scoped modification of the 'TCState': run the continuation where
  -- the part of the state targeted by the lens has its value altered by
  -- the given function, without modifying the state in the "enclosing"
  -- thread.
  locallyTCState :: Lens' TCState a -> (a -> a) -> m b -> m b

  -- | Read the current 'SessionState'.
  --
  -- Since the 'SessionState' is shared between threads, it is unwise to
  -- hold onto the result of this function for very long.
  getSessionState :: m SessionState

  withTCState :: (TCState -> TCState) -> m a -> m a
  withTCState = Lens' TCState TCState -> (TCState -> TCState) -> m a -> m a
forall a b. Lens' TCState a -> (a -> a) -> m b -> m b
forall (m :: * -> *) a b.
ReadTCState m =>
Lens' TCState a -> (a -> a) -> m b -> m b
locallyTCState (TCState -> f TCState) -> TCState -> f TCState
forall a. a -> a
Lens' TCState TCState
id

  default getTCState :: (MonadTrans t, ReadTCState n, t n ~ m) => m TCState
  getTCState = n TCState -> t n TCState
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift n TCState
forall (m :: * -> *). ReadTCState m => m TCState
getTCState

  default locallyTCState
    :: (MonadTransControl t, ReadTCState n, t n ~ m)
    => Lens' TCState a -> (a -> a) -> m b -> m b
  locallyTCState Lens' TCState a
l = (n (StT t b) -> n (StT t b)) -> m b -> m b
(n (StT t b) -> n (StT t b)) -> t n b -> t n b
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a b.
(MonadTransControl t, Monad (t m), Monad m) =>
(m (StT t a) -> m (StT t b)) -> t m a -> t m b
liftThrough ((n (StT t b) -> n (StT t b)) -> m b -> m b)
-> ((a -> a) -> n (StT t b) -> n (StT t b))
-> (a -> a)
-> m b
-> m b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Lens' TCState a -> (a -> a) -> n (StT t b) -> n (StT t b)
forall a b. Lens' TCState a -> (a -> a) -> n b -> n b
forall (m :: * -> *) a b.
ReadTCState m =>
Lens' TCState a -> (a -> a) -> m b -> m b
locallyTCState (a -> f a) -> TCState -> f TCState
Lens' TCState a
l

  default getSessionState :: (MonadTrans t, ReadTCState n, t n ~ m) => m SessionState
  getSessionState = n SessionState -> t n SessionState
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift n SessionState
forall (m :: * -> *). ReadTCState m => m SessionState
getSessionState

instance ReadTCState m => ReadTCState (ListT m) where
  locallyTCState :: forall a b. Lens' TCState a -> (a -> a) -> ListT m b -> ListT m b
locallyTCState Lens' TCState a
l = (m (Maybe (b, ListT m b)) -> m (Maybe (b, ListT m b)))
-> ListT m b -> ListT m b
forall (m :: * -> *) a (n :: * -> *) b.
(m (Maybe (a, ListT m a)) -> n (Maybe (b, ListT n b)))
-> ListT m a -> ListT n b
mapListT ((m (Maybe (b, ListT m b)) -> m (Maybe (b, ListT m b)))
 -> ListT m b -> ListT m b)
-> ((a -> a)
    -> m (Maybe (b, ListT m b)) -> m (Maybe (b, ListT m b)))
-> (a -> a)
-> ListT m b
-> ListT m b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Lens' TCState a
-> (a -> a) -> m (Maybe (b, ListT m b)) -> m (Maybe (b, ListT m b))
forall a b. Lens' TCState a -> (a -> a) -> m b -> m b
forall (m :: * -> *) a b.
ReadTCState m =>
Lens' TCState a -> (a -> a) -> m b -> m b
locallyTCState (a -> f a) -> TCState -> f TCState
Lens' TCState a
l

instance ReadTCState m => ReadTCState (ChangeT m)
instance ReadTCState m => ReadTCState (ExceptT err m)
instance ReadTCState m => ReadTCState (IdentityT m)
instance ReadTCState m => ReadTCState (MaybeT m)
instance ReadTCState m => ReadTCState (ReaderT r m)
instance ReadTCState m => ReadTCState (StateT s m)
instance (Monoid w, ReadTCState m) => ReadTCState (WriterT w m)
instance ReadTCState m => ReadTCState (Strict.ReaderT r m)
instance ReadTCState m => ReadTCState (Strict.StateT s m)
instance (Monoid w, ReadTCState m) => ReadTCState (Strict.WriterT w m)

instance Show TCState where
  show :: TCState -> String
show TCState
_ = String
"TCSt{}"

type Backend = Backend_boot Definition TCM
type Backend' opts env menv mod def = Backend'_boot Definition TCM opts env menv mod def

type BackendForeignCode = Map BackendName ForeignCodeStack
type ImportedModules    = Set TopLevelModuleName

data UserWarningInfo = UserWarningInfo
  ShortText
  -- ^ The warning to display.
  C.Name
  -- ^ The original concrete name of the WARNING_ON_USAGE pragma.
  --   Only raise a warning if the concrete names match, to allow
  --   deprecating names instead of just definitions (e.g. Set).
  deriving (Int -> UserWarningInfo -> ShowS
[UserWarningInfo] -> ShowS
UserWarningInfo -> String
(Int -> UserWarningInfo -> ShowS)
-> (UserWarningInfo -> String)
-> ([UserWarningInfo] -> ShowS)
-> Show UserWarningInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> UserWarningInfo -> ShowS
showsPrec :: Int -> UserWarningInfo -> ShowS
$cshow :: UserWarningInfo -> String
show :: UserWarningInfo -> String
$cshowList :: [UserWarningInfo] -> ShowS
showList :: [UserWarningInfo] -> ShowS
Show, (forall x. UserWarningInfo -> Rep UserWarningInfo x)
-> (forall x. Rep UserWarningInfo x -> UserWarningInfo)
-> Generic UserWarningInfo
forall x. Rep UserWarningInfo x -> UserWarningInfo
forall x. UserWarningInfo -> Rep UserWarningInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. UserWarningInfo -> Rep UserWarningInfo x
from :: forall x. UserWarningInfo -> Rep UserWarningInfo x
$cto :: forall x. Rep UserWarningInfo x -> UserWarningInfo
to :: forall x. Rep UserWarningInfo x -> UserWarningInfo
Generic)

type UserWarnings = Map QName UserWarningInfo

data PreScopeState = PreScopeState
  { PreScopeState -> HighlightingInfo
stPreTokens             :: !HighlightingInfo
    -- ^ Highlighting info for tokens and Happy parser warnings (but
    -- not for those tokens/warnings for which highlighting exists in
    -- 'stPostSyntaxInfo').
  , PreScopeState -> Signature
stPreImports            :: !Signature  -- XX populated by scope checker
    -- ^ Imported declared identifiers.
    --   Those must not be serialized!
  , PreScopeState -> ImportedModules
stPreImportedModules    :: !ImportedModules
      -- Andreas, 2023-08-05, issue #6750, don't make this a 'HashSet'
      -- because then the order of its @toList@ is undefined,
      -- leading to undefined deserialization order.
    -- ^ The top-level modules imported by the current module.
  , PreScopeState -> VisitedModules
stPreVisitedModules     :: !VisitedModules   -- imports
      -- ^ Modules loaded so far.
      --   In contrast 'stDecodedModules', contains also modules that are only scope-checked.
  , PreScopeState -> ScopeInfo
stPreScope              :: !ScopeInfo
    -- generated by scope checker, current file:
    -- which modules you have, public definitions, current file, maps concrete names to abstract names.
  , PreScopeState -> PatternSynDefns
stPrePatternSyns        :: !A.PatternSynDefns
    -- ^ Pattern synonyms of the current file.  Serialized.
  , PreScopeState -> PatternSynDefns
stPrePatternSynImports  :: !A.PatternSynDefns
    -- ^ Imported pattern synonyms.  Must not be serialized!
  , PreScopeState -> Maybe (Set QName)
stPreGeneralizedVars    :: !(Strict.Maybe (Set QName))
    -- ^ Collected variables we wish to generalize over; used during scope checking of terms.
    --   If 'Nothing', we are in a position where we do not support generalization,
    --   and do not accept additions to this collection.
  , PreScopeState -> PragmaOptions
stPrePragmaOptions      :: !PragmaOptions
    -- ^ Options applying to the current file. @OPTIONS@
    -- pragmas only affect this field.
  , PreScopeState -> Map SomeBuiltin (Builtin PrimFun)
stPreImportedBuiltins   :: !BuiltinThings
  , PreScopeState -> DisplayForms
stPreImportedDisplayForms :: !DisplayForms
    -- ^ Display forms added by someone else to imported identifiers
  , PreScopeState -> InteractionId
stPreFreshInteractionId :: !InteractionId
  , PreScopeState -> UserWarnings
stPreImportedUserWarnings :: !UserWarnings
    -- ^ Imported @UserWarning@s, not to be stored in the @Interface@
  , PreScopeState -> UserWarnings
stPreLocalUserWarnings    :: !UserWarnings
    -- ^ Locally defined @UserWarning@s, to be stored in the @Interface@
  , PreScopeState -> Maybe ShortText
stPreWarningOnImport      :: !(Strict.Maybe ShortText)
    -- ^ Whether the current module should raise a warning when opened
  , PreScopeState -> Set QName
stPreImportedPartialDefs :: !(Set QName)
    -- ^ Imported partial definitions, not to be stored in the @Interface@
  , PreScopeState -> RemoteMetaStore
stPreImportedMetaStore :: !RemoteMetaStore
    -- ^ Used for meta-variables from other modules.
  , PreScopeState -> HashMap QName (ScopeCopyRef, QName)
stPreCopiedNames       :: !(HashMap A.QName (ScopeCopyRef, A.QName))
    -- ^ Associates copied names (the key) to their originals, as well
    -- as to the copies they belong.
    -- Computed by the scope checker, used to compute opaque blocks and
    -- to trim module applications.
  , PreScopeState -> HashMap QName (HashSet QName)
stPreNameCopies        :: !(HashMap A.QName (HashSet A.QName))
    -- ^ Associates an original name (the key) to all its copies (the
    -- value).
    -- Computed by the scope checker, used to compute opaque blocks.
  , PreScopeState -> UnusedImportsState
stPreUnusedImportsState :: !UnusedImportsState
    -- ^ Information collected by the scope checker to generate warnings
    -- about unused imports.
  }
  deriving (forall x. PreScopeState -> Rep PreScopeState x)
-> (forall x. Rep PreScopeState x -> PreScopeState)
-> Generic PreScopeState
forall x. Rep PreScopeState x -> PreScopeState
forall x. PreScopeState -> Rep PreScopeState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PreScopeState -> Rep PreScopeState x
from :: forall x. PreScopeState -> Rep PreScopeState x
$cto :: forall x. Rep PreScopeState x -> PreScopeState
to :: forall x. Rep PreScopeState x -> PreScopeState
Generic

-- | Name disambiguation for the sake of highlighting.
data DisambiguatedName = DisambiguatedName NameKind A.QName
  deriving (forall x. DisambiguatedName -> Rep DisambiguatedName x)
-> (forall x. Rep DisambiguatedName x -> DisambiguatedName)
-> Generic DisambiguatedName
forall x. Rep DisambiguatedName x -> DisambiguatedName
forall x. DisambiguatedName -> Rep DisambiguatedName x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. DisambiguatedName -> Rep DisambiguatedName x
from :: forall x. DisambiguatedName -> Rep DisambiguatedName x
$cto :: forall x. Rep DisambiguatedName x -> DisambiguatedName
to :: forall x. Rep DisambiguatedName x -> DisambiguatedName
Generic

-- | Name from file position of occurrence to disambiguation.
type DisambiguatedNames = IntMap DisambiguatedName
type ConcreteNames = Map Name (List1 C.Name)

data PostNamesCheckpoints = PostNamesCheckpoints {
    PostNamesCheckpoints -> ModuleCheckpoints
stPostModuleCheckpoints   :: !ModuleCheckpoints
    -- ^ For each module remember the checkpoint corresponding to the orignal
    --   context of the module parameters.
  , PostNamesCheckpoints -> CheckpointId
stPostFreshCheckpointId   :: !CheckpointId
  } deriving ((forall x. PostNamesCheckpoints -> Rep PostNamesCheckpoints x)
-> (forall x. Rep PostNamesCheckpoints x -> PostNamesCheckpoints)
-> Generic PostNamesCheckpoints
forall x. Rep PostNamesCheckpoints x -> PostNamesCheckpoints
forall x. PostNamesCheckpoints -> Rep PostNamesCheckpoints x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PostNamesCheckpoints -> Rep PostNamesCheckpoints x
from :: forall x. PostNamesCheckpoints -> Rep PostNamesCheckpoints x
$cto :: forall x. Rep PostNamesCheckpoints x -> PostNamesCheckpoints
to :: forall x. Rep PostNamesCheckpoints x -> PostNamesCheckpoints
Generic)

data PostMetaState = PostMetaState {
    PostMetaState -> MetaId
stPostFreshMetaId         :: !MetaId
  , PostMetaState -> ProblemId
stPostFreshProblemId      :: !ProblemId
  , PostMetaState -> LocalMetaStore
stPostOpenMetaStore       :: !LocalMetaStore
    -- ^ Used for open meta-variables.
  , PostMetaState -> LocalMetaStore
stPostSolvedMetaStore     :: !LocalMetaStore
    -- ^ Used for local, instantiated meta-variables.
  , PostMetaState -> Constraints
stPostAwakeConstraints    :: !Constraints
  , PostMetaState -> Constraints
stPostSleepingConstraints :: !Constraints
  , PostMetaState -> Set QName
stPostOccursCheckDefs     :: !(Set QName) -- local
    -- ^ Definitions to be considered during occurs check.
    --   Initialized to the current mutual block before the check.
    --   During occurs check, we remove definitions from this set
    --   as soon we have checked them.
  } deriving ((forall x. PostMetaState -> Rep PostMetaState x)
-> (forall x. Rep PostMetaState x -> PostMetaState)
-> Generic PostMetaState
forall x. Rep PostMetaState x -> PostMetaState
forall x. PostMetaState -> Rep PostMetaState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PostMetaState -> Rep PostMetaState x
from :: forall x. PostMetaState -> Rep PostMetaState x
$cto :: forall x. Rep PostMetaState x -> PostMetaState
to :: forall x. Rep PostMetaState x -> PostMetaState
Generic)

data PostColdState = PostColdState
  { PostColdState -> Flags64
stPostFlags               :: !Flags64
  , PostColdState -> HighlightingInfo
stPostSyntaxInfo          :: !HighlightingInfo
    -- ^ Highlighting info.
  , PostColdState -> DisambiguatedNames
stPostDisambiguatedNames  :: !DisambiguatedNames
    -- ^ Disambiguation carried out by the type checker.
    --   Maps position of first name character to disambiguated @'A.QName'@
    --   for each @'A.AmbiguousQName'@ already passed by the type checker.
  , PostColdState -> InteractionPoints
stPostInteractionPoints   :: !InteractionPoints -- scope checker first
  , PostColdState -> Signature
stPostSignature           :: !Signature
    -- ^ Declared identifiers of the current file.
    --   These will be serialized after successful type checking.
  , PostColdState -> DisplayForms
stPostImportsDisplayForms :: !DisplayForms
    -- ^ Display forms we add for imported identifiers
  , PostColdState -> BackendForeignCode
stPostForeignCode         :: !BackendForeignCode
    -- ^ @{-\# FOREIGN \#-}@ code that should be included in the compiled output.
    -- Does not include code for imported modules.
  , PostColdState -> Maybe (Pair ModuleName TopLevelModuleName)
stPostCurrentModule       :: !(Strict.Maybe (Strict.Pair ModuleName TopLevelModuleName))
    -- ^ The current module is available after it has been type
    -- checked.
  , PostColdState -> Set QName
stPostPendingInstances    :: !(Set QName)
  , PostColdState -> Set QName
stPostTemporaryInstances  :: !(Set QName)
  , PostColdState -> ConcreteNames
stPostConcreteNames       :: !ConcreteNames
    -- ^ Map keeping track of concrete names assigned to each abstract name
    --   (can be more than one name in case the first one is shadowed)
  , PostColdState -> Statistics
stPostStatistics          :: !Statistics
    -- ^ Counters to collect various statistics about meta variables etc.
    --   Only for current file.
  , PostColdState -> Set TCWarning
stPostTCWarnings          :: !(Set TCWarning)
  , PostColdState -> MutualBlocks
stPostMutualBlocks        :: !MutualBlocks
  , PostColdState -> Map SomeBuiltin (Builtin PrimFun)
stPostLocalBuiltins       :: !BuiltinThings
  , PostColdState -> MutualId
stPostFreshMutualId       :: !MutualId
  , PostColdState -> Int
stPostFreshInt            :: !Int
  , PostColdState -> NameId
stPostFreshNameId         :: !NameId
  , PostColdState -> OpaqueId
stPostFreshOpaqueId       :: !OpaqueId
  , PostColdState -> Set QName
stPostLocalPartialDefs    :: !(Set QName)
    -- ^ Local partial definitions, to be stored in the @Interface@
  , PostColdState -> Map OpaqueId OpaqueBlock
stPostOpaqueBlocks        :: !(Map OpaqueId OpaqueBlock)
    -- ^ Associates opaque identifiers to their actual blocks.
  , PostColdState -> Map QName OpaqueId
stPostOpaqueIds           :: !(Map QName OpaqueId)
    -- ^ Associates each opaque QName to the block it was defined in.
  } deriving ((forall x. PostColdState -> Rep PostColdState x)
-> (forall x. Rep PostColdState x -> PostColdState)
-> Generic PostColdState
forall x. Rep PostColdState x -> PostColdState
forall x. PostColdState -> Rep PostColdState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PostColdState -> Rep PostColdState x
from :: forall x. PostColdState -> Rep PostColdState x
$cto :: forall x. Rep PostColdState x -> PostColdState
to :: forall x. Rep PostColdState x -> PostColdState
Generic)

-- Flags
----------------------------------------------------------------------------------------------------

-- ^ Dirty when a constraint is added, used to prevent pointer update.
-- Currently unused.
{-# INLINE stPostDirty #-}
stPostDirty :: Lens' Flags64 Bool
stPostDirty :: Lens' Flags64 Bool
stPostDirty = Int -> Lens' Flags64 Bool
mkFlag Int
0

{-# INLINE stPostAreWeCaching #-}
stPostAreWeCaching :: Lens' Flags64 Bool
stPostAreWeCaching :: Lens' Flags64 Bool
stPostAreWeCaching = Int -> Lens' Flags64 Bool
mkFlag Int
1

{-# INLINE stPostPostponeInstanceSearch #-}
stPostPostponeInstanceSearch :: Lens' Flags64 Bool
stPostPostponeInstanceSearch :: Lens' Flags64 Bool
stPostPostponeInstanceSearch = Int -> Lens' Flags64 Bool
mkFlag Int
2

{-# INLINE stPostConsideringInstance #-}
stPostConsideringInstance :: Lens' Flags64 Bool
stPostConsideringInstance :: Lens' Flags64 Bool
stPostConsideringInstance = Int -> Lens' Flags64 Bool
mkFlag Int
3

-- | Should we instantiate away blocking metas?
--   This can produce ill-typed terms but they are often more readable. See issue #3606.
--   Best set to True only for calls to pretty*/reify to limit unwanted reductions.
{-# INLINE stPostInstantiateBlocking #-}
stPostInstantiateBlocking :: Lens' Flags64 Bool
stPostInstantiateBlocking :: Lens' Flags64 Bool
stPostInstantiateBlocking = Int -> Lens' Flags64 Bool
mkFlag Int
4

{-# INLINE stPostInstanceHack #-}
-- ^ Is this a context where we should always try every possible
-- instance candidate? Used to support "inert improvement", see
-- @shouldBlockOverlap@ in InstanceArguments.
stPostInstanceHack :: Lens' Flags64 Bool
stPostInstanceHack :: Lens' Flags64 Bool
stPostInstanceHack = Int -> Lens' Flags64 Bool
mkFlag Int
5

----------------------------------------------------------------------------------------------------

data PostScopeState = PostScopeState {
    PostScopeState -> PostNamesCheckpoints
stPostNamesCheckpoints :: !PostNamesCheckpoints
  , PostScopeState -> PostMetaState
stPostMetaState        :: !PostMetaState
  , PostScopeState -> PostColdState
stPostColdState        :: !PostColdState
  } deriving ((forall x. PostScopeState -> Rep PostScopeState x)
-> (forall x. Rep PostScopeState x -> PostScopeState)
-> Generic PostScopeState
forall x. Rep PostScopeState x -> PostScopeState
forall x. PostScopeState -> Rep PostScopeState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PostScopeState -> Rep PostScopeState x
from :: forall x. PostScopeState -> Rep PostScopeState x
$cto :: forall x. Rep PostScopeState x -> PostScopeState
to :: forall x. Rep PostScopeState x -> PostScopeState
Generic)

-- | A part of the state that grows monotonically over the whole Agda session.
-- Shared between all threads, and never reset.
data SessionState = SessionState
  { SessionState -> [Backend]
stSessionBackends :: [Backend]
    -- ^ Backends with their options.

  , SessionState -> FileDictWithBuiltins
stSessionFileDict :: !FileDictWithBuiltins
    -- ^ Map file names to unique 'FileId' and back.
    --   Assuming we do not see terribly many different files during one Agda session,
    --   this map needs not be garbage-collected.
    --
    --   Also informs about whether a 'FileId' belongs to one of
    --   Agda's primitive and builtin modules.

  , SessionState -> ModuleToSourceId
stSessionModuleToSourceId :: !ModuleToSourceId
    -- ^ Maps 'TopLevelModuleNames' to the 'FileId's from which they
    -- were loaded.

  , SessionState -> InteractionOutputCallback
stSessionInteractionOutputCallback :: InteractionOutputCallback
    -- ^ Callback function to call when there is a response to give to
    -- the interactive frontend.
    --
    -- See the documentation of 'InteractionOutputCallback'. Set by
    -- the interactor (Terminal (default), Emacs, JSON), remaining
    -- fixed throughout the session.

  , SessionState -> LibCache
stSessionLibCache :: !LibCache
    -- ^ Cached state of the library system: the project configurations,
    -- the locations of @.agda-lib@ files, and the paths where interface
    -- files should be stored.

  , SessionState -> ReadFileCache
stSessionReadFiles :: !ReadFileCache
    -- ^ Cache for file reads and hashing.
  }
  deriving ((forall x. SessionState -> Rep SessionState x)
-> (forall x. Rep SessionState x -> SessionState)
-> Generic SessionState
forall x. Rep SessionState x -> SessionState
forall x. SessionState -> Rep SessionState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. SessionState -> Rep SessionState x
from :: forall x. SessionState -> Rep SessionState x
$cto :: forall x. Rep SessionState x -> SessionState
to :: forall x. Rep SessionState x -> SessionState
Generic)

-- | A part of the state which is not reverted when an error is thrown
-- or the state is reset.
data PersistentTCState = PersistentTCSt
  { PersistentTCState -> Atomic SessionState
stPersistentSession :: !(Atomic SessionState)
    -- ^ State that persists for the whole Agda session.
    --   Grows monotonically, never sees any deletion.
  , PersistentTCState -> VisitedModules
stDecodedModules    :: !DecodedModules
      -- ^ Type-checked modules we visited during our Agda session.
      --   A module gets dropped from this list if its source
      --   or the source of any of its dependencies changed,
      --   or when its identity or the identity of one of its dependencies changed
      --   due to a change of the include paths.
  , PersistentTCState -> BiMap RawTopLevelModuleName ModuleNameHash
stPersistentTopLevelModuleNames ::
      !(BiMap RawTopLevelModuleName ModuleNameHash)
    -- ^ Module name hashes for top-level module names (and vice
    -- versa).
  , PersistentTCState -> CommandLineOptions
stPersistentOptions :: CommandLineOptions
  , PersistentTCState -> Statistics
stAccumStatistics   :: !Statistics
    -- ^ Should be strict field.
  , PersistentTCState -> Maybe LoadedFileCache
stPersistLoadedFileCache :: !(Strict.Maybe LoadedFileCache)
    -- ^ Cached typechecking state from the last loaded file.
    --   Should be @Nothing@ when checking imports.
  }
  deriving (forall x. PersistentTCState -> Rep PersistentTCState x)
-> (forall x. Rep PersistentTCState x -> PersistentTCState)
-> Generic PersistentTCState
forall x. Rep PersistentTCState x -> PersistentTCState
forall x. PersistentTCState -> Rep PersistentTCState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PersistentTCState -> Rep PersistentTCState x
from :: forall x. PersistentTCState -> Rep PersistentTCState x
$cto :: forall x. Rep PersistentTCState x -> PersistentTCState
to :: forall x. Rep PersistentTCState x -> PersistentTCState
Generic

data LoadedFileCache = LoadedFileCache
  { LoadedFileCache -> CachedTypeCheckLog
lfcCached  :: !CachedTypeCheckLog
  , LoadedFileCache -> CachedTypeCheckLog
lfcCurrent :: !CurrentTypeCheckLog
  }
  deriving (forall x. LoadedFileCache -> Rep LoadedFileCache x)
-> (forall x. Rep LoadedFileCache x -> LoadedFileCache)
-> Generic LoadedFileCache
forall x. Rep LoadedFileCache x -> LoadedFileCache
forall x. LoadedFileCache -> Rep LoadedFileCache x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. LoadedFileCache -> Rep LoadedFileCache x
from :: forall x. LoadedFileCache -> Rep LoadedFileCache x
$cto :: forall x. Rep LoadedFileCache x -> LoadedFileCache
to :: forall x. Rep LoadedFileCache x -> LoadedFileCache
Generic

-- | A log of what the type checker does and states after the action is
-- completed.  The cached version is stored first executed action first.
type CachedTypeCheckLog = [(TypeCheckAction, PostScopeState)]

-- | Like 'CachedTypeCheckLog', but storing the log for an ongoing type
-- checking of a module.  Stored in reverse order (last performed action
-- first).
type CurrentTypeCheckLog = [(TypeCheckAction, PostScopeState)]

-- | A complete log for a module will look like this:
--
--   * 'Pragmas'
--
--   * 'EnterSection', entering the main module.
--
--   * 'Decl'\/'EnterSection'\/'LeaveSection', for declarations and nested
--     modules
--
--   * 'LeaveSection', leaving the main module.
--
data TypeCheckAction
  = EnterSection !ModuleName !A.Telescope
  | LeaveSection !ModuleName
  | Decl !A.Declaration
    -- ^ Never a Section or ScopeDecl
  | Pragmas !PragmaOptions
  deriving ((forall x. TypeCheckAction -> Rep TypeCheckAction x)
-> (forall x. Rep TypeCheckAction x -> TypeCheckAction)
-> Generic TypeCheckAction
forall x. Rep TypeCheckAction x -> TypeCheckAction
forall x. TypeCheckAction -> Rep TypeCheckAction x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TypeCheckAction -> Rep TypeCheckAction x
from :: forall x. TypeCheckAction -> Rep TypeCheckAction x
$cto :: forall x. Rep TypeCheckAction x -> TypeCheckAction
to :: forall x. Rep TypeCheckAction x -> TypeCheckAction
Generic)


-- | Empty session state.

initFileDict :: AbsolutePath -> FileDictWithBuiltins
initFileDict :: AbsolutePath -> FileDictWithBuiltins
initFileDict AbsolutePath
primLibDir = FileDictBuilder
-> BuiltinModuleIds -> AbsolutePath -> FileDictWithBuiltins
FileDictWithBuiltins FileDictBuilder
forall a. Null a => a
empty BuiltinModuleIds
forall a. Null a => a
empty AbsolutePath
primLibDir

initSessionState :: AbsolutePath -> SessionState
initSessionState :: AbsolutePath -> SessionState
initSessionState AbsolutePath
primLibDir = SessionState
  { stSessionFileDict :: FileDictWithBuiltins
stSessionFileDict                  = AbsolutePath -> FileDictWithBuiltins
initFileDict AbsolutePath
primLibDir
  , stSessionBackends :: [Backend]
stSessionBackends                  = [Backend]
forall a. Null a => a
empty
  , stSessionModuleToSourceId :: ModuleToSourceId
stSessionModuleToSourceId          = ModuleToSourceId
forall a. Null a => a
empty
  , stSessionInteractionOutputCallback :: InteractionOutputCallback
stSessionInteractionOutputCallback = InteractionOutputCallback
defaultInteractionOutputCallback
  , stSessionLibCache :: LibCache
stSessionLibCache                  = LibCache
forall a. Null a => a
empty
  , stSessionReadFiles :: ReadFileCache
stSessionReadFiles                 = ReadFileCache
forall a. Null a => a
empty
  }

-- | Empty persistent state.

initPersistentStateFromSessionState :: Atomic SessionState -> PersistentTCState
initPersistentStateFromSessionState :: Atomic SessionState -> PersistentTCState
initPersistentStateFromSessionState Atomic SessionState
s = PersistentTCSt
  { stPersistentSession :: Atomic SessionState
stPersistentSession             = Atomic SessionState
s
  , stPersistentOptions :: CommandLineOptions
stPersistentOptions             = CommandLineOptions
defaultOptions
  , stPersistentTopLevelModuleNames :: BiMap RawTopLevelModuleName ModuleNameHash
stPersistentTopLevelModuleNames = BiMap RawTopLevelModuleName ModuleNameHash
forall a. Null a => a
empty
  , stDecodedModules :: VisitedModules
stDecodedModules                = VisitedModules
forall k a. Map k a
Map.empty
  , stAccumStatistics :: Statistics
stAccumStatistics               = Statistics
forall a. Null a => a
empty
  , stPersistLoadedFileCache :: Maybe LoadedFileCache
stPersistLoadedFileCache        = Maybe LoadedFileCache
forall a. Null a => a
empty
  }

-- | An initial 'MetaId'.

initialMetaId :: MetaId
initialMetaId :: MetaId
initialMetaId = MetaId
  { metaId :: Word64
metaId     = Word64
0
  , metaModule :: ModuleNameHash
metaModule = ModuleNameHash
noModuleNameHash
  }

-- | Empty state of type checker.

initPreScopeState :: PreScopeState
initPreScopeState :: PreScopeState
initPreScopeState = PreScopeState
  { stPreTokens :: HighlightingInfo
stPreTokens               = HighlightingInfo
forall a. Monoid a => a
mempty
  , stPreImports :: Signature
stPreImports              = Signature
emptySignature
  , stPreImportedModules :: ImportedModules
stPreImportedModules      = ImportedModules
forall a. Null a => a
empty
  , stPreVisitedModules :: VisitedModules
stPreVisitedModules       = VisitedModules
forall k a. Map k a
Map.empty
  , stPreScope :: ScopeInfo
stPreScope                = ScopeInfo
emptyScopeInfo
  , stPrePatternSyns :: PatternSynDefns
stPrePatternSyns          = PatternSynDefns
forall k a. Map k a
Map.empty
  , stPrePatternSynImports :: PatternSynDefns
stPrePatternSynImports    = PatternSynDefns
forall k a. Map k a
Map.empty
  , stPreGeneralizedVars :: Maybe (Set QName)
stPreGeneralizedVars      = Maybe (Set QName)
forall a. Monoid a => a
mempty
  , stPrePragmaOptions :: PragmaOptions
stPrePragmaOptions        = PragmaOptions
defaultInteractionOptions
  , stPreImportedBuiltins :: Map SomeBuiltin (Builtin PrimFun)
stPreImportedBuiltins     = Map SomeBuiltin (Builtin PrimFun)
forall k a. Map k a
Map.empty
  , stPreImportedDisplayForms :: DisplayForms
stPreImportedDisplayForms = DisplayForms
forall k v. HashMap k v
HMap.empty
  , stPreFreshInteractionId :: InteractionId
stPreFreshInteractionId   = InteractionId
0
  , stPreImportedUserWarnings :: UserWarnings
stPreImportedUserWarnings = UserWarnings
forall k a. Map k a
Map.empty
  , stPreLocalUserWarnings :: UserWarnings
stPreLocalUserWarnings    = UserWarnings
forall k a. Map k a
Map.empty
  , stPreWarningOnImport :: Maybe ShortText
stPreWarningOnImport      = Maybe ShortText
forall a. Null a => a
empty
  , stPreImportedPartialDefs :: Set QName
stPreImportedPartialDefs  = Set QName
forall a. Set a
Set.empty
  , stPreImportedMetaStore :: RemoteMetaStore
stPreImportedMetaStore    = RemoteMetaStore
forall k v. HashMap k v
HMap.empty
  , stPreCopiedNames :: HashMap QName (ScopeCopyRef, QName)
stPreCopiedNames          = HashMap QName (ScopeCopyRef, QName)
forall k v. HashMap k v
HMap.empty
  , stPreNameCopies :: HashMap QName (HashSet QName)
stPreNameCopies           = HashMap QName (HashSet QName)
forall k v. HashMap k v
HMap.empty
  , stPreUnusedImportsState :: UnusedImportsState
stPreUnusedImportsState   = UnusedImportsState
forall a. Null a => a
empty
  }


initPostNamesCheckpoints :: PostNamesCheckpoints
initPostNamesCheckpoints :: PostNamesCheckpoints
initPostNamesCheckpoints = PostNamesCheckpoints
  { stPostModuleCheckpoints :: ModuleCheckpoints
stPostModuleCheckpoints      = ModuleCheckpoints
ModuleCheckpointsTop
  , stPostFreshCheckpointId :: CheckpointId
stPostFreshCheckpointId      = CheckpointId
1
  }

initPostMetaState :: PostMetaState
initPostMetaState :: PostMetaState
initPostMetaState = PostMetaState
  { stPostFreshMetaId :: MetaId
stPostFreshMetaId            = MetaId
initialMetaId
  , stPostFreshProblemId :: ProblemId
stPostFreshProblemId         = ProblemId
1
  , stPostOpenMetaStore :: LocalMetaStore
stPostOpenMetaStore          = LocalMetaStore
forall k a. Map k a
Map.empty
  , stPostSolvedMetaStore :: LocalMetaStore
stPostSolvedMetaStore        = LocalMetaStore
forall k a. Map k a
Map.empty
  , stPostAwakeConstraints :: Constraints
stPostAwakeConstraints       = []
  , stPostSleepingConstraints :: Constraints
stPostSleepingConstraints    = []
  , stPostOccursCheckDefs :: Set QName
stPostOccursCheckDefs        = Set QName
forall a. Set a
Set.empty
  }

initPostFlags :: Flags64
initPostFlags :: Flags64
initPostFlags = Word64 -> Flags64
Flags64 Word64
0
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
stPostDirty                  ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
stPostAreWeCaching           ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
stPostPostponeInstanceSearch ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
stPostConsideringInstance    ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
stPostInstantiateBlocking    ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
stPostInstanceHack           ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False

initPostColdState :: PostColdState
initPostColdState :: PostColdState
initPostColdState = PostColdState
  { stPostFlags :: Flags64
stPostFlags                  = Flags64
initPostFlags
  , stPostSyntaxInfo :: HighlightingInfo
stPostSyntaxInfo             = HighlightingInfo
forall a. Monoid a => a
mempty
  , stPostDisambiguatedNames :: DisambiguatedNames
stPostDisambiguatedNames     = DisambiguatedNames
forall a. IntMap a
IntMap.empty
  , stPostInteractionPoints :: InteractionPoints
stPostInteractionPoints      = InteractionPoints
forall a. Null a => a
empty
  , stPostSignature :: Signature
stPostSignature              = Signature
emptySignature
  , stPostImportsDisplayForms :: DisplayForms
stPostImportsDisplayForms    = DisplayForms
forall k v. HashMap k v
HMap.empty
  , stPostCurrentModule :: Maybe (Pair ModuleName TopLevelModuleName)
stPostCurrentModule          = Maybe (Pair ModuleName TopLevelModuleName)
forall a. Null a => a
empty
  , stPostPendingInstances :: Set QName
stPostPendingInstances       = Set QName
forall a. Set a
Set.empty
  , stPostTemporaryInstances :: Set QName
stPostTemporaryInstances     = Set QName
forall a. Set a
Set.empty
  , stPostConcreteNames :: ConcreteNames
stPostConcreteNames          = ConcreteNames
forall k a. Map k a
Map.empty
  , stPostStatistics :: Statistics
stPostStatistics             = Statistics
forall a. Null a => a
empty
  , stPostTCWarnings :: Set TCWarning
stPostTCWarnings             = Set TCWarning
forall a. Null a => a
empty
  , stPostMutualBlocks :: MutualBlocks
stPostMutualBlocks           = MutualBlocks
forall a. Null a => a
empty
  , stPostLocalBuiltins :: Map SomeBuiltin (Builtin PrimFun)
stPostLocalBuiltins          = Map SomeBuiltin (Builtin PrimFun)
forall k a. Map k a
Map.empty
  , stPostFreshMutualId :: MutualId
stPostFreshMutualId          = MutualId
0
  , stPostFreshInt :: Int
stPostFreshInt               = Int
0
  , stPostFreshNameId :: NameId
stPostFreshNameId            = Word64 -> ModuleNameHash -> NameId
NameId Word64
0 ModuleNameHash
noModuleNameHash
  , stPostFreshOpaqueId :: OpaqueId
stPostFreshOpaqueId          = Word64 -> ModuleNameHash -> OpaqueId
OpaqueId Word64
0 ModuleNameHash
noModuleNameHash
  , stPostLocalPartialDefs :: Set QName
stPostLocalPartialDefs       = Set QName
forall a. Set a
Set.empty
  , stPostOpaqueBlocks :: Map OpaqueId OpaqueBlock
stPostOpaqueBlocks           = Map OpaqueId OpaqueBlock
forall k a. Map k a
Map.empty
  , stPostOpaqueIds :: Map QName OpaqueId
stPostOpaqueIds              = Map QName OpaqueId
forall k a. Map k a
Map.empty
  , stPostForeignCode :: BackendForeignCode
stPostForeignCode            = BackendForeignCode
forall k a. Map k a
Map.empty
  }

initPostScopeState :: PostScopeState
initPostScopeState :: PostScopeState
initPostScopeState = PostScopeState
  { stPostNamesCheckpoints :: PostNamesCheckpoints
stPostNamesCheckpoints = PostNamesCheckpoints
initPostNamesCheckpoints
  , stPostMetaState :: PostMetaState
stPostMetaState        = PostMetaState
initPostMetaState
  , stPostColdState :: PostColdState
stPostColdState        = PostColdState
initPostColdState
  }

initStateIO :: IO TCState
initStateIO :: IO TCState
initStateIO = AbsolutePath -> IO TCState
initState (AbsolutePath -> IO TCState) -> IO AbsolutePath -> IO TCState
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< IO AbsolutePath
getPrimitiveLibDir

initState :: AbsolutePath -> IO TCState
initState :: AbsolutePath -> IO TCState
initState AbsolutePath
fp = Atomic SessionState -> TCState
initStateFromSessionState (Atomic SessionState -> TCState)
-> IO (Atomic SessionState) -> IO TCState
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SessionState -> IO (Atomic SessionState)
forall (m :: * -> *) a. MonadIO m => a -> m (Atomic a)
newAtomic (AbsolutePath -> SessionState
initSessionState AbsolutePath
fp)

initStateFromSessionState :: Atomic SessionState -> TCState
initStateFromSessionState :: Atomic SessionState -> TCState
initStateFromSessionState = PersistentTCState -> TCState
initStateFromPersistentState (PersistentTCState -> TCState)
-> (Atomic SessionState -> PersistentTCState)
-> Atomic SessionState
-> TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Atomic SessionState -> PersistentTCState
initPersistentStateFromSessionState

initStateFromPersistentState :: PersistentTCState -> TCState
initStateFromPersistentState :: PersistentTCState -> TCState
initStateFromPersistentState PersistentTCState
s = TCSt
  { stPersistentState :: PersistentTCState
stPersistentState = PersistentTCState
s
  , stPreScopeState :: PreScopeState
stPreScopeState   = PreScopeState
initPreScopeState
  , stPostScopeState :: PostScopeState
stPostScopeState  = PostScopeState
initPostScopeState
  }

-- * Lenses for 'TCState'

-- ** Components of 'TCState'

{-# INLINE lensPersistentState #-}
lensPersistentState :: Lens' TCState PersistentTCState
lensPersistentState :: Lens' TCState PersistentTCState
lensPersistentState = \PersistentTCState -> f PersistentTCState
f TCState
s -> PersistentTCState -> f PersistentTCState
f (TCState -> PersistentTCState
stPersistentState TCState
s) f PersistentTCState -> (PersistentTCState -> TCState) -> f TCState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ PersistentTCState
x -> TCState
s { stPersistentState = x }

{-# INLINE lensPreScopeState #-}
lensPreScopeState :: Lens' TCState PreScopeState
lensPreScopeState :: Lens' TCState PreScopeState
lensPreScopeState = \PreScopeState -> f PreScopeState
f TCState
s -> PreScopeState -> f PreScopeState
f (TCState -> PreScopeState
stPreScopeState TCState
s) f PreScopeState -> (PreScopeState -> TCState) -> f TCState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ PreScopeState
x -> TCState
s { stPreScopeState = x }

{-# INLINE lensPostScopeState #-}
lensPostScopeState :: Lens' TCState PostScopeState
lensPostScopeState :: Lens' TCState PostScopeState
lensPostScopeState = \PostScopeState -> f PostScopeState
f TCState
s -> PostScopeState -> f PostScopeState
f (TCState -> PostScopeState
stPostScopeState TCState
s) f PostScopeState -> (PostScopeState -> TCState) -> f TCState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ PostScopeState
x -> TCState
s { stPostScopeState = x }

-- ** Components of 'SessionState'

lensBackends :: Lens' SessionState [Backend]
lensBackends :: Lens' SessionState [Backend]
lensBackends [Backend] -> f [Backend]
f SessionState
s = [Backend] -> f [Backend]
f (SessionState -> [Backend]
stSessionBackends SessionState
s) f [Backend] -> ([Backend] -> SessionState) -> f SessionState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ [Backend]
x -> SessionState
s { stSessionBackends = x }

lensFileDict :: Lens' SessionState FileDictWithBuiltins
lensFileDict :: Lens' SessionState FileDictWithBuiltins
lensFileDict FileDictWithBuiltins -> f FileDictWithBuiltins
f SessionState
s = FileDictWithBuiltins -> f FileDictWithBuiltins
f (SessionState -> FileDictWithBuiltins
stSessionFileDict SessionState
s) f FileDictWithBuiltins
-> (FileDictWithBuiltins -> SessionState) -> f SessionState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ FileDictWithBuiltins
x -> SessionState
s { stSessionFileDict = x }

lensModuleToSourceId :: Lens' SessionState ModuleToSourceId
lensModuleToSourceId :: Lens' SessionState ModuleToSourceId
lensModuleToSourceId ModuleToSourceId -> f ModuleToSourceId
f SessionState
s = ModuleToSourceId -> f ModuleToSourceId
f (SessionState -> ModuleToSourceId
stSessionModuleToSourceId SessionState
s) f ModuleToSourceId
-> (ModuleToSourceId -> SessionState) -> f SessionState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ModuleToSourceId
x -> SessionState
s { stSessionModuleToSourceId = x }

lensFileDictBuilder :: Lens' SessionState FileDictBuilder
lensFileDictBuilder :: Lens' SessionState FileDictBuilder
lensFileDictBuilder = (FileDictWithBuiltins -> f FileDictWithBuiltins)
-> SessionState -> f SessionState
Lens' SessionState FileDictWithBuiltins
lensFileDict ((FileDictWithBuiltins -> f FileDictWithBuiltins)
 -> SessionState -> f SessionState)
-> ((FileDictBuilder -> f FileDictBuilder)
    -> FileDictWithBuiltins -> f FileDictWithBuiltins)
-> (FileDictBuilder -> f FileDictBuilder)
-> SessionState
-> f SessionState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FileDictBuilder -> f FileDictBuilder)
-> FileDictWithBuiltins -> f FileDictWithBuiltins
Lens' FileDictWithBuiltins FileDictBuilder
lensFileDictFileDictBuilder

lensBuiltinModuleIds :: Lens' SessionState BuiltinModuleIds
lensBuiltinModuleIds :: Lens' SessionState BuiltinModuleIds
lensBuiltinModuleIds = (FileDictWithBuiltins -> f FileDictWithBuiltins)
-> SessionState -> f SessionState
Lens' SessionState FileDictWithBuiltins
lensFileDict ((FileDictWithBuiltins -> f FileDictWithBuiltins)
 -> SessionState -> f SessionState)
-> ((BuiltinModuleIds -> f BuiltinModuleIds)
    -> FileDictWithBuiltins -> f FileDictWithBuiltins)
-> (BuiltinModuleIds -> f BuiltinModuleIds)
-> SessionState
-> f SessionState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (BuiltinModuleIds -> f BuiltinModuleIds)
-> FileDictWithBuiltins -> f FileDictWithBuiltins
Lens' FileDictWithBuiltins BuiltinModuleIds
lensFileDictBuiltinModuleIds

lensPrimitiveLibDir :: Lens' SessionState PrimitiveLibDir
lensPrimitiveLibDir :: Lens' SessionState AbsolutePath
lensPrimitiveLibDir = (FileDictWithBuiltins -> f FileDictWithBuiltins)
-> SessionState -> f SessionState
Lens' SessionState FileDictWithBuiltins
lensFileDict ((FileDictWithBuiltins -> f FileDictWithBuiltins)
 -> SessionState -> f SessionState)
-> ((AbsolutePath -> f AbsolutePath)
    -> FileDictWithBuiltins -> f FileDictWithBuiltins)
-> (AbsolutePath -> f AbsolutePath)
-> SessionState
-> f SessionState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AbsolutePath -> f AbsolutePath)
-> FileDictWithBuiltins -> f FileDictWithBuiltins
Lens' FileDictWithBuiltins AbsolutePath
lensFileDictPrimitiveLibDir

lensInteractionOutputCallback :: Lens' SessionState InteractionOutputCallback
lensInteractionOutputCallback :: Lens' SessionState InteractionOutputCallback
lensInteractionOutputCallback InteractionOutputCallback -> f InteractionOutputCallback
f SessionState
s = InteractionOutputCallback -> f InteractionOutputCallback
f (SessionState -> InteractionOutputCallback
stSessionInteractionOutputCallback SessionState
s) f InteractionOutputCallback
-> (InteractionOutputCallback -> SessionState) -> f SessionState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ InteractionOutputCallback
x -> SessionState
s { stSessionInteractionOutputCallback = x }

lensLibCache :: Lens' SessionState LibCache
lensLibCache :: Lens' SessionState LibCache
lensLibCache LibCache -> f LibCache
f SessionState
s = LibCache -> f LibCache
f (SessionState -> LibCache
stSessionLibCache SessionState
s) f LibCache -> (LibCache -> SessionState) -> f SessionState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \LibCache
x -> SessionState
s { stSessionLibCache = x }

lensReadFileCache :: Lens' SessionState ReadFileCache
lensReadFileCache :: Lens' SessionState ReadFileCache
lensReadFileCache ReadFileCache -> f ReadFileCache
f SessionState
s = ReadFileCache -> f ReadFileCache
f (SessionState -> ReadFileCache
stSessionReadFiles SessionState
s) f ReadFileCache
-> (ReadFileCache -> SessionState) -> f SessionState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ReadFileCache
x -> SessionState
s { stSessionReadFiles = x }

-- ** Components of 'PersistentTCState'

lensPersistentSession :: Lens' PersistentTCState (Atomic SessionState)
lensPersistentSession :: Lens' PersistentTCState (Atomic SessionState)
lensPersistentSession Atomic SessionState -> f (Atomic SessionState)
f PersistentTCState
s = Atomic SessionState -> f (Atomic SessionState)
f (PersistentTCState -> Atomic SessionState
stPersistentSession PersistentTCState
s) f (Atomic SessionState)
-> (Atomic SessionState -> PersistentTCState)
-> f PersistentTCState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Atomic SessionState
x -> PersistentTCState
s { stPersistentSession = x }

lensLoadedFileCache :: Lens' PersistentTCState (Strict.Maybe LoadedFileCache)
lensLoadedFileCache :: Lens' PersistentTCState (Maybe LoadedFileCache)
lensLoadedFileCache Maybe LoadedFileCache -> f (Maybe LoadedFileCache)
f PersistentTCState
s = Maybe LoadedFileCache -> f (Maybe LoadedFileCache)
f (PersistentTCState -> Maybe LoadedFileCache
stPersistLoadedFileCache PersistentTCState
s) f (Maybe LoadedFileCache)
-> (Maybe LoadedFileCache -> PersistentTCState)
-> f PersistentTCState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Maybe LoadedFileCache
x -> PersistentTCState
s { stPersistLoadedFileCache = x }

lensTopLevelModuleNames :: Lens' PersistentTCState (BiMap RawTopLevelModuleName ModuleNameHash)
lensTopLevelModuleNames :: Lens'
  PersistentTCState (BiMap RawTopLevelModuleName ModuleNameHash)
lensTopLevelModuleNames BiMap RawTopLevelModuleName ModuleNameHash
-> f (BiMap RawTopLevelModuleName ModuleNameHash)
f PersistentTCState
s =
  BiMap RawTopLevelModuleName ModuleNameHash
-> f (BiMap RawTopLevelModuleName ModuleNameHash)
f (PersistentTCState -> BiMap RawTopLevelModuleName ModuleNameHash
stPersistentTopLevelModuleNames PersistentTCState
s) f (BiMap RawTopLevelModuleName ModuleNameHash)
-> (BiMap RawTopLevelModuleName ModuleNameHash
    -> PersistentTCState)
-> f PersistentTCState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ BiMap RawTopLevelModuleName ModuleNameHash
x -> PersistentTCState
s { stPersistentTopLevelModuleNames = x }

-- ** Components of 'PreScopeState'

lensPreTokens :: Lens' PreScopeState HighlightingInfo
lensPreTokens :: Lens' PreScopeState HighlightingInfo
lensPreTokens HighlightingInfo -> f HighlightingInfo
f PreScopeState
s = HighlightingInfo -> f HighlightingInfo
f (PreScopeState -> HighlightingInfo
stPreTokens PreScopeState
s) f HighlightingInfo
-> (HighlightingInfo -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ HighlightingInfo
x -> PreScopeState
s { stPreTokens = x }

lensImports :: Lens' PreScopeState Signature
lensImports :: Lens' PreScopeState Signature
lensImports Signature -> f Signature
f PreScopeState
s = Signature -> f Signature
f (PreScopeState -> Signature
stPreImports PreScopeState
s) f Signature -> (Signature -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Signature
x -> PreScopeState
s { stPreImports = x }

lensImportedModules :: Lens' PreScopeState ImportedModules
lensImportedModules :: Lens' PreScopeState ImportedModules
lensImportedModules ImportedModules -> f ImportedModules
f PreScopeState
s = ImportedModules -> f ImportedModules
f (PreScopeState -> ImportedModules
stPreImportedModules PreScopeState
s) f ImportedModules
-> (ImportedModules -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ImportedModules
x -> PreScopeState
s { stPreImportedModules = x }

lensVisitedModules :: Lens' PreScopeState VisitedModules
lensVisitedModules :: Lens' PreScopeState VisitedModules
lensVisitedModules VisitedModules -> f VisitedModules
f PreScopeState
s = VisitedModules -> f VisitedModules
f (PreScopeState -> VisitedModules
stPreVisitedModules PreScopeState
s ) f VisitedModules
-> (VisitedModules -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ VisitedModules
x -> PreScopeState
s { stPreVisitedModules = x }

lensScope :: Lens' PreScopeState ScopeInfo
lensScope :: Lens' PreScopeState ScopeInfo
lensScope ScopeInfo -> f ScopeInfo
f PreScopeState
s = ScopeInfo -> f ScopeInfo
f (PreScopeState -> ScopeInfo
stPreScope PreScopeState
s ) f ScopeInfo -> (ScopeInfo -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ScopeInfo
x -> PreScopeState
s { stPreScope = x }

lensPatternSyns :: Lens' PreScopeState A.PatternSynDefns
lensPatternSyns :: Lens' PreScopeState PatternSynDefns
lensPatternSyns PatternSynDefns -> f PatternSynDefns
f PreScopeState
s = PatternSynDefns -> f PatternSynDefns
f (PreScopeState -> PatternSynDefns
stPrePatternSyns PreScopeState
s ) f PatternSynDefns
-> (PatternSynDefns -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ PatternSynDefns
x -> PreScopeState
s { stPrePatternSyns = x }

lensPatternSynImports :: Lens' PreScopeState A.PatternSynDefns
lensPatternSynImports :: Lens' PreScopeState PatternSynDefns
lensPatternSynImports PatternSynDefns -> f PatternSynDefns
f PreScopeState
s = PatternSynDefns -> f PatternSynDefns
f (PreScopeState -> PatternSynDefns
stPrePatternSynImports PreScopeState
s ) f PatternSynDefns
-> (PatternSynDefns -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ PatternSynDefns
x -> PreScopeState
s { stPrePatternSynImports = x }

lensGeneralizedVars :: Lens' PreScopeState (Strict.Maybe (Set QName))
lensGeneralizedVars :: Lens' PreScopeState (Maybe (Set QName))
lensGeneralizedVars Maybe (Set QName) -> f (Maybe (Set QName))
f PreScopeState
s = Maybe (Set QName) -> f (Maybe (Set QName))
f (PreScopeState -> Maybe (Set QName)
stPreGeneralizedVars PreScopeState
s ) f (Maybe (Set QName))
-> (Maybe (Set QName) -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Maybe (Set QName)
x -> PreScopeState
s { stPreGeneralizedVars = x }

instance LensPragmaOptions PreScopeState where
  {-# INLINE lensPragmaOptions #-}
  lensPragmaOptions :: Lens' PreScopeState PragmaOptions
lensPragmaOptions = \PragmaOptions -> f PragmaOptions
f PreScopeState
s -> PragmaOptions -> f PragmaOptions
f (PreScopeState -> PragmaOptions
stPrePragmaOptions PreScopeState
s ) f PragmaOptions
-> (PragmaOptions -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ PragmaOptions
x -> PreScopeState
s { stPrePragmaOptions = x }

lensImportedBuiltins :: Lens' PreScopeState BuiltinThings
lensImportedBuiltins :: Lens' PreScopeState (Map SomeBuiltin (Builtin PrimFun))
lensImportedBuiltins Map SomeBuiltin (Builtin PrimFun)
-> f (Map SomeBuiltin (Builtin PrimFun))
f PreScopeState
s = Map SomeBuiltin (Builtin PrimFun)
-> f (Map SomeBuiltin (Builtin PrimFun))
f (PreScopeState -> Map SomeBuiltin (Builtin PrimFun)
stPreImportedBuiltins PreScopeState
s ) f (Map SomeBuiltin (Builtin PrimFun))
-> (Map SomeBuiltin (Builtin PrimFun) -> PreScopeState)
-> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Map SomeBuiltin (Builtin PrimFun)
x -> PreScopeState
s { stPreImportedBuiltins = x }

lensFreshInteractionId :: Lens' PreScopeState InteractionId
lensFreshInteractionId :: Lens' PreScopeState InteractionId
lensFreshInteractionId InteractionId -> f InteractionId
f PreScopeState
s = InteractionId -> f InteractionId
f (PreScopeState -> InteractionId
stPreFreshInteractionId PreScopeState
s ) f InteractionId
-> (InteractionId -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ InteractionId
x -> PreScopeState
s { stPreFreshInteractionId = x }

lensImportedUserWarnings :: Lens' PreScopeState UserWarnings
lensImportedUserWarnings :: Lens' PreScopeState UserWarnings
lensImportedUserWarnings UserWarnings -> f UserWarnings
f PreScopeState
s = UserWarnings -> f UserWarnings
f (PreScopeState -> UserWarnings
stPreImportedUserWarnings PreScopeState
s ) f UserWarnings
-> (UserWarnings -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ UserWarnings
x -> PreScopeState
s { stPreImportedUserWarnings = x }

lensLocalUserWarnings :: Lens' PreScopeState UserWarnings
lensLocalUserWarnings :: Lens' PreScopeState UserWarnings
lensLocalUserWarnings UserWarnings -> f UserWarnings
f PreScopeState
s = UserWarnings -> f UserWarnings
f (PreScopeState -> UserWarnings
stPreLocalUserWarnings PreScopeState
s ) f UserWarnings
-> (UserWarnings -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ UserWarnings
x -> PreScopeState
s { stPreLocalUserWarnings = x }

lensWarningOnImport :: Lens' PreScopeState (Strict.Maybe ShortText)
lensWarningOnImport :: Lens' PreScopeState (Maybe ShortText)
lensWarningOnImport Maybe ShortText -> f (Maybe ShortText)
f PreScopeState
s = Maybe ShortText -> f (Maybe ShortText)
f (PreScopeState -> Maybe ShortText
stPreWarningOnImport PreScopeState
s) f (Maybe ShortText)
-> (Maybe ShortText -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Maybe ShortText
x -> PreScopeState
s { stPreWarningOnImport = x }

lensImportedPartialDefs :: Lens' PreScopeState (Set QName)
lensImportedPartialDefs :: Lens' PreScopeState (Set QName)
lensImportedPartialDefs Set QName -> f (Set QName)
f PreScopeState
s = Set QName -> f (Set QName)
f (PreScopeState -> Set QName
stPreImportedPartialDefs PreScopeState
s) f (Set QName) -> (Set QName -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Set QName
x -> PreScopeState
s { stPreImportedPartialDefs = x }

lensImportedMetaStore :: Lens' PreScopeState RemoteMetaStore
lensImportedMetaStore :: Lens' PreScopeState RemoteMetaStore
lensImportedMetaStore RemoteMetaStore -> f RemoteMetaStore
f PreScopeState
s = RemoteMetaStore -> f RemoteMetaStore
f (PreScopeState -> RemoteMetaStore
stPreImportedMetaStore PreScopeState
s) f RemoteMetaStore
-> (RemoteMetaStore -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \RemoteMetaStore
x -> PreScopeState
s { stPreImportedMetaStore = x }

lensCopiedNames :: Lens' PreScopeState (HashMap QName (ScopeCopyRef, QName))
lensCopiedNames :: Lens' PreScopeState (HashMap QName (ScopeCopyRef, QName))
lensCopiedNames HashMap QName (ScopeCopyRef, QName)
-> f (HashMap QName (ScopeCopyRef, QName))
f PreScopeState
s = HashMap QName (ScopeCopyRef, QName)
-> f (HashMap QName (ScopeCopyRef, QName))
f (PreScopeState -> HashMap QName (ScopeCopyRef, QName)
stPreCopiedNames PreScopeState
s) f (HashMap QName (ScopeCopyRef, QName))
-> (HashMap QName (ScopeCopyRef, QName) -> PreScopeState)
-> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ HashMap QName (ScopeCopyRef, QName)
x -> PreScopeState
s { stPreCopiedNames = x }

lensNameCopies :: Lens' PreScopeState (HashMap QName (HashSet QName))
lensNameCopies :: Lens' PreScopeState (HashMap QName (HashSet QName))
lensNameCopies HashMap QName (HashSet QName) -> f (HashMap QName (HashSet QName))
f PreScopeState
s = HashMap QName (HashSet QName) -> f (HashMap QName (HashSet QName))
f (PreScopeState -> HashMap QName (HashSet QName)
stPreNameCopies PreScopeState
s) f (HashMap QName (HashSet QName))
-> (HashMap QName (HashSet QName) -> PreScopeState)
-> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ HashMap QName (HashSet QName)
x -> PreScopeState
s { stPreNameCopies = x }

lensUnusedImportsState :: Lens' PreScopeState UnusedImportsState
lensUnusedImportsState :: Lens' PreScopeState UnusedImportsState
lensUnusedImportsState UnusedImportsState -> f UnusedImportsState
f PreScopeState
s = UnusedImportsState -> f UnusedImportsState
f (PreScopeState -> UnusedImportsState
stPreUnusedImportsState PreScopeState
s) f UnusedImportsState
-> (UnusedImportsState -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !UnusedImportsState
x -> PreScopeState
s { stPreUnusedImportsState = x }

{-# INLINE lensImportedDisplayForms #-}
lensImportedDisplayForms :: Lens' PreScopeState DisplayForms
lensImportedDisplayForms :: Lens' PreScopeState DisplayForms
lensImportedDisplayForms = \DisplayForms -> f DisplayForms
f PreScopeState
s -> DisplayForms -> f DisplayForms
f (PreScopeState -> DisplayForms
stPreImportedDisplayForms PreScopeState
s) f DisplayForms
-> (DisplayForms -> PreScopeState) -> f PreScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ DisplayForms
x -> PreScopeState
s {stPreImportedDisplayForms = x}


-- ** Components of PostScopeState

{-# INLINE lensCurrentModule #-}
lensCurrentModule :: Lens' PostScopeState (Strict.Maybe (Strict.Pair ModuleName TopLevelModuleName))
lensCurrentModule :: Lens' PostScopeState (Maybe (Pair ModuleName TopLevelModuleName))
lensCurrentModule = \Maybe (Pair ModuleName TopLevelModuleName)
-> f (Maybe (Pair ModuleName TopLevelModuleName))
f PostScopeState
s ->
  Maybe (Pair ModuleName TopLevelModuleName)
-> f (Maybe (Pair ModuleName TopLevelModuleName))
f (PostColdState -> Maybe (Pair ModuleName TopLevelModuleName)
stPostCurrentModule (PostColdState -> Maybe (Pair ModuleName TopLevelModuleName))
-> PostColdState -> Maybe (Pair ModuleName TopLevelModuleName)
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f (Maybe (Pair ModuleName TopLevelModuleName))
-> (Maybe (Pair ModuleName TopLevelModuleName) -> PostScopeState)
-> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Maybe (Pair ModuleName TopLevelModuleName)
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostCurrentModule = x}}

{-# INLINE lensForeignCode #-}
lensForeignCode :: Lens' PostScopeState BackendForeignCode
lensForeignCode :: Lens' PostScopeState BackendForeignCode
lensForeignCode = \BackendForeignCode -> f BackendForeignCode
f PostScopeState
s ->
  BackendForeignCode -> f BackendForeignCode
f (PostColdState -> BackendForeignCode
stPostForeignCode (PostColdState -> BackendForeignCode)
-> PostColdState -> BackendForeignCode
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f BackendForeignCode
-> (BackendForeignCode -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ BackendForeignCode
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostForeignCode = x}}

{-# INLINE lensLocalPartialDefs #-}
lensLocalPartialDefs :: Lens' PostScopeState (Set QName)
lensLocalPartialDefs :: Lens' PostScopeState (Set QName)
lensLocalPartialDefs = \Set QName -> f (Set QName)
f PostScopeState
s ->
  Set QName -> f (Set QName)
f (PostColdState -> Set QName
stPostLocalPartialDefs (PostColdState -> Set QName) -> PostColdState -> Set QName
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f (Set QName) -> (Set QName -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Set QName
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostLocalPartialDefs = x}}

{-# INLINE lensFreshNameId #-}
lensFreshNameId :: Lens' PostScopeState NameId
lensFreshNameId :: Lens' PostScopeState NameId
lensFreshNameId = \NameId -> f NameId
f PostScopeState
s ->
  NameId -> f NameId
f (PostColdState -> NameId
stPostFreshNameId (PostColdState -> NameId) -> PostColdState -> NameId
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f NameId -> (NameId -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ NameId
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostFreshNameId = x}}

{-# INLINE lensFreshOpaqueId #-}
lensFreshOpaqueId :: Lens' PostScopeState OpaqueId
lensFreshOpaqueId :: Lens' PostScopeState OpaqueId
lensFreshOpaqueId = \OpaqueId -> f OpaqueId
f PostScopeState
s ->
  OpaqueId -> f OpaqueId
f (PostColdState -> OpaqueId
stPostFreshOpaqueId (PostColdState -> OpaqueId) -> PostColdState -> OpaqueId
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f OpaqueId -> (OpaqueId -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ OpaqueId
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostFreshOpaqueId = x}}

{-# INLINE lensOpaqueBlocks #-}
lensOpaqueBlocks :: Lens' PostScopeState (Map OpaqueId OpaqueBlock)
lensOpaqueBlocks :: Lens' PostScopeState (Map OpaqueId OpaqueBlock)
lensOpaqueBlocks = \Map OpaqueId OpaqueBlock -> f (Map OpaqueId OpaqueBlock)
f PostScopeState
s ->
  Map OpaqueId OpaqueBlock -> f (Map OpaqueId OpaqueBlock)
f (PostColdState -> Map OpaqueId OpaqueBlock
stPostOpaqueBlocks (PostColdState -> Map OpaqueId OpaqueBlock)
-> PostColdState -> Map OpaqueId OpaqueBlock
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f (Map OpaqueId OpaqueBlock)
-> (Map OpaqueId OpaqueBlock -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Map OpaqueId OpaqueBlock
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostOpaqueBlocks = x}}

{-# INLINE lensOpaqueIds #-}
lensOpaqueIds :: Lens' PostScopeState (Map QName OpaqueId)
lensOpaqueIds :: Lens' PostScopeState (Map QName OpaqueId)
lensOpaqueIds = \Map QName OpaqueId -> f (Map QName OpaqueId)
f PostScopeState
s ->
  Map QName OpaqueId -> f (Map QName OpaqueId)
f (PostColdState -> Map QName OpaqueId
stPostOpaqueIds (PostColdState -> Map QName OpaqueId)
-> PostColdState -> Map QName OpaqueId
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f (Map QName OpaqueId)
-> (Map QName OpaqueId -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Map QName OpaqueId
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostOpaqueIds = x}}

{-# INLINE lensSyntaxInfo #-}
lensSyntaxInfo :: Lens' PostScopeState HighlightingInfo
lensSyntaxInfo :: Lens' PostScopeState HighlightingInfo
lensSyntaxInfo = \HighlightingInfo -> f HighlightingInfo
f PostScopeState
s ->
  HighlightingInfo -> f HighlightingInfo
f (PostColdState -> HighlightingInfo
stPostSyntaxInfo (PostColdState -> HighlightingInfo)
-> PostColdState -> HighlightingInfo
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f HighlightingInfo
-> (HighlightingInfo -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ HighlightingInfo
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostSyntaxInfo = x}}

{-# INLINE lensDisambiguatedNames #-}
lensDisambiguatedNames :: Lens' PostScopeState DisambiguatedNames
lensDisambiguatedNames :: Lens' PostScopeState DisambiguatedNames
lensDisambiguatedNames = \DisambiguatedNames -> f DisambiguatedNames
f PostScopeState
s ->
  DisambiguatedNames -> f DisambiguatedNames
f (PostColdState -> DisambiguatedNames
stPostDisambiguatedNames (PostColdState -> DisambiguatedNames)
-> PostColdState -> DisambiguatedNames
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f DisambiguatedNames
-> (DisambiguatedNames -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ DisambiguatedNames
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostDisambiguatedNames = x}}

{-# INLINE lensOpenMetaStore #-}
lensOpenMetaStore :: Lens' PostScopeState LocalMetaStore
lensOpenMetaStore :: Lens' PostScopeState LocalMetaStore
lensOpenMetaStore = \LocalMetaStore -> f LocalMetaStore
f PostScopeState
s ->
  LocalMetaStore -> f LocalMetaStore
f (PostMetaState -> LocalMetaStore
stPostOpenMetaStore (PostMetaState -> LocalMetaStore)
-> PostMetaState -> LocalMetaStore
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostMetaState
stPostMetaState PostScopeState
s) f LocalMetaStore
-> (LocalMetaStore -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ LocalMetaStore
x -> PostScopeState
s { stPostMetaState = (stPostMetaState s) {stPostOpenMetaStore = x}}

{-# INLINE lensSolvedMetaStore #-}
lensSolvedMetaStore :: Lens' PostScopeState LocalMetaStore
lensSolvedMetaStore :: Lens' PostScopeState LocalMetaStore
lensSolvedMetaStore = \LocalMetaStore -> f LocalMetaStore
f PostScopeState
s ->
  LocalMetaStore -> f LocalMetaStore
f (PostMetaState -> LocalMetaStore
stPostSolvedMetaStore (PostMetaState -> LocalMetaStore)
-> PostMetaState -> LocalMetaStore
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostMetaState
stPostMetaState PostScopeState
s) f LocalMetaStore
-> (LocalMetaStore -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ LocalMetaStore
x -> PostScopeState
s { stPostMetaState = (stPostMetaState s) {stPostSolvedMetaStore = x}}

{-# INLINE lensInteractionPoints #-}
lensInteractionPoints :: Lens' PostScopeState InteractionPoints
lensInteractionPoints :: Lens' PostScopeState InteractionPoints
lensInteractionPoints = \InteractionPoints -> f InteractionPoints
f PostScopeState
s ->
  InteractionPoints -> f InteractionPoints
f (PostColdState -> InteractionPoints
stPostInteractionPoints (PostColdState -> InteractionPoints)
-> PostColdState -> InteractionPoints
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f InteractionPoints
-> (InteractionPoints -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ InteractionPoints
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostInteractionPoints = x}}

{-# INLINE lensAwakeConstraints #-}
lensAwakeConstraints :: Lens' PostScopeState Constraints
lensAwakeConstraints :: Lens' PostScopeState Constraints
lensAwakeConstraints = \Constraints -> f Constraints
f PostScopeState
s ->
  Constraints -> f Constraints
f (PostMetaState -> Constraints
stPostAwakeConstraints (PostMetaState -> Constraints) -> PostMetaState -> Constraints
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostMetaState
stPostMetaState PostScopeState
s) f Constraints
-> (Constraints -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Constraints
x -> PostScopeState
s { stPostMetaState = (stPostMetaState s) {stPostAwakeConstraints = x}}

{-# INLINE lensSleepingConstraints #-}
lensSleepingConstraints :: Lens' PostScopeState Constraints
lensSleepingConstraints :: Lens' PostScopeState Constraints
lensSleepingConstraints = \Constraints -> f Constraints
f PostScopeState
s ->
  Constraints -> f Constraints
f (PostMetaState -> Constraints
stPostSleepingConstraints (PostMetaState -> Constraints) -> PostMetaState -> Constraints
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostMetaState
stPostMetaState PostScopeState
s) f Constraints
-> (Constraints -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Constraints
x -> PostScopeState
s { stPostMetaState = (stPostMetaState s) {stPostSleepingConstraints = x}}

{-# INLINE lensOccursCheckDefs #-}
lensOccursCheckDefs :: Lens' PostScopeState (Set QName)
lensOccursCheckDefs :: Lens' PostScopeState (Set QName)
lensOccursCheckDefs = \Set QName -> f (Set QName)
f PostScopeState
s ->
  Set QName -> f (Set QName)
f (PostMetaState -> Set QName
stPostOccursCheckDefs (PostMetaState -> Set QName) -> PostMetaState -> Set QName
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostMetaState
stPostMetaState PostScopeState
s) f (Set QName) -> (Set QName -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Set QName
x -> PostScopeState
s { stPostMetaState = (stPostMetaState s) {stPostOccursCheckDefs = x}}

{-# INLINE lensSignature #-}
lensSignature :: Lens' PostScopeState Signature
lensSignature :: Lens' PostScopeState Signature
lensSignature = \Signature -> f Signature
f PostScopeState
s ->
  Signature -> f Signature
f (PostColdState -> Signature
stPostSignature (PostColdState -> Signature) -> PostColdState -> Signature
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f Signature -> (Signature -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Signature
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostSignature = x}}

{-# INLINE lensModuleCheckpoints #-}
lensModuleCheckpoints :: Lens' PostScopeState ModuleCheckpoints
lensModuleCheckpoints :: Lens' PostScopeState ModuleCheckpoints
lensModuleCheckpoints = \ModuleCheckpoints -> f ModuleCheckpoints
f PostScopeState
s ->
  ModuleCheckpoints -> f ModuleCheckpoints
f (PostNamesCheckpoints -> ModuleCheckpoints
stPostModuleCheckpoints (PostNamesCheckpoints -> ModuleCheckpoints)
-> PostNamesCheckpoints -> ModuleCheckpoints
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostNamesCheckpoints
stPostNamesCheckpoints PostScopeState
s) f ModuleCheckpoints
-> (ModuleCheckpoints -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ModuleCheckpoints
x -> PostScopeState
s { stPostNamesCheckpoints = (stPostNamesCheckpoints s) {stPostModuleCheckpoints = x}}

{-# INLINE lensImportsDisplayForms #-}
lensImportsDisplayForms :: Lens' PostScopeState DisplayForms
lensImportsDisplayForms :: Lens' PostScopeState DisplayForms
lensImportsDisplayForms = \DisplayForms -> f DisplayForms
f PostScopeState
s ->
  DisplayForms -> f DisplayForms
f (PostColdState -> DisplayForms
stPostImportsDisplayForms (PostColdState -> DisplayForms) -> PostColdState -> DisplayForms
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f DisplayForms
-> (DisplayForms -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ DisplayForms
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostImportsDisplayForms = x}}

{-# INLINE lensTemporaryInstances #-}
lensTemporaryInstances :: Lens' PostScopeState (Set QName)
lensTemporaryInstances :: Lens' PostScopeState (Set QName)
lensTemporaryInstances = \Set QName -> f (Set QName)
f PostScopeState
s ->
  Set QName -> f (Set QName)
f (PostColdState -> Set QName
stPostTemporaryInstances (PostColdState -> Set QName) -> PostColdState -> Set QName
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f (Set QName) -> (Set QName -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Set QName
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostTemporaryInstances = x}}

{-# INLINE lensConcreteNames #-}
lensConcreteNames :: Lens' PostScopeState ConcreteNames
lensConcreteNames :: Lens' PostScopeState ConcreteNames
lensConcreteNames = \ConcreteNames -> f ConcreteNames
f PostScopeState
s ->
  ConcreteNames -> f ConcreteNames
f (PostColdState -> ConcreteNames
stPostConcreteNames (PostColdState -> ConcreteNames) -> PostColdState -> ConcreteNames
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f ConcreteNames
-> (ConcreteNames -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ConcreteNames
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostConcreteNames = x}}

{-# INLINE lensStatistics #-}
lensStatistics :: Lens' PostScopeState Statistics
lensStatistics :: Lens' PostScopeState Statistics
lensStatistics = \Statistics -> f Statistics
f PostScopeState
s ->
  Statistics -> f Statistics
f (PostColdState -> Statistics
stPostStatistics (PostColdState -> Statistics) -> PostColdState -> Statistics
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f Statistics -> (Statistics -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Statistics
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostStatistics = x}}

{-# INLINE lensTCWarnings #-}
lensTCWarnings :: Lens' PostScopeState (Set TCWarning)
lensTCWarnings :: Lens' PostScopeState (Set TCWarning)
lensTCWarnings = \Set TCWarning -> f (Set TCWarning)
f PostScopeState
s ->
  Set TCWarning -> f (Set TCWarning)
f (PostColdState -> Set TCWarning
stPostTCWarnings (PostColdState -> Set TCWarning) -> PostColdState -> Set TCWarning
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f (Set TCWarning)
-> (Set TCWarning -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Set TCWarning
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostTCWarnings = x}}

{-# INLINE lensMutualBlocks #-}
lensMutualBlocks :: Lens' PostScopeState MutualBlocks
lensMutualBlocks :: Lens' PostScopeState MutualBlocks
lensMutualBlocks = \MutualBlocks -> f MutualBlocks
f PostScopeState
s ->
  MutualBlocks -> f MutualBlocks
f (PostColdState -> MutualBlocks
stPostMutualBlocks (PostColdState -> MutualBlocks) -> PostColdState -> MutualBlocks
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f MutualBlocks
-> (MutualBlocks -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ MutualBlocks
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostMutualBlocks = x}}

{-# INLINE lensLocalBuiltins #-}
lensLocalBuiltins :: Lens' PostScopeState BuiltinThings
lensLocalBuiltins :: Lens' PostScopeState (Map SomeBuiltin (Builtin PrimFun))
lensLocalBuiltins = \Map SomeBuiltin (Builtin PrimFun)
-> f (Map SomeBuiltin (Builtin PrimFun))
f PostScopeState
s ->
  Map SomeBuiltin (Builtin PrimFun)
-> f (Map SomeBuiltin (Builtin PrimFun))
f (PostColdState -> Map SomeBuiltin (Builtin PrimFun)
stPostLocalBuiltins (PostColdState -> Map SomeBuiltin (Builtin PrimFun))
-> PostColdState -> Map SomeBuiltin (Builtin PrimFun)
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f (Map SomeBuiltin (Builtin PrimFun))
-> (Map SomeBuiltin (Builtin PrimFun) -> PostScopeState)
-> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Map SomeBuiltin (Builtin PrimFun)
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostLocalBuiltins = x}}

{-# INLINE lensFreshMetaId #-}
lensFreshMetaId :: Lens' PostScopeState MetaId
lensFreshMetaId :: Lens' PostScopeState MetaId
lensFreshMetaId = \MetaId -> f MetaId
f PostScopeState
s ->
  MetaId -> f MetaId
f (PostMetaState -> MetaId
stPostFreshMetaId (PostMetaState -> MetaId) -> PostMetaState -> MetaId
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostMetaState
stPostMetaState PostScopeState
s) f MetaId -> (MetaId -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ MetaId
x -> PostScopeState
s { stPostMetaState = (stPostMetaState s) {stPostFreshMetaId = x}}

{-# INLINE lensFreshMutualId #-}
lensFreshMutualId :: Lens' PostScopeState MutualId
lensFreshMutualId :: Lens' PostScopeState MutualId
lensFreshMutualId = \MutualId -> f MutualId
f PostScopeState
s ->
  MutualId -> f MutualId
f (PostColdState -> MutualId
stPostFreshMutualId (PostColdState -> MutualId) -> PostColdState -> MutualId
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f MutualId -> (MutualId -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ MutualId
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostFreshMutualId = x}}

{-# INLINE lensFreshProblemId #-}
lensFreshProblemId :: Lens' PostScopeState ProblemId
lensFreshProblemId :: Lens' PostScopeState ProblemId
lensFreshProblemId = \ProblemId -> f ProblemId
f PostScopeState
s ->
  ProblemId -> f ProblemId
f (PostMetaState -> ProblemId
stPostFreshProblemId (PostMetaState -> ProblemId) -> PostMetaState -> ProblemId
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostMetaState
stPostMetaState PostScopeState
s) f ProblemId -> (ProblemId -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ProblemId
x -> PostScopeState
s { stPostMetaState = (stPostMetaState s) {stPostFreshProblemId = x}}

{-# INLINE lensFreshCheckpointId #-}
lensFreshCheckpointId :: Lens' PostScopeState CheckpointId
lensFreshCheckpointId :: Lens' PostScopeState CheckpointId
lensFreshCheckpointId = \CheckpointId -> f CheckpointId
f PostScopeState
s ->
  CheckpointId -> f CheckpointId
f (PostNamesCheckpoints -> CheckpointId
stPostFreshCheckpointId (PostNamesCheckpoints -> CheckpointId)
-> PostNamesCheckpoints -> CheckpointId
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostNamesCheckpoints
stPostNamesCheckpoints PostScopeState
s) f CheckpointId
-> (CheckpointId -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ CheckpointId
x -> PostScopeState
s { stPostNamesCheckpoints = (stPostNamesCheckpoints s) {stPostFreshCheckpointId = x}}

{-# INLINE lensFreshInt #-}
lensFreshInt :: Lens' PostScopeState Int
lensFreshInt :: Lens' PostScopeState Int
lensFreshInt = \Int -> f Int
f PostScopeState
s ->
  Int -> f Int
f (PostColdState -> Int
stPostFreshInt (PostColdState -> Int) -> PostColdState -> Int
forall a b. (a -> b) -> a -> b
$ PostScopeState -> PostColdState
stPostColdState PostScopeState
s) f Int -> (Int -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Int
x -> PostScopeState
s { stPostColdState = (stPostColdState s) {stPostFreshInt = x}}


-- Flags
----------------------------------------------------------------------------------------------------

{-# INLINE mkPostFlag #-}
mkPostFlag :: Int -> Lens' PostScopeState Bool
mkPostFlag :: Int -> Lens' PostScopeState Bool
mkPostFlag Int
i = \Bool -> f Bool
f PostScopeState
s ->
  let old :: Bool
old = Int -> Flags64 -> Bool
getFlag Int
i (PostColdState -> Flags64
stPostFlags (PostScopeState -> PostColdState
stPostColdState PostScopeState
s)) in
  Bool -> f Bool
f Bool
old f Bool -> (Bool -> PostScopeState) -> f PostScopeState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \Bool
b ->
    -- avoiding copy on unchanged flags
    if Bool
b Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
old then PostScopeState
s else
      PostScopeState
s {stPostColdState = (stPostColdState s) {
       stPostFlags = setFlag i b (stPostFlags (stPostColdState s))}}

-- ^ Dirty when a constraint is added, used to prevent pointer update.
-- Currently unused.
{-# INLINE lensDirty #-}
lensDirty :: Lens' PostScopeState Bool
lensDirty :: Lens' PostScopeState Bool
lensDirty = Int -> Lens' PostScopeState Bool
mkPostFlag Int
0

{-# INLINE lensAreWeCaching #-}
lensAreWeCaching :: Lens' PostScopeState Bool
lensAreWeCaching :: Lens' PostScopeState Bool
lensAreWeCaching = Int -> Lens' PostScopeState Bool
mkPostFlag Int
1

{-# INLINE lensPostponeInstanceSearch #-}
lensPostponeInstanceSearch :: Lens' PostScopeState Bool
lensPostponeInstanceSearch :: Lens' PostScopeState Bool
lensPostponeInstanceSearch = Int -> Lens' PostScopeState Bool
mkPostFlag Int
2

{-# INLINE lensConsideringInstance #-}
lensConsideringInstance :: Lens' PostScopeState Bool
lensConsideringInstance :: Lens' PostScopeState Bool
lensConsideringInstance = Int -> Lens' PostScopeState Bool
mkPostFlag Int
3

-- | Should we instantiate away blocking metas?
--   This can produce ill-typed terms but they are often more readable. See issue #3606.
--   Best set to True only for calls to pretty*/reify to limit unwanted reductions.
{-# INLINE lensInstantiateBlocking #-}
lensInstantiateBlocking :: Lens' PostScopeState Bool
lensInstantiateBlocking :: Lens' PostScopeState Bool
lensInstantiateBlocking = Int -> Lens' PostScopeState Bool
mkPostFlag Int
4

{-# INLINE lensInstanceHack #-}
-- ^ Is this a context where we should always try every possible
-- instance candidate? Used to support "inert improvement", see
-- @shouldBlockOverlap@ in InstanceArguments.
lensInstanceHack :: Lens' PostScopeState Bool
lensInstanceHack :: Lens' PostScopeState Bool
lensInstanceHack = Int -> Lens' PostScopeState Bool
mkPostFlag Int
5


-- * @st@-prefixed lenses
------------------------------------------------------------------------

-- ** Persistent state

stLoadedFileCache :: Lens' TCState (Maybe LoadedFileCache)
stLoadedFileCache :: Lens' TCState (Maybe LoadedFileCache)
stLoadedFileCache = (PersistentTCState -> f PersistentTCState) -> TCState -> f TCState
Lens' TCState PersistentTCState
lensPersistentState ((PersistentTCState -> f PersistentTCState)
 -> TCState -> f TCState)
-> ((Maybe LoadedFileCache -> f (Maybe LoadedFileCache))
    -> PersistentTCState -> f PersistentTCState)
-> (Maybe LoadedFileCache -> f (Maybe LoadedFileCache))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe LoadedFileCache -> f (Maybe LoadedFileCache))
-> PersistentTCState -> f PersistentTCState
Lens' PersistentTCState (Maybe LoadedFileCache)
lensLoadedFileCache ((Maybe LoadedFileCache -> f (Maybe LoadedFileCache))
 -> PersistentTCState -> f PersistentTCState)
-> ((Maybe LoadedFileCache -> f (Maybe LoadedFileCache))
    -> Maybe LoadedFileCache -> f (Maybe LoadedFileCache))
-> (Maybe LoadedFileCache -> f (Maybe LoadedFileCache))
-> PersistentTCState
-> f PersistentTCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe LoadedFileCache -> f (Maybe LoadedFileCache))
-> Maybe LoadedFileCache -> f (Maybe LoadedFileCache)
forall a (p :: * -> * -> *) (f :: * -> *).
(Profunctor p, Functor f) =>
p (Maybe a) (f (Maybe a)) -> p (Maybe a) (f (Maybe a))
Strict.isoMaybeLazy

stTopLevelModuleNames :: Lens' TCState (BiMap RawTopLevelModuleName ModuleNameHash)
stTopLevelModuleNames :: Lens' TCState (BiMap RawTopLevelModuleName ModuleNameHash)
stTopLevelModuleNames = (PersistentTCState -> f PersistentTCState) -> TCState -> f TCState
Lens' TCState PersistentTCState
lensPersistentState ((PersistentTCState -> f PersistentTCState)
 -> TCState -> f TCState)
-> ((BiMap RawTopLevelModuleName ModuleNameHash
     -> f (BiMap RawTopLevelModuleName ModuleNameHash))
    -> PersistentTCState -> f PersistentTCState)
-> (BiMap RawTopLevelModuleName ModuleNameHash
    -> f (BiMap RawTopLevelModuleName ModuleNameHash))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (BiMap RawTopLevelModuleName ModuleNameHash
 -> f (BiMap RawTopLevelModuleName ModuleNameHash))
-> PersistentTCState -> f PersistentTCState
Lens'
  PersistentTCState (BiMap RawTopLevelModuleName ModuleNameHash)
lensTopLevelModuleNames

-- ** Pre scope state

stTokens :: Lens' TCState HighlightingInfo
stTokens :: Lens' TCState HighlightingInfo
stTokens = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((HighlightingInfo -> f HighlightingInfo)
    -> PreScopeState -> f PreScopeState)
-> (HighlightingInfo -> f HighlightingInfo)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (HighlightingInfo -> f HighlightingInfo)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState HighlightingInfo
lensPreTokens

stImports :: Lens' TCState Signature
stImports :: Lens' TCState Signature
stImports = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((Signature -> f Signature) -> PreScopeState -> f PreScopeState)
-> (Signature -> f Signature)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Signature -> f Signature) -> PreScopeState -> f PreScopeState
Lens' PreScopeState Signature
lensImports

stImportedModules :: Lens' TCState ImportedModules
stImportedModules :: Lens' TCState ImportedModules
stImportedModules = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((ImportedModules -> f ImportedModules)
    -> PreScopeState -> f PreScopeState)
-> (ImportedModules -> f ImportedModules)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ImportedModules -> f ImportedModules)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState ImportedModules
lensImportedModules

lensModuleToSource :: Lens' SessionState ModuleToSource
lensModuleToSource :: Lens' SessionState ModuleToSource
lensModuleToSource = ALens' SessionState FileDictWithBuiltins
-> ALens' SessionState ModuleToSourceId
-> Lens' SessionState (FileDictWithBuiltins, ModuleToSourceId)
forall s a b. ALens' s a -> ALens' s b -> Lens' s (a, b)
lensProduct ALens' SessionState FileDictWithBuiltins
Lens' SessionState FileDictWithBuiltins
lensFileDict ALens' SessionState ModuleToSourceId
Lens' SessionState ModuleToSourceId
lensModuleToSourceId (((FileDictWithBuiltins, ModuleToSourceId)
  -> f (FileDictWithBuiltins, ModuleToSourceId))
 -> SessionState -> f SessionState)
-> ((ModuleToSource -> f ModuleToSource)
    -> (FileDictWithBuiltins, ModuleToSourceId)
    -> f (FileDictWithBuiltins, ModuleToSourceId))
-> (ModuleToSource -> f ModuleToSource)
-> SessionState
-> f SessionState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ModuleToSource -> f ModuleToSource)
-> (FileDictWithBuiltins, ModuleToSourceId)
-> f (FileDictWithBuiltins, ModuleToSourceId)
Lens' (FileDictWithBuiltins, ModuleToSourceId) ModuleToSource
lensPairModuleToSource

stVisitedModules :: Lens' TCState VisitedModules
stVisitedModules :: Lens' TCState VisitedModules
stVisitedModules = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((VisitedModules -> f VisitedModules)
    -> PreScopeState -> f PreScopeState)
-> (VisitedModules -> f VisitedModules)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (VisitedModules -> f VisitedModules)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState VisitedModules
lensVisitedModules

stScope :: Lens' TCState ScopeInfo
stScope :: Lens' TCState ScopeInfo
stScope = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((ScopeInfo -> f ScopeInfo) -> PreScopeState -> f PreScopeState)
-> (ScopeInfo -> f ScopeInfo)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ScopeInfo -> f ScopeInfo) -> PreScopeState -> f PreScopeState
Lens' PreScopeState ScopeInfo
lensScope

stPatternSyns :: Lens' TCState A.PatternSynDefns
stPatternSyns :: Lens' TCState PatternSynDefns
stPatternSyns = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((PatternSynDefns -> f PatternSynDefns)
    -> PreScopeState -> f PreScopeState)
-> (PatternSynDefns -> f PatternSynDefns)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PatternSynDefns -> f PatternSynDefns)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState PatternSynDefns
lensPatternSyns

stPatternSynImports :: Lens' TCState A.PatternSynDefns
stPatternSynImports :: Lens' TCState PatternSynDefns
stPatternSynImports = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((PatternSynDefns -> f PatternSynDefns)
    -> PreScopeState -> f PreScopeState)
-> (PatternSynDefns -> f PatternSynDefns)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PatternSynDefns -> f PatternSynDefns)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState PatternSynDefns
lensPatternSynImports

stGeneralizedVars :: Lens' TCState (Maybe (Set QName))
stGeneralizedVars :: Lens' TCState (Maybe (Set QName))
stGeneralizedVars = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((Maybe (Set QName) -> f (Maybe (Set QName)))
    -> PreScopeState -> f PreScopeState)
-> (Maybe (Set QName) -> f (Maybe (Set QName)))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe (Set QName) -> f (Maybe (Set QName)))
-> PreScopeState -> f PreScopeState
Lens' PreScopeState (Maybe (Set QName))
lensGeneralizedVars ((Maybe (Set QName) -> f (Maybe (Set QName)))
 -> PreScopeState -> f PreScopeState)
-> ((Maybe (Set QName) -> f (Maybe (Set QName)))
    -> Maybe (Set QName) -> f (Maybe (Set QName)))
-> (Maybe (Set QName) -> f (Maybe (Set QName)))
-> PreScopeState
-> f PreScopeState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe (Set QName) -> f (Maybe (Set QName)))
-> Maybe (Set QName) -> f (Maybe (Set QName))
forall a (p :: * -> * -> *) (f :: * -> *).
(Profunctor p, Functor f) =>
p (Maybe a) (f (Maybe a)) -> p (Maybe a) (f (Maybe a))
Strict.isoMaybeLazy

instance LensPragmaOptions TCState where
  {-# inline lensPragmaOptions #-}
  lensPragmaOptions :: Lens' TCState PragmaOptions
lensPragmaOptions = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((PragmaOptions -> f PragmaOptions)
    -> PreScopeState -> f PreScopeState)
-> (PragmaOptions -> f PragmaOptions)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PragmaOptions -> f PragmaOptions)
-> PreScopeState -> f PreScopeState
forall a. LensPragmaOptions a => Lens' a PragmaOptions
Lens' PreScopeState PragmaOptions
lensPragmaOptions

stPragmaOptions :: Lens' TCState PragmaOptions
stPragmaOptions :: Lens' TCState PragmaOptions
stPragmaOptions = (PragmaOptions -> f PragmaOptions) -> TCState -> f TCState
forall a. LensPragmaOptions a => Lens' a PragmaOptions
Lens' TCState PragmaOptions
lensPragmaOptions

stImportedBuiltins :: Lens' TCState BuiltinThings
stImportedBuiltins :: Lens' TCState (Map SomeBuiltin (Builtin PrimFun))
stImportedBuiltins = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((Map SomeBuiltin (Builtin PrimFun)
     -> f (Map SomeBuiltin (Builtin PrimFun)))
    -> PreScopeState -> f PreScopeState)
-> (Map SomeBuiltin (Builtin PrimFun)
    -> f (Map SomeBuiltin (Builtin PrimFun)))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Map SomeBuiltin (Builtin PrimFun)
 -> f (Map SomeBuiltin (Builtin PrimFun)))
-> PreScopeState -> f PreScopeState
Lens' PreScopeState (Map SomeBuiltin (Builtin PrimFun))
lensImportedBuiltins

stForeignCode :: Lens' TCState BackendForeignCode
stForeignCode :: Lens' TCState BackendForeignCode
stForeignCode = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((BackendForeignCode -> f BackendForeignCode)
    -> PostScopeState -> f PostScopeState)
-> (BackendForeignCode -> f BackendForeignCode)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (BackendForeignCode -> f BackendForeignCode)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState BackendForeignCode
lensForeignCode

stFreshInteractionId :: Lens' TCState InteractionId
stFreshInteractionId :: Lens' TCState InteractionId
stFreshInteractionId = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((InteractionId -> f InteractionId)
    -> PreScopeState -> f PreScopeState)
-> (InteractionId -> f InteractionId)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (InteractionId -> f InteractionId)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState InteractionId
lensFreshInteractionId

stImportedUserWarnings :: Lens' TCState UserWarnings
stImportedUserWarnings :: Lens' TCState UserWarnings
stImportedUserWarnings = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((UserWarnings -> f UserWarnings)
    -> PreScopeState -> f PreScopeState)
-> (UserWarnings -> f UserWarnings)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (UserWarnings -> f UserWarnings)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState UserWarnings
lensImportedUserWarnings

stLocalUserWarnings :: Lens' TCState UserWarnings
stLocalUserWarnings :: Lens' TCState UserWarnings
stLocalUserWarnings = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((UserWarnings -> f UserWarnings)
    -> PreScopeState -> f PreScopeState)
-> (UserWarnings -> f UserWarnings)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (UserWarnings -> f UserWarnings)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState UserWarnings
lensLocalUserWarnings

getUserWarnings :: ReadTCState m => m UserWarnings
getUserWarnings :: forall (m :: * -> *). ReadTCState m => m UserWarnings
getUserWarnings = do
  iuw <- Lens' TCState UserWarnings -> m UserWarnings
forall (m :: * -> *) a. ReadTCState m => Lens' TCState a -> m a
useR (UserWarnings -> f UserWarnings) -> TCState -> f TCState
Lens' TCState UserWarnings
stImportedUserWarnings
  luw <- useR stLocalUserWarnings
  return $ iuw `Map.union` luw

stWarningOnImport :: Lens' TCState (Maybe ShortText)
stWarningOnImport :: Lens' TCState (Maybe ShortText)
stWarningOnImport = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((Maybe ShortText -> f (Maybe ShortText))
    -> PreScopeState -> f PreScopeState)
-> (Maybe ShortText -> f (Maybe ShortText))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe ShortText -> f (Maybe ShortText))
-> PreScopeState -> f PreScopeState
Lens' PreScopeState (Maybe ShortText)
lensWarningOnImport ((Maybe ShortText -> f (Maybe ShortText))
 -> PreScopeState -> f PreScopeState)
-> ((Maybe ShortText -> f (Maybe ShortText))
    -> Maybe ShortText -> f (Maybe ShortText))
-> (Maybe ShortText -> f (Maybe ShortText))
-> PreScopeState
-> f PreScopeState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe ShortText -> f (Maybe ShortText))
-> Maybe ShortText -> f (Maybe ShortText)
forall a (p :: * -> * -> *) (f :: * -> *).
(Profunctor p, Functor f) =>
p (Maybe a) (f (Maybe a)) -> p (Maybe a) (f (Maybe a))
Strict.isoMaybeLazy

stImportedPartialDefs :: Lens' TCState (Set QName)
stImportedPartialDefs :: Lens' TCState (Set QName)
stImportedPartialDefs = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((Set QName -> f (Set QName))
    -> PreScopeState -> f PreScopeState)
-> (Set QName -> f (Set QName))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Set QName -> f (Set QName)) -> PreScopeState -> f PreScopeState
Lens' PreScopeState (Set QName)
lensImportedPartialDefs

stImportedMetaStore :: Lens' TCState RemoteMetaStore
stImportedMetaStore :: Lens' TCState RemoteMetaStore
stImportedMetaStore = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((RemoteMetaStore -> f RemoteMetaStore)
    -> PreScopeState -> f PreScopeState)
-> (RemoteMetaStore -> f RemoteMetaStore)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (RemoteMetaStore -> f RemoteMetaStore)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState RemoteMetaStore
lensImportedMetaStore

stCopiedNames :: Lens' TCState (HashMap QName (ScopeCopyRef, QName))
stCopiedNames :: Lens' TCState (HashMap QName (ScopeCopyRef, QName))
stCopiedNames = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((HashMap QName (ScopeCopyRef, QName)
     -> f (HashMap QName (ScopeCopyRef, QName)))
    -> PreScopeState -> f PreScopeState)
-> (HashMap QName (ScopeCopyRef, QName)
    -> f (HashMap QName (ScopeCopyRef, QName)))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (HashMap QName (ScopeCopyRef, QName)
 -> f (HashMap QName (ScopeCopyRef, QName)))
-> PreScopeState -> f PreScopeState
Lens' PreScopeState (HashMap QName (ScopeCopyRef, QName))
lensCopiedNames

stNameCopies :: Lens' TCState (HashMap QName (HashSet QName))
stNameCopies :: Lens' TCState (HashMap QName (HashSet QName))
stNameCopies = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((HashMap QName (HashSet QName)
     -> f (HashMap QName (HashSet QName)))
    -> PreScopeState -> f PreScopeState)
-> (HashMap QName (HashSet QName)
    -> f (HashMap QName (HashSet QName)))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (HashMap QName (HashSet QName)
 -> f (HashMap QName (HashSet QName)))
-> PreScopeState -> f PreScopeState
Lens' PreScopeState (HashMap QName (HashSet QName))
lensNameCopies

stImportedDisplayForms :: Lens' TCState DisplayForms
stImportedDisplayForms :: Lens' TCState DisplayForms
stImportedDisplayForms = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((DisplayForms -> f DisplayForms)
    -> PreScopeState -> f PreScopeState)
-> (DisplayForms -> f DisplayForms)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DisplayForms -> f DisplayForms)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState DisplayForms
lensImportedDisplayForms

stUnusedImportsState :: Lens' TCState UnusedImportsState
stUnusedImportsState :: Lens' TCState UnusedImportsState
stUnusedImportsState = (PreScopeState -> f PreScopeState) -> TCState -> f TCState
Lens' TCState PreScopeState
lensPreScopeState ((PreScopeState -> f PreScopeState) -> TCState -> f TCState)
-> ((UnusedImportsState -> f UnusedImportsState)
    -> PreScopeState -> f PreScopeState)
-> (UnusedImportsState -> f UnusedImportsState)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (UnusedImportsState -> f UnusedImportsState)
-> PreScopeState -> f PreScopeState
Lens' PreScopeState UnusedImportsState
lensUnusedImportsState

-- ** Post scope state

stLocalPartialDefs :: Lens' TCState (Set QName)
stLocalPartialDefs :: Lens' TCState (Set QName)
stLocalPartialDefs = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Set QName -> f (Set QName))
    -> PostScopeState -> f PostScopeState)
-> (Set QName -> f (Set QName))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Set QName -> f (Set QName)) -> PostScopeState -> f PostScopeState
Lens' PostScopeState (Set QName)
lensLocalPartialDefs

getPartialDefs :: ReadTCState m => m (Set QName)
getPartialDefs :: forall (m :: * -> *). ReadTCState m => m (Set QName)
getPartialDefs = do
  ipd <- Lens' TCState (Set QName) -> m (Set QName)
forall (m :: * -> *) a. ReadTCState m => Lens' TCState a -> m a
useR (Set QName -> f (Set QName)) -> TCState -> f TCState
Lens' TCState (Set QName)
stImportedPartialDefs
  lpd <- useR stLocalPartialDefs
  return $ ipd `Set.union` lpd

stFreshNameId :: Lens' TCState NameId
stFreshNameId :: Lens' TCState NameId
stFreshNameId = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((NameId -> f NameId) -> PostScopeState -> f PostScopeState)
-> (NameId -> f NameId)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (NameId -> f NameId) -> PostScopeState -> f PostScopeState
Lens' PostScopeState NameId
lensFreshNameId

stFreshOpaqueId :: Lens' TCState OpaqueId
stFreshOpaqueId :: Lens' TCState OpaqueId
stFreshOpaqueId = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((OpaqueId -> f OpaqueId) -> PostScopeState -> f PostScopeState)
-> (OpaqueId -> f OpaqueId)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (OpaqueId -> f OpaqueId) -> PostScopeState -> f PostScopeState
Lens' PostScopeState OpaqueId
lensFreshOpaqueId

stOpaqueBlocks :: Lens' TCState (Map OpaqueId OpaqueBlock)
stOpaqueBlocks :: Lens' TCState (Map OpaqueId OpaqueBlock)
stOpaqueBlocks = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Map OpaqueId OpaqueBlock -> f (Map OpaqueId OpaqueBlock))
    -> PostScopeState -> f PostScopeState)
-> (Map OpaqueId OpaqueBlock -> f (Map OpaqueId OpaqueBlock))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Map OpaqueId OpaqueBlock -> f (Map OpaqueId OpaqueBlock))
-> PostScopeState -> f PostScopeState
Lens' PostScopeState (Map OpaqueId OpaqueBlock)
lensOpaqueBlocks

stOpaqueIds :: Lens' TCState (Map QName OpaqueId)
stOpaqueIds :: Lens' TCState (Map QName OpaqueId)
stOpaqueIds = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Map QName OpaqueId -> f (Map QName OpaqueId))
    -> PostScopeState -> f PostScopeState)
-> (Map QName OpaqueId -> f (Map QName OpaqueId))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Map QName OpaqueId -> f (Map QName OpaqueId))
-> PostScopeState -> f PostScopeState
Lens' PostScopeState (Map QName OpaqueId)
lensOpaqueIds

stInstanceHack :: Lens' TCState Bool
stInstanceHack :: Lens' TCState Bool
stInstanceHack = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Bool -> f Bool) -> PostScopeState -> f PostScopeState)
-> (Bool -> f Bool)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> f Bool) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Bool
lensInstanceHack

stSyntaxInfo :: Lens' TCState HighlightingInfo
stSyntaxInfo :: Lens' TCState HighlightingInfo
stSyntaxInfo = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((HighlightingInfo -> f HighlightingInfo)
    -> PostScopeState -> f PostScopeState)
-> (HighlightingInfo -> f HighlightingInfo)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (HighlightingInfo -> f HighlightingInfo)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState HighlightingInfo
lensSyntaxInfo

stDisambiguatedNames :: Lens' TCState DisambiguatedNames
stDisambiguatedNames :: Lens' TCState DisambiguatedNames
stDisambiguatedNames = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((DisambiguatedNames -> f DisambiguatedNames)
    -> PostScopeState -> f PostScopeState)
-> (DisambiguatedNames -> f DisambiguatedNames)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DisambiguatedNames -> f DisambiguatedNames)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState DisambiguatedNames
lensDisambiguatedNames

stOpenMetaStore :: Lens' TCState LocalMetaStore
stOpenMetaStore :: Lens' TCState LocalMetaStore
stOpenMetaStore = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((LocalMetaStore -> f LocalMetaStore)
    -> PostScopeState -> f PostScopeState)
-> (LocalMetaStore -> f LocalMetaStore)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (LocalMetaStore -> f LocalMetaStore)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState LocalMetaStore
lensOpenMetaStore

stSolvedMetaStore :: Lens' TCState LocalMetaStore
stSolvedMetaStore :: Lens' TCState LocalMetaStore
stSolvedMetaStore = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((LocalMetaStore -> f LocalMetaStore)
    -> PostScopeState -> f PostScopeState)
-> (LocalMetaStore -> f LocalMetaStore)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (LocalMetaStore -> f LocalMetaStore)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState LocalMetaStore
lensSolvedMetaStore

stInteractionPoints :: Lens' TCState InteractionPoints
stInteractionPoints :: Lens' TCState InteractionPoints
stInteractionPoints = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((InteractionPoints -> f InteractionPoints)
    -> PostScopeState -> f PostScopeState)
-> (InteractionPoints -> f InteractionPoints)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (InteractionPoints -> f InteractionPoints)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState InteractionPoints
lensInteractionPoints

stAwakeConstraints :: Lens' TCState Constraints
stAwakeConstraints :: Lens' TCState Constraints
stAwakeConstraints = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Constraints -> f Constraints)
    -> PostScopeState -> f PostScopeState)
-> (Constraints -> f Constraints)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Constraints -> f Constraints)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState Constraints
lensAwakeConstraints

stSleepingConstraints :: Lens' TCState Constraints
stSleepingConstraints :: Lens' TCState Constraints
stSleepingConstraints = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Constraints -> f Constraints)
    -> PostScopeState -> f PostScopeState)
-> (Constraints -> f Constraints)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Constraints -> f Constraints)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState Constraints
lensSleepingConstraints

stDirty :: Lens' TCState Bool
stDirty :: Lens' TCState Bool
stDirty = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Bool -> f Bool) -> PostScopeState -> f PostScopeState)
-> (Bool -> f Bool)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> f Bool) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Bool
lensDirty

stOccursCheckDefs :: Lens' TCState (Set QName)
stOccursCheckDefs :: Lens' TCState (Set QName)
stOccursCheckDefs = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Set QName -> f (Set QName))
    -> PostScopeState -> f PostScopeState)
-> (Set QName -> f (Set QName))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Set QName -> f (Set QName)) -> PostScopeState -> f PostScopeState
Lens' PostScopeState (Set QName)
lensOccursCheckDefs

stSignature :: Lens' TCState Signature
stSignature :: Lens' TCState Signature
stSignature = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Signature -> f Signature)
    -> PostScopeState -> f PostScopeState)
-> (Signature -> f Signature)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Signature -> f Signature) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Signature
lensSignature

stModuleCheckpoints :: Lens' TCState ModuleCheckpoints
stModuleCheckpoints :: Lens' TCState ModuleCheckpoints
stModuleCheckpoints = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((ModuleCheckpoints -> f ModuleCheckpoints)
    -> PostScopeState -> f PostScopeState)
-> (ModuleCheckpoints -> f ModuleCheckpoints)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ModuleCheckpoints -> f ModuleCheckpoints)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState ModuleCheckpoints
lensModuleCheckpoints

stImportsDisplayForms :: Lens' TCState DisplayForms
stImportsDisplayForms :: Lens' TCState DisplayForms
stImportsDisplayForms = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((DisplayForms -> f DisplayForms)
    -> PostScopeState -> f PostScopeState)
-> (DisplayForms -> f DisplayForms)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DisplayForms -> f DisplayForms)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState DisplayForms
lensImportsDisplayForms

stWarningSet :: Lens' TCState (Set WarningName)
stWarningSet :: Lens' TCState (Set WarningName)
stWarningSet = (PragmaOptions -> f PragmaOptions) -> TCState -> f TCState
Lens' TCState PragmaOptions
stPragmaOptions ((PragmaOptions -> f PragmaOptions) -> TCState -> f TCState)
-> ((Set WarningName -> f (Set WarningName))
    -> PragmaOptions -> f PragmaOptions)
-> (Set WarningName -> f (Set WarningName))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (WarningMode -> f WarningMode) -> PragmaOptions -> f PragmaOptions
forall (f :: * -> *).
Functor f =>
(WarningMode -> f WarningMode) -> PragmaOptions -> f PragmaOptions
lensOptWarningMode ((WarningMode -> f WarningMode)
 -> PragmaOptions -> f PragmaOptions)
-> ((Set WarningName -> f (Set WarningName))
    -> WarningMode -> f WarningMode)
-> (Set WarningName -> f (Set WarningName))
-> PragmaOptions
-> f PragmaOptions
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Set WarningName -> f (Set WarningName))
-> WarningMode -> f WarningMode
Lens' WarningMode (Set WarningName)
warningSet

stCurrentModule :: Lens' TCState (Strict.Maybe (Strict.Pair ModuleName TopLevelModuleName))
stCurrentModule :: Lens' TCState (Maybe (Pair ModuleName TopLevelModuleName))
stCurrentModule = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Maybe (Pair ModuleName TopLevelModuleName)
     -> f (Maybe (Pair ModuleName TopLevelModuleName)))
    -> PostScopeState -> f PostScopeState)
-> (Maybe (Pair ModuleName TopLevelModuleName)
    -> f (Maybe (Pair ModuleName TopLevelModuleName)))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe (Pair ModuleName TopLevelModuleName)
 -> f (Maybe (Pair ModuleName TopLevelModuleName)))
-> PostScopeState -> f PostScopeState
Lens' PostScopeState (Maybe (Pair ModuleName TopLevelModuleName))
lensCurrentModule

{-# INLINE stInstanceDefs #-}
stInstanceDefs :: Lens' TCState TempInstanceTable
stInstanceDefs :: Lens' TCState TempInstanceTable
stInstanceDefs = \TempInstanceTable -> f TempInstanceTable
f TCState
s ->
  TempInstanceTable -> f TempInstanceTable
f ( TCState
s TCState
-> Getting InstanceTable TCState InstanceTable -> InstanceTable
forall s a. s -> Getting a s a -> a
^. (Signature -> Const InstanceTable Signature)
-> TCState -> Const InstanceTable TCState
Lens' TCState Signature
stSignature ((Signature -> Const InstanceTable Signature)
 -> TCState -> Const InstanceTable TCState)
-> ((InstanceTable -> Const InstanceTable InstanceTable)
    -> Signature -> Const InstanceTable Signature)
-> Getting InstanceTable TCState InstanceTable
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (InstanceTable -> Const InstanceTable InstanceTable)
-> Signature -> Const InstanceTable Signature
Lens' Signature InstanceTable
sigInstances
    , PostColdState -> Set QName
stPostPendingInstances (PostScopeState -> PostColdState
stPostColdState (TCState -> PostScopeState
stPostScopeState TCState
s))
    )
  f TempInstanceTable -> (TempInstanceTable -> TCState) -> f TCState
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \(!InstanceTable
t, !Set QName
x) ->
    ASetter TCState TCState InstanceTable InstanceTable
-> InstanceTable -> TCState -> TCState
forall s t a b. ASetter s t a b -> b -> s -> t
set ((Signature -> Identity Signature) -> TCState -> Identity TCState
Lens' TCState Signature
stSignature ((Signature -> Identity Signature) -> TCState -> Identity TCState)
-> ((InstanceTable -> Identity InstanceTable)
    -> Signature -> Identity Signature)
-> ASetter TCState TCState InstanceTable InstanceTable
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (InstanceTable -> Identity InstanceTable)
-> Signature -> Identity Signature
Lens' Signature InstanceTable
sigInstances) InstanceTable
t
      (TCState
s { stPostScopeState = (stPostScopeState s) {
           stPostColdState = (stPostColdState (stPostScopeState s)){
               stPostPendingInstances = x }}})

stTemporaryInstances :: Lens' TCState (Set QName)
stTemporaryInstances :: Lens' TCState (Set QName)
stTemporaryInstances = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Set QName -> f (Set QName))
    -> PostScopeState -> f PostScopeState)
-> (Set QName -> f (Set QName))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Set QName -> f (Set QName)) -> PostScopeState -> f PostScopeState
Lens' PostScopeState (Set QName)
lensTemporaryInstances

stConcreteNames :: Lens' TCState ConcreteNames
stConcreteNames :: Lens' TCState ConcreteNames
stConcreteNames = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((ConcreteNames -> f ConcreteNames)
    -> PostScopeState -> f PostScopeState)
-> (ConcreteNames -> f ConcreteNames)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ConcreteNames -> f ConcreteNames)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState ConcreteNames
lensConcreteNames

stStatistics :: Lens' TCState Statistics
stStatistics :: Lens' TCState Statistics
stStatistics = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Statistics -> f Statistics)
    -> PostScopeState -> f PostScopeState)
-> (Statistics -> f Statistics)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Statistics -> f Statistics) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Statistics
lensStatistics

stTCWarnings :: Lens' TCState (Set TCWarning)
stTCWarnings :: Lens' TCState (Set TCWarning)
stTCWarnings = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Set TCWarning -> f (Set TCWarning))
    -> PostScopeState -> f PostScopeState)
-> (Set TCWarning -> f (Set TCWarning))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Set TCWarning -> f (Set TCWarning))
-> PostScopeState -> f PostScopeState
Lens' PostScopeState (Set TCWarning)
lensTCWarnings

stMutualBlocks :: Lens' TCState MutualBlocks
stMutualBlocks :: Lens' TCState MutualBlocks
stMutualBlocks = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((MutualBlocks -> f MutualBlocks)
    -> PostScopeState -> f PostScopeState)
-> (MutualBlocks -> f MutualBlocks)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MutualBlocks -> f MutualBlocks)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState MutualBlocks
lensMutualBlocks

stLocalBuiltins :: Lens' TCState BuiltinThings
stLocalBuiltins :: Lens' TCState (Map SomeBuiltin (Builtin PrimFun))
stLocalBuiltins = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Map SomeBuiltin (Builtin PrimFun)
     -> f (Map SomeBuiltin (Builtin PrimFun)))
    -> PostScopeState -> f PostScopeState)
-> (Map SomeBuiltin (Builtin PrimFun)
    -> f (Map SomeBuiltin (Builtin PrimFun)))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Map SomeBuiltin (Builtin PrimFun)
 -> f (Map SomeBuiltin (Builtin PrimFun)))
-> PostScopeState -> f PostScopeState
Lens' PostScopeState (Map SomeBuiltin (Builtin PrimFun))
lensLocalBuiltins

stFreshMetaId :: Lens' TCState MetaId
stFreshMetaId :: Lens' TCState MetaId
stFreshMetaId = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((MetaId -> f MetaId) -> PostScopeState -> f PostScopeState)
-> (MetaId -> f MetaId)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MetaId -> f MetaId) -> PostScopeState -> f PostScopeState
Lens' PostScopeState MetaId
lensFreshMetaId

stFreshMutualId :: Lens' TCState MutualId
stFreshMutualId :: Lens' TCState MutualId
stFreshMutualId = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((MutualId -> f MutualId) -> PostScopeState -> f PostScopeState)
-> (MutualId -> f MutualId)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MutualId -> f MutualId) -> PostScopeState -> f PostScopeState
Lens' PostScopeState MutualId
lensFreshMutualId

stFreshProblemId :: Lens' TCState ProblemId
stFreshProblemId :: Lens' TCState ProblemId
stFreshProblemId = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((ProblemId -> f ProblemId)
    -> PostScopeState -> f PostScopeState)
-> (ProblemId -> f ProblemId)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ProblemId -> f ProblemId) -> PostScopeState -> f PostScopeState
Lens' PostScopeState ProblemId
lensFreshProblemId

stFreshCheckpointId :: Lens' TCState CheckpointId
stFreshCheckpointId :: Lens' TCState CheckpointId
stFreshCheckpointId = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((CheckpointId -> f CheckpointId)
    -> PostScopeState -> f PostScopeState)
-> (CheckpointId -> f CheckpointId)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CheckpointId -> f CheckpointId)
-> PostScopeState -> f PostScopeState
Lens' PostScopeState CheckpointId
lensFreshCheckpointId

stFreshInt :: Lens' TCState Int
stFreshInt :: Lens' TCState Int
stFreshInt = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Int -> f Int) -> PostScopeState -> f PostScopeState)
-> (Int -> f Int)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int -> f Int) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Int
lensFreshInt

-- | use @areWeCaching@ from the Caching module instead.
stAreWeCaching :: Lens' TCState Bool
stAreWeCaching :: Lens' TCState Bool
stAreWeCaching = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Bool -> f Bool) -> PostScopeState -> f PostScopeState)
-> (Bool -> f Bool)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> f Bool) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Bool
lensAreWeCaching

stPostponeInstanceSearch :: Lens' TCState Bool
stPostponeInstanceSearch :: Lens' TCState Bool
stPostponeInstanceSearch = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Bool -> f Bool) -> PostScopeState -> f PostScopeState)
-> (Bool -> f Bool)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> f Bool) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Bool
lensPostponeInstanceSearch

stConsideringInstance :: Lens' TCState Bool
stConsideringInstance :: Lens' TCState Bool
stConsideringInstance = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Bool -> f Bool) -> PostScopeState -> f PostScopeState)
-> (Bool -> f Bool)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> f Bool) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Bool
lensConsideringInstance

stInstantiateBlocking :: Lens' TCState Bool
stInstantiateBlocking :: Lens' TCState Bool
stInstantiateBlocking = (PostScopeState -> f PostScopeState) -> TCState -> f TCState
Lens' TCState PostScopeState
lensPostScopeState ((PostScopeState -> f PostScopeState) -> TCState -> f TCState)
-> ((Bool -> f Bool) -> PostScopeState -> f PostScopeState)
-> (Bool -> f Bool)
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> f Bool) -> PostScopeState -> f PostScopeState
Lens' PostScopeState Bool
lensInstantiateBlocking

stInstanceTree :: Lens' TCState (DiscrimTree QName)
stInstanceTree :: Lens' TCState (DiscrimTree QName)
stInstanceTree = (Signature -> f Signature) -> TCState -> f TCState
Lens' TCState Signature
stSignature ((Signature -> f Signature) -> TCState -> f TCState)
-> ((DiscrimTree QName -> f (DiscrimTree QName))
    -> Signature -> f Signature)
-> (DiscrimTree QName -> f (DiscrimTree QName))
-> TCState
-> f TCState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (InstanceTable -> f InstanceTable) -> Signature -> f Signature
Lens' Signature InstanceTable
sigInstances ((InstanceTable -> f InstanceTable) -> Signature -> f Signature)
-> ((DiscrimTree QName -> f (DiscrimTree QName))
    -> InstanceTable -> f InstanceTable)
-> (DiscrimTree QName -> f (DiscrimTree QName))
-> Signature
-> f Signature
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (DiscrimTree QName -> f (DiscrimTree QName))
-> InstanceTable -> f InstanceTable
Lens' InstanceTable (DiscrimTree QName)
itableTree

stBuiltinThings :: TCState -> BuiltinThings
stBuiltinThings :: TCState -> Map SomeBuiltin (Builtin PrimFun)
stBuiltinThings TCState
s = Map SomeBuiltin (Builtin PrimFun)
-> Map SomeBuiltin (Builtin PrimFun)
-> Map SomeBuiltin (Builtin PrimFun)
forall k a. Ord k => Map k a -> Map k a -> Map k a
Map.union (TCState
s TCState
-> Getting
     (Map SomeBuiltin (Builtin PrimFun))
     TCState
     (Map SomeBuiltin (Builtin PrimFun))
-> Map SomeBuiltin (Builtin PrimFun)
forall s a. s -> Getting a s a -> a
^. Getting
  (Map SomeBuiltin (Builtin PrimFun))
  TCState
  (Map SomeBuiltin (Builtin PrimFun))
Lens' TCState (Map SomeBuiltin (Builtin PrimFun))
stLocalBuiltins) (TCState
s TCState
-> Getting
     (Map SomeBuiltin (Builtin PrimFun))
     TCState
     (Map SomeBuiltin (Builtin PrimFun))
-> Map SomeBuiltin (Builtin PrimFun)
forall s a. s -> Getting a s a -> a
^. Getting
  (Map SomeBuiltin (Builtin PrimFun))
  TCState
  (Map SomeBuiltin (Builtin PrimFun))
Lens' TCState (Map SomeBuiltin (Builtin PrimFun))
stImportedBuiltins)

-- * Fresh things
------------------------------------------------------------------------

class Enum i => HasFresh i where
    freshLens :: Lens' TCState i
    nextFresh' :: i -> i
    nextFresh' = i -> i
forall a. Enum a => a -> a
succ

{-# INLINE nextFresh #-}
nextFresh :: HasFresh i => TCState -> (i, TCState)
nextFresh :: forall i. HasFresh i => TCState -> (i, TCState)
nextFresh TCState
s =
  let !c :: i
c = TCState
s TCState -> Getting i TCState i -> i
forall s a. s -> Getting a s a -> a
^. Getting i TCState i
forall i. HasFresh i => Lens' TCState i
Lens' TCState i
freshLens
      !next :: TCState
next = ASetter TCState TCState i i -> i -> TCState -> TCState
forall s t a b. ASetter s t a b -> b -> s -> t
set ASetter TCState TCState i i
forall i. HasFresh i => Lens' TCState i
Lens' TCState i
freshLens (i -> i
forall i. HasFresh i => i -> i
nextFresh' i
c) TCState
s
  in (i
c, TCState
next)

class Monad m => MonadFresh i m where
  fresh :: m i

  default fresh :: (MonadTrans t, MonadFresh i n, t n ~ m) => m i
  fresh = n i -> t n i
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift n i
forall i (m :: * -> *). MonadFresh i m => m i
fresh

instance MonadFresh i m => MonadFresh i (ExceptT e m)
instance MonadFresh i m => MonadFresh i (MaybeT m)
instance MonadFresh i m => MonadFresh i (ReaderT r m)
instance MonadFresh i m => MonadFresh i (StateT s m)
instance (MonadFresh i m, Monoid w) => MonadFresh i (WriterT w m)
instance MonadFresh i m => MonadFresh i (ListT m)
instance MonadFresh i m => MonadFresh i (IdentityT m)

instance HasFresh i => MonadFresh i TCM where
  fresh :: TCM i
fresh = do
        !s <- TCMT IO TCState
forall (m :: * -> *). MonadTCState m => m TCState
getTC
        let (!c , !s') = nextFresh s
        putTC s'
        return c
  {-# INLINE fresh #-}

instance HasFresh MetaId where
  freshLens :: Lens' TCState MetaId
freshLens = (MetaId -> f MetaId) -> TCState -> f TCState
Lens' TCState MetaId
stFreshMetaId

instance HasFresh MutualId where
  freshLens :: Lens' TCState MutualId
freshLens = (MutualId -> f MutualId) -> TCState -> f TCState
Lens' TCState MutualId
stFreshMutualId

instance HasFresh InteractionId where
  freshLens :: Lens' TCState InteractionId
freshLens = (InteractionId -> f InteractionId) -> TCState -> f TCState
Lens' TCState InteractionId
stFreshInteractionId

instance HasFresh NameId where
  freshLens :: Lens' TCState NameId
freshLens = (NameId -> f NameId) -> TCState -> f TCState
Lens' TCState NameId
stFreshNameId
  -- nextFresh increments the current fresh name by 2 so @NameId@s used
  -- before caching starts do not overlap with the ones used after.
  nextFresh' :: NameId -> NameId
nextFresh' = NameId -> NameId
forall a. Enum a => a -> a
succ (NameId -> NameId) -> (NameId -> NameId) -> NameId -> NameId
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NameId -> NameId
forall a. Enum a => a -> a
succ

instance HasFresh OpaqueId where
  freshLens :: Lens' TCState OpaqueId
freshLens = (OpaqueId -> f OpaqueId) -> TCState -> f TCState
Lens' TCState OpaqueId
stFreshOpaqueId

instance HasFresh Int where
  freshLens :: Lens' TCState Int
freshLens = (Int -> f Int) -> TCState -> f TCState
Lens' TCState Int
stFreshInt

instance HasFresh ProblemId where
  freshLens :: Lens' TCState ProblemId
freshLens = (ProblemId -> f ProblemId) -> TCState -> f TCState
Lens' TCState ProblemId
stFreshProblemId

newtype CheckpointId = CheckpointId Int
  deriving (CheckpointId -> CheckpointId -> Bool
(CheckpointId -> CheckpointId -> Bool)
-> (CheckpointId -> CheckpointId -> Bool) -> Eq CheckpointId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CheckpointId -> CheckpointId -> Bool
== :: CheckpointId -> CheckpointId -> Bool
$c/= :: CheckpointId -> CheckpointId -> Bool
/= :: CheckpointId -> CheckpointId -> Bool
Eq, Eq CheckpointId
Eq CheckpointId =>
(CheckpointId -> CheckpointId -> Ordering)
-> (CheckpointId -> CheckpointId -> Bool)
-> (CheckpointId -> CheckpointId -> Bool)
-> (CheckpointId -> CheckpointId -> Bool)
-> (CheckpointId -> CheckpointId -> Bool)
-> (CheckpointId -> CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId -> CheckpointId)
-> Ord CheckpointId
CheckpointId -> CheckpointId -> Bool
CheckpointId -> CheckpointId -> Ordering
CheckpointId -> CheckpointId -> CheckpointId
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: CheckpointId -> CheckpointId -> Ordering
compare :: CheckpointId -> CheckpointId -> Ordering
$c< :: CheckpointId -> CheckpointId -> Bool
< :: CheckpointId -> CheckpointId -> Bool
$c<= :: CheckpointId -> CheckpointId -> Bool
<= :: CheckpointId -> CheckpointId -> Bool
$c> :: CheckpointId -> CheckpointId -> Bool
> :: CheckpointId -> CheckpointId -> Bool
$c>= :: CheckpointId -> CheckpointId -> Bool
>= :: CheckpointId -> CheckpointId -> Bool
$cmax :: CheckpointId -> CheckpointId -> CheckpointId
max :: CheckpointId -> CheckpointId -> CheckpointId
$cmin :: CheckpointId -> CheckpointId -> CheckpointId
min :: CheckpointId -> CheckpointId -> CheckpointId
Ord, Int -> CheckpointId
CheckpointId -> Int
CheckpointId -> [CheckpointId]
CheckpointId -> CheckpointId
CheckpointId -> CheckpointId -> [CheckpointId]
CheckpointId -> CheckpointId -> CheckpointId -> [CheckpointId]
(CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId)
-> (Int -> CheckpointId)
-> (CheckpointId -> Int)
-> (CheckpointId -> [CheckpointId])
-> (CheckpointId -> CheckpointId -> [CheckpointId])
-> (CheckpointId -> CheckpointId -> [CheckpointId])
-> (CheckpointId -> CheckpointId -> CheckpointId -> [CheckpointId])
-> Enum CheckpointId
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: CheckpointId -> CheckpointId
succ :: CheckpointId -> CheckpointId
$cpred :: CheckpointId -> CheckpointId
pred :: CheckpointId -> CheckpointId
$ctoEnum :: Int -> CheckpointId
toEnum :: Int -> CheckpointId
$cfromEnum :: CheckpointId -> Int
fromEnum :: CheckpointId -> Int
$cenumFrom :: CheckpointId -> [CheckpointId]
enumFrom :: CheckpointId -> [CheckpointId]
$cenumFromThen :: CheckpointId -> CheckpointId -> [CheckpointId]
enumFromThen :: CheckpointId -> CheckpointId -> [CheckpointId]
$cenumFromTo :: CheckpointId -> CheckpointId -> [CheckpointId]
enumFromTo :: CheckpointId -> CheckpointId -> [CheckpointId]
$cenumFromThenTo :: CheckpointId -> CheckpointId -> CheckpointId -> [CheckpointId]
enumFromThenTo :: CheckpointId -> CheckpointId -> CheckpointId -> [CheckpointId]
Enum, Num CheckpointId
Ord CheckpointId
(Num CheckpointId, Ord CheckpointId) =>
(CheckpointId -> Rational) -> Real CheckpointId
CheckpointId -> Rational
forall a. (Num a, Ord a) => (a -> Rational) -> Real a
$ctoRational :: CheckpointId -> Rational
toRational :: CheckpointId -> Rational
Real, Enum CheckpointId
Real CheckpointId
(Real CheckpointId, Enum CheckpointId) =>
(CheckpointId -> CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId -> (CheckpointId, CheckpointId))
-> (CheckpointId -> CheckpointId -> (CheckpointId, CheckpointId))
-> (CheckpointId -> Integer)
-> Integral CheckpointId
CheckpointId -> Integer
CheckpointId -> CheckpointId -> (CheckpointId, CheckpointId)
CheckpointId -> CheckpointId -> CheckpointId
forall a.
(Real a, Enum a) =>
(a -> a -> a)
-> (a -> a -> a)
-> (a -> a -> a)
-> (a -> a -> a)
-> (a -> a -> (a, a))
-> (a -> a -> (a, a))
-> (a -> Integer)
-> Integral a
$cquot :: CheckpointId -> CheckpointId -> CheckpointId
quot :: CheckpointId -> CheckpointId -> CheckpointId
$crem :: CheckpointId -> CheckpointId -> CheckpointId
rem :: CheckpointId -> CheckpointId -> CheckpointId
$cdiv :: CheckpointId -> CheckpointId -> CheckpointId
div :: CheckpointId -> CheckpointId -> CheckpointId
$cmod :: CheckpointId -> CheckpointId -> CheckpointId
mod :: CheckpointId -> CheckpointId -> CheckpointId
$cquotRem :: CheckpointId -> CheckpointId -> (CheckpointId, CheckpointId)
quotRem :: CheckpointId -> CheckpointId -> (CheckpointId, CheckpointId)
$cdivMod :: CheckpointId -> CheckpointId -> (CheckpointId, CheckpointId)
divMod :: CheckpointId -> CheckpointId -> (CheckpointId, CheckpointId)
$ctoInteger :: CheckpointId -> Integer
toInteger :: CheckpointId -> Integer
Integral, Integer -> CheckpointId
CheckpointId -> CheckpointId
CheckpointId -> CheckpointId -> CheckpointId
(CheckpointId -> CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId)
-> (CheckpointId -> CheckpointId)
-> (Integer -> CheckpointId)
-> Num CheckpointId
forall a.
(a -> a -> a)
-> (a -> a -> a)
-> (a -> a -> a)
-> (a -> a)
-> (a -> a)
-> (a -> a)
-> (Integer -> a)
-> Num a
$c+ :: CheckpointId -> CheckpointId -> CheckpointId
+ :: CheckpointId -> CheckpointId -> CheckpointId
$c- :: CheckpointId -> CheckpointId -> CheckpointId
- :: CheckpointId -> CheckpointId -> CheckpointId
$c* :: CheckpointId -> CheckpointId -> CheckpointId
* :: CheckpointId -> CheckpointId -> CheckpointId
$cnegate :: CheckpointId -> CheckpointId
negate :: CheckpointId -> CheckpointId
$cabs :: CheckpointId -> CheckpointId
abs :: CheckpointId -> CheckpointId
$csignum :: CheckpointId -> CheckpointId
signum :: CheckpointId -> CheckpointId
$cfromInteger :: Integer -> CheckpointId
fromInteger :: Integer -> CheckpointId
Num, CheckpointId -> ()
(CheckpointId -> ()) -> NFData CheckpointId
forall a. (a -> ()) -> NFData a
$crnf :: CheckpointId -> ()
rnf :: CheckpointId -> ()
NFData)

instance Show CheckpointId where
  show :: CheckpointId -> String
show (CheckpointId Int
n) = Int -> String
forall a. Show a => a -> String
show Int
n

instance Pretty CheckpointId where
  pretty :: CheckpointId -> Doc
pretty (CheckpointId Int
n) = Int -> Doc
forall a. Pretty a => a -> Doc
pretty Int
n

instance HasFresh CheckpointId where
  freshLens :: Lens' TCState CheckpointId
freshLens = (CheckpointId -> f CheckpointId) -> TCState -> f TCState
Lens' TCState CheckpointId
stFreshCheckpointId

freshName :: MonadFresh NameId m => Range -> ShortText -> m Name
freshName :: forall (m :: * -> *).
MonadFresh NameId m =>
Range -> ShortText -> m Name
freshName Range
r ShortText
s = do
  i <- m NameId
forall i (m :: * -> *). MonadFresh i m => m i
fresh
  return $ mkName r i s

freshNoName :: MonadFresh NameId m => Range -> m Name
freshNoName :: forall (m :: * -> *). MonadFresh NameId m => Range -> m Name
freshNoName Range
r =
    do  i <- m NameId
forall i (m :: * -> *). MonadFresh i m => m i
fresh
        return $ makeName i (C.NoName noRange i) r noFixity' False

freshNoName_ :: MonadFresh NameId m => m Name
freshNoName_ :: forall (m :: * -> *). MonadFresh NameId m => m Name
freshNoName_ = Range -> m Name
forall (m :: * -> *). MonadFresh NameId m => Range -> m Name
freshNoName Range
forall a. Range' a
noRange

freshRecordName :: MonadFresh NameId m => m Name
freshRecordName :: forall (m :: * -> *). MonadFresh NameId m => m Name
freshRecordName = do
  i <- m NameId
forall i (m :: * -> *). MonadFresh i m => m i
fresh
  return $ makeName i (C.setNotInScope $ C.simpleName "r") noRange noFixity' True

-- | Create a fresh name from @a@.
class FreshName a where
  freshName_ :: MonadFresh NameId m => a -> m Name

instance FreshName (Range, ShortText) where
  freshName_ :: forall (m :: * -> *).
MonadFresh NameId m =>
(Range, ShortText) -> m Name
freshName_ = (Range -> ShortText -> m Name) -> (Range, ShortText) -> m Name
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Range -> ShortText -> m Name
forall (m :: * -> *).
MonadFresh NameId m =>
Range -> ShortText -> m Name
freshName

instance FreshName ShortText where
  freshName_ :: forall (m :: * -> *). MonadFresh NameId m => ShortText -> m Name
freshName_ = Range -> ShortText -> m Name
forall (m :: * -> *).
MonadFresh NameId m =>
Range -> ShortText -> m Name
freshName Range
forall a. Range' a
noRange

instance FreshName Range where
  freshName_ :: forall (m :: * -> *). MonadFresh NameId m => Range -> m Name
freshName_ = Range -> m Name
forall (m :: * -> *). MonadFresh NameId m => Range -> m Name
freshNoName

instance FreshName () where
  freshName_ :: forall (m :: * -> *). MonadFresh NameId m => () -> m Name
freshName_ () = m Name
forall (m :: * -> *). MonadFresh NameId m => m Name
freshNoName_

instance FreshName Name where
  freshName_ :: forall (m :: * -> *). MonadFresh NameId m => Name -> m Name
freshName_ (Name NameId
_ Name
con Name
can Range
bs Fixity'
fix Bool
rn) = do
    i <- m NameId
forall i (m :: * -> *). MonadFresh i m => m i
fresh
    pure $ Name i con can bs fix rn

instance FreshName C.Name where
  freshName_ :: forall (m :: * -> *). MonadFresh NameId m => Name -> m Name
freshName_ Name
c = do
    i <- m NameId
forall i (m :: * -> *). MonadFresh i m => m i
fresh
    pure $ Name i c c noRange noFixity' False

----------------------------------------------------------------------------------------------------
-- * Module Checkpoints
--
-- During the course of typechecking, we often need to bounce between wildly
-- different contexts. To do this, we need to have access to a substitution
-- that describes how our current context was built. This is handled internally
-- via __checkpoints__. These are unique identifiers that index into a map
-- @'envCheckpoints'@ that translates @'CheckpointId'@s into @'Substitution'@s,
-- which allows us to cheaply look up the substitution that describes how to
-- enter some other context.
--
-- Agda also uses checkpoints to manage parameterised module telescopes.
-- This is a natural choice: we've already got a map of substitutions
-- in the typing environment, so if we are able to associate every module name
-- to a checkpoint, we can re-use this machinery to store substitutions
-- @Γ ⊢ ρ : Δm@ that map our current context @Γ@ into a module parameter
-- telescope @Δm@ for some module @m@.
--
-- However, things get a bit tricky when we enter and leave modules.
-- Consider the following code:
--
-- > module M1 (A : Type) where
-- >   module M2 (ff : ⊥) where
-- >     x : Nat
-- >     x = ... -- Typechecking here
-- >   ...
--
-- When we are typechecking the RHS of @x@, the substitution associated to
-- @M2@ ought to be a checkpoint pointing to the identity substitution
--
-- > A : Type, ff : ⊥ ⊢ A, ff : (A : Type, ff : ⊥).
--
-- Things only get tricky when we finish typechecking the body of @M2@, and
-- re-enter the outer module @M1@. When we are back in the body of @M1@, our
-- ambient context no longer contains a @ff : ⊥@, and the checkpoint associated to
-- @M2@ needs to point to:
--
-- > A : Type ⊢ A : (A : Type).
--
-- To manage this, we keep track of a stack that associates a set of @'ModuleName's@ to
-- a single @'CheckPointId'@. This makes it relatively efficient to determine when
-- we should update the checkpoint of a group of modules. Checkpoint ids are allocated
-- monotonically, so whenever a checkpoint goes out of scope, we can do batch updates of
-- checkpoint ids by walking back along the stack of module names until we hit the checkpoint
-- we are looking for.
----------------------------------------------------------------------------------------------------

-- | A stack of module checkpoints for the current module.
--
--   We use a hand-rolled stack over a list so that we can @UNPACK@ the @CheckpointId@
--   and make all the fields strict.
data ModuleCheckpoints
  = ModuleCheckpointsTop
  -- ^ We are in a top-level module, so we don't need to worry about checkpoints.
  | ModuleCheckpointsSection !ModuleCheckpoints !(Set ModuleName) {-# UNPACK #-} !CheckpointId
  -- ^ A group of modules that all share a single checkpoint.
  deriving ((forall x. ModuleCheckpoints -> Rep ModuleCheckpoints x)
-> (forall x. Rep ModuleCheckpoints x -> ModuleCheckpoints)
-> Generic ModuleCheckpoints
forall x. Rep ModuleCheckpoints x -> ModuleCheckpoints
forall x. ModuleCheckpoints -> Rep ModuleCheckpoints x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ModuleCheckpoints -> Rep ModuleCheckpoints x
from :: forall x. ModuleCheckpoints -> Rep ModuleCheckpoints x
$cto :: forall x. Rep ModuleCheckpoints x -> ModuleCheckpoints
to :: forall x. Rep ModuleCheckpoints x -> ModuleCheckpoints
Generic)

-- All fields of @ModuleCheckpoints@ are strict, so we only need to force the outermost constructor.
instance NFData ModuleCheckpoints where
  rnf :: ModuleCheckpoints -> ()
rnf ModuleCheckpoints
ModuleCheckpointsTop = ()
  rnf (ModuleCheckpointsSection ModuleCheckpoints
_ Set ModuleName
_ CheckpointId
_) = ()

instance Pretty ModuleCheckpoints where
  pretty :: ModuleCheckpoints -> Doc
pretty (ModuleCheckpoints
ModuleCheckpointsTop) = Doc
"[]"
  pretty (ModuleCheckpointsSection ModuleCheckpoints
mchkpts Set ModuleName
mnames CheckpointId
chkpt) =
    (ModuleCheckpoints -> Doc
forall a. Pretty a => a -> Doc
pretty ModuleCheckpoints
mchkpts Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
comma) Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Doc -> Doc
parens (Set ModuleName -> Doc
forall a. Pretty a => a -> Doc
pretty Set ModuleName
mnames Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Doc
colon Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> CheckpointId -> Doc
forall a. Pretty a => a -> Doc
pretty CheckpointId
chkpt)

----------------------------------------------------------------------------------------------------
-- * Associating concrete names to an abstract name
----------------------------------------------------------------------------------------------------

-- | A monad that has read and write access to the stConcreteNames
--   part of the TCState. Basically, this is a synonym for `MonadState
--   ConcreteNames m` (which cannot be used directly because of the
--   limitations of Haskell's typeclass system).
class Monad m => MonadStConcreteNames m where
  runStConcreteNames :: StateT ConcreteNames m a -> m a

  useConcreteNames :: m ConcreteNames
  useConcreteNames = StateT ConcreteNames m ConcreteNames -> m ConcreteNames
forall a. StateT ConcreteNames m a -> m a
forall (m :: * -> *) a.
MonadStConcreteNames m =>
StateT ConcreteNames m a -> m a
runStConcreteNames StateT ConcreteNames m ConcreteNames
forall s (m :: * -> *). MonadState s m => m s
get

  modifyConcreteNames :: (ConcreteNames -> ConcreteNames) -> m ()
  modifyConcreteNames = StateT ConcreteNames m () -> m ()
forall a. StateT ConcreteNames m a -> m a
forall (m :: * -> *) a.
MonadStConcreteNames m =>
StateT ConcreteNames m a -> m a
runStConcreteNames (StateT ConcreteNames m () -> m ())
-> ((ConcreteNames -> ConcreteNames) -> StateT ConcreteNames m ())
-> (ConcreteNames -> ConcreteNames)
-> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ConcreteNames -> ConcreteNames) -> StateT ConcreteNames m ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify

instance MonadStConcreteNames TCM where
  runStConcreteNames :: forall a. StateT ConcreteNames (TCMT IO) a -> TCM a
runStConcreteNames StateT ConcreteNames (TCMT IO) a
m =
    TCM a -> TCM a -> TCM a
forall a. TCM a -> TCM a -> TCM a
ifImpureConv (Lens' TCState ConcreteNames
-> (ConcreteNames -> TCMT IO (a, ConcreteNames)) -> TCM a
forall (m :: * -> *) a r.
(MonadTCState m, ReadTCState m) =>
Lens' TCState a -> (a -> m (r, a)) -> m r
stateTCLensM (ConcreteNames -> f ConcreteNames) -> TCState -> f TCState
Lens' TCState ConcreteNames
stConcreteNames ((ConcreteNames -> TCMT IO (a, ConcreteNames)) -> TCM a)
-> (ConcreteNames -> TCMT IO (a, ConcreteNames)) -> TCM a
forall a b. (a -> b) -> a -> b
$ StateT ConcreteNames (TCMT IO) a
-> ConcreteNames -> TCMT IO (a, ConcreteNames)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT StateT ConcreteNames (TCMT IO) a
m) (TCM a -> TCM a) -> TCM a -> TCM a
forall a b. (a -> b) -> a -> b
$ do
      concNames <- Lens' TCState ConcreteNames -> TCM ConcreteNames
forall (m :: * -> *) a. ReadTCState m => Lens' TCState a -> m a
useR (ConcreteNames -> f ConcreteNames) -> TCState -> f TCState
Lens' TCState ConcreteNames
stConcreteNames
      evalStateT m concNames

-- | The concrete names get lost in case of an exception.
instance MonadStConcreteNames m => MonadStConcreteNames (ExceptT e m) where
  runStConcreteNames :: forall a. StateT ConcreteNames (ExceptT e m) a -> ExceptT e m a
runStConcreteNames StateT ConcreteNames (ExceptT e m) a
m = m (Either e a) -> ExceptT e m a
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (m (Either e a) -> ExceptT e m a)
-> m (Either e a) -> ExceptT e m a
forall a b. (a -> b) -> a -> b
$ StateT ConcreteNames m (Either e a) -> m (Either e a)
forall a. StateT ConcreteNames m a -> m a
forall (m :: * -> *) a.
MonadStConcreteNames m =>
StateT ConcreteNames m a -> m a
runStConcreteNames (StateT ConcreteNames m (Either e a) -> m (Either e a))
-> StateT ConcreteNames m (Either e a) -> m (Either e a)
forall a b. (a -> b) -> a -> b
$ (ConcreteNames -> m (Either e a, ConcreteNames))
-> StateT ConcreteNames m (Either e a)
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((ConcreteNames -> m (Either e a, ConcreteNames))
 -> StateT ConcreteNames m (Either e a))
-> (ConcreteNames -> m (Either e a, ConcreteNames))
-> StateT ConcreteNames m (Either e a)
forall a b. (a -> b) -> a -> b
$ \ ConcreteNames
ns -> do
    ExceptT e m (a, ConcreteNames) -> m (Either e (a, ConcreteNames))
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (StateT ConcreteNames (ExceptT e m) a
-> ConcreteNames -> ExceptT e m (a, ConcreteNames)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT StateT ConcreteNames (ExceptT e m) a
m ConcreteNames
ns) m (Either e (a, ConcreteNames))
-> (Either e (a, ConcreteNames) -> (Either e a, ConcreteNames))
-> m (Either e a, ConcreteNames)
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \case
      Left e
e         -> (e -> Either e a
forall a b. a -> Either a b
Left e
e, ConcreteNames
forall a. Monoid a => a
mempty)
      Right (a
x, ConcreteNames
ns') -> (a -> Either e a
forall a b. b -> Either a b
Right a
x, ConcreteNames
ns')

instance MonadStConcreteNames m => MonadStConcreteNames (IdentityT m) where
  runStConcreteNames :: forall a. StateT ConcreteNames (IdentityT m) a -> IdentityT m a
runStConcreteNames StateT ConcreteNames (IdentityT m) a
m = m a -> IdentityT m a
forall {k} (f :: k -> *) (a :: k). f a -> IdentityT f a
IdentityT (m a -> IdentityT m a) -> m a -> IdentityT m a
forall a b. (a -> b) -> a -> b
$ StateT ConcreteNames m a -> m a
forall a. StateT ConcreteNames m a -> m a
forall (m :: * -> *) a.
MonadStConcreteNames m =>
StateT ConcreteNames m a -> m a
runStConcreteNames (StateT ConcreteNames m a -> m a)
-> StateT ConcreteNames m a -> m a
forall a b. (a -> b) -> a -> b
$ (ConcreteNames -> m (a, ConcreteNames)) -> StateT ConcreteNames m a
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((ConcreteNames -> m (a, ConcreteNames))
 -> StateT ConcreteNames m a)
-> (ConcreteNames -> m (a, ConcreteNames))
-> StateT ConcreteNames m a
forall a b. (a -> b) -> a -> b
$ IdentityT m (a, ConcreteNames) -> m (a, ConcreteNames)
forall {k} (f :: k -> *) (a :: k). IdentityT f a -> f a
runIdentityT (IdentityT m (a, ConcreteNames) -> m (a, ConcreteNames))
-> (ConcreteNames -> IdentityT m (a, ConcreteNames))
-> ConcreteNames
-> m (a, ConcreteNames)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. StateT ConcreteNames (IdentityT m) a
-> ConcreteNames -> IdentityT m (a, ConcreteNames)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT StateT ConcreteNames (IdentityT m) a
m

instance MonadStConcreteNames m => MonadStConcreteNames (MaybeT m) where
  runStConcreteNames :: forall a. StateT ConcreteNames (MaybeT m) a -> MaybeT m a
runStConcreteNames StateT ConcreteNames (MaybeT m) a
m = m (Maybe a) -> MaybeT m a
forall (m :: * -> *) a. m (Maybe a) -> MaybeT m a
MaybeT (m (Maybe a) -> MaybeT m a) -> m (Maybe a) -> MaybeT m a
forall a b. (a -> b) -> a -> b
$ StateT ConcreteNames m (Maybe a) -> m (Maybe a)
forall a. StateT ConcreteNames m a -> m a
forall (m :: * -> *) a.
MonadStConcreteNames m =>
StateT ConcreteNames m a -> m a
runStConcreteNames (StateT ConcreteNames m (Maybe a) -> m (Maybe a))
-> StateT ConcreteNames m (Maybe a) -> m (Maybe a)
forall a b. (a -> b) -> a -> b
$ (ConcreteNames -> m (Maybe a, ConcreteNames))
-> StateT ConcreteNames m (Maybe a)
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((ConcreteNames -> m (Maybe a, ConcreteNames))
 -> StateT ConcreteNames m (Maybe a))
-> (ConcreteNames -> m (Maybe a, ConcreteNames))
-> StateT ConcreteNames m (Maybe a)
forall a b. (a -> b) -> a -> b
$ \ ConcreteNames
ns -> do
    MaybeT m (a, ConcreteNames) -> m (Maybe (a, ConcreteNames))
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (StateT ConcreteNames (MaybeT m) a
-> ConcreteNames -> MaybeT m (a, ConcreteNames)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT StateT ConcreteNames (MaybeT m) a
m ConcreteNames
ns) m (Maybe (a, ConcreteNames))
-> (Maybe (a, ConcreteNames) -> (Maybe a, ConcreteNames))
-> m (Maybe a, ConcreteNames)
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \case
      Maybe (a, ConcreteNames)
Nothing       -> (Maybe a
forall a. Maybe a
Nothing, ConcreteNames
forall a. Monoid a => a
mempty)
      Just (a
x, ConcreteNames
ns') -> (a -> Maybe a
forall a. a -> Maybe a
Just a
x, ConcreteNames
ns')

instance MonadStConcreteNames m => MonadStConcreteNames (ReaderT r m) where
  runStConcreteNames :: forall a. StateT ConcreteNames (ReaderT r m) a -> ReaderT r m a
runStConcreteNames StateT ConcreteNames (ReaderT r m) a
m = (r -> m a) -> ReaderT r m a
forall r (m :: * -> *) a. (r -> m a) -> ReaderT r m a
ReaderT ((r -> m a) -> ReaderT r m a) -> (r -> m a) -> ReaderT r m a
forall a b. (a -> b) -> a -> b
$ StateT ConcreteNames m a -> m a
forall a. StateT ConcreteNames m a -> m a
forall (m :: * -> *) a.
MonadStConcreteNames m =>
StateT ConcreteNames m a -> m a
runStConcreteNames (StateT ConcreteNames m a -> m a)
-> (r -> StateT ConcreteNames m a) -> r -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ConcreteNames -> m (a, ConcreteNames)) -> StateT ConcreteNames m a
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((ConcreteNames -> m (a, ConcreteNames))
 -> StateT ConcreteNames m a)
-> (r -> ConcreteNames -> m (a, ConcreteNames))
-> r
-> StateT ConcreteNames m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ConcreteNames -> r -> m (a, ConcreteNames))
-> r -> ConcreteNames -> m (a, ConcreteNames)
forall a b c. (a -> b -> c) -> b -> a -> c
flip (ReaderT r m (a, ConcreteNames) -> r -> m (a, ConcreteNames)
forall r (m :: * -> *) a. ReaderT r m a -> r -> m a
runReaderT (ReaderT r m (a, ConcreteNames) -> r -> m (a, ConcreteNames))
-> (ConcreteNames -> ReaderT r m (a, ConcreteNames))
-> ConcreteNames
-> r
-> m (a, ConcreteNames)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. StateT ConcreteNames (ReaderT r m) a
-> ConcreteNames -> ReaderT r m (a, ConcreteNames)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT StateT ConcreteNames (ReaderT r m) a
m)

instance MonadStConcreteNames m => MonadStConcreteNames (StateT s m) where
  runStConcreteNames :: forall a. StateT ConcreteNames (StateT s m) a -> StateT s m a
runStConcreteNames StateT ConcreteNames (StateT s m) a
m = (s -> m (a, s)) -> StateT s m a
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((s -> m (a, s)) -> StateT s m a)
-> (s -> m (a, s)) -> StateT s m a
forall a b. (a -> b) -> a -> b
$ \s
s -> StateT ConcreteNames m (a, s) -> m (a, s)
forall a. StateT ConcreteNames m a -> m a
forall (m :: * -> *) a.
MonadStConcreteNames m =>
StateT ConcreteNames m a -> m a
runStConcreteNames (StateT ConcreteNames m (a, s) -> m (a, s))
-> StateT ConcreteNames m (a, s) -> m (a, s)
forall a b. (a -> b) -> a -> b
$ (ConcreteNames -> m ((a, s), ConcreteNames))
-> StateT ConcreteNames m (a, s)
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((ConcreteNames -> m ((a, s), ConcreteNames))
 -> StateT ConcreteNames m (a, s))
-> (ConcreteNames -> m ((a, s), ConcreteNames))
-> StateT ConcreteNames m (a, s)
forall a b. (a -> b) -> a -> b
$ \ConcreteNames
ns -> do
    ((x,ns'),s') <- StateT s m (a, ConcreteNames) -> s -> m ((a, ConcreteNames), s)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT (StateT ConcreteNames (StateT s m) a
-> ConcreteNames -> StateT s m (a, ConcreteNames)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT StateT ConcreteNames (StateT s m) a
m ConcreteNames
ns) s
s
    return ((x,s'),ns')

instance (MonadStConcreteNames m, Monoid w) => MonadStConcreteNames (WriterT w m) where
  runStConcreteNames :: forall a. StateT ConcreteNames (WriterT w m) a -> WriterT w m a
runStConcreteNames StateT ConcreteNames (WriterT w m) a
m = m (a, w) -> WriterT w m a
forall w (m :: * -> *) a. m (a, w) -> WriterT w m a
WriterT (m (a, w) -> WriterT w m a) -> m (a, w) -> WriterT w m a
forall a b. (a -> b) -> a -> b
$ StateT ConcreteNames m (a, w) -> m (a, w)
forall a. StateT ConcreteNames m a -> m a
forall (m :: * -> *) a.
MonadStConcreteNames m =>
StateT ConcreteNames m a -> m a
runStConcreteNames (StateT ConcreteNames m (a, w) -> m (a, w))
-> StateT ConcreteNames m (a, w) -> m (a, w)
forall a b. (a -> b) -> a -> b
$ (ConcreteNames -> m ((a, w), ConcreteNames))
-> StateT ConcreteNames m (a, w)
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((ConcreteNames -> m ((a, w), ConcreteNames))
 -> StateT ConcreteNames m (a, w))
-> (ConcreteNames -> m ((a, w), ConcreteNames))
-> StateT ConcreteNames m (a, w)
forall a b. (a -> b) -> a -> b
$ \ ConcreteNames
ns -> do
    ((x,ns'),w) <- WriterT w m (a, ConcreteNames) -> m ((a, ConcreteNames), w)
forall w (m :: * -> *) a. WriterT w m a -> m (a, w)
runWriterT (WriterT w m (a, ConcreteNames) -> m ((a, ConcreteNames), w))
-> WriterT w m (a, ConcreteNames) -> m ((a, ConcreteNames), w)
forall a b. (a -> b) -> a -> b
$ StateT ConcreteNames (WriterT w m) a
-> ConcreteNames -> WriterT w m (a, ConcreteNames)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT StateT ConcreteNames (WriterT w m) a
m ConcreteNames
ns
    return ((x,w),ns')

----------------------------------------------------------------------------------------------------
-- * File handling
----------------------------------------------------------------------------------------------------

instance GetFileId FileDictWithBuiltins where
  getFileId :: HasCallStack => FileDictWithBuiltins -> AbsolutePath -> FileId
getFileId = FileDictBuilder -> AbsolutePath -> FileId
forall a.
(GetFileId a, HasCallStack) =>
a -> AbsolutePath -> FileId
getFileId (FileDictBuilder -> AbsolutePath -> FileId)
-> (FileDictWithBuiltins -> FileDictBuilder)
-> FileDictWithBuiltins
-> AbsolutePath
-> FileId
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileDictWithBuiltins -> FileDictBuilder
fileDictBuilder

instance GetIdFile FileDictWithBuiltins where
  getIdFile :: FileDictWithBuiltins -> FileId -> AbsolutePath
getIdFile = FileDictBuilder -> FileId -> AbsolutePath
forall a. GetIdFile a => a -> FileId -> AbsolutePath
getIdFile (FileDictBuilder -> FileId -> AbsolutePath)
-> (FileDictWithBuiltins -> FileDictBuilder)
-> FileDictWithBuiltins
-> FileId
-> AbsolutePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileDictWithBuiltins -> FileDictBuilder
fileDictBuilder

-- | Get the file name of a 'SourceFile'.

srcFilePath :: MonadFileId m => SourceFile -> m AbsolutePath
srcFilePath :: forall (m :: * -> *). MonadFileId m => SourceFile -> m AbsolutePath
srcFilePath (SourceFile FileId
fi) = FileId -> m AbsolutePath
forall (m :: * -> *).
(MonadFileId m, HasCallStack) =>
FileId -> m AbsolutePath
fileFromId FileId
fi

-- | Get make a 'SourceFile' from a file name.
srcFromPath :: MonadFileId m => AbsolutePath -> m SourceFile
srcFromPath :: forall (m :: * -> *). MonadFileId m => AbsolutePath -> m SourceFile
srcFromPath AbsolutePath
p = FileId -> SourceFile
SourceFile (FileId -> SourceFile) -> m FileId -> m SourceFile
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> AbsolutePath -> m FileId
forall (m :: * -> *). MonadFileId m => AbsolutePath -> m FileId
idFromFile AbsolutePath
p

instance Pretty ModuleToSource where
  pretty :: ModuleToSource -> Doc
pretty (ModuleToSource FileDictWithBuiltins
dict ModuleToSourceId
mods) = [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
    [ [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
hsep [ Doc
"-", TopLevelModuleName -> Doc
forall a. Pretty a => a -> Doc
pretty TopLevelModuleName
m, Doc
"->", AbsolutePath -> Doc
forall a. Pretty a => a -> Doc
pretty (AbsolutePath -> Doc) -> AbsolutePath -> Doc
forall a b. (a -> b) -> a -> b
$ FileDictWithBuiltins -> FileId -> AbsolutePath
forall a. GetIdFile a => a -> FileId -> AbsolutePath
getIdFile FileDictWithBuiltins
dict FileId
i ]
    | (TopLevelModuleName
m, SourceFile FileId
i) <- ModuleToSourceId -> [(TopLevelModuleName, SourceFile)]
forall k a. Map k a -> [(k, a)]
Map.toList ModuleToSourceId
mods
    ]

-- | Lookup the path of a top level module name, which must be a known one.

topLevelModuleFilePath :: HasCallStack => ModuleToSource -> TopLevelModuleName -> AbsolutePath
topLevelModuleFilePath :: HasCallStack =>
ModuleToSource -> TopLevelModuleName -> AbsolutePath
topLevelModuleFilePath (ModuleToSource FileDictWithBuiltins
dict ModuleToSourceId
m2s) TopLevelModuleName
m =
  FileDictWithBuiltins -> FileId -> AbsolutePath
forall a. GetIdFile a => a -> FileId -> AbsolutePath
getIdFile FileDictWithBuiltins
dict (FileId -> AbsolutePath) -> FileId -> AbsolutePath
forall a b. (a -> b) -> a -> b
$ SourceFile -> FileId
srcFileId (SourceFile -> FileId) -> SourceFile -> FileId
forall a b. (a -> b) -> a -> b
$ SourceFile -> TopLevelModuleName -> ModuleToSourceId -> SourceFile
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault SourceFile
forall a. HasCallStack => a
__IMPOSSIBLE__ TopLevelModuleName
m ModuleToSourceId
m2s

-- | The contents of a file we have read.
data ReadFile = ReadFile
  { ReadFile -> Text
readFileText :: !Text
    -- ^ The file's textual content.
  , ReadFile -> Word64
readFileHash :: !Hash
    -- ^ The hash of the file's contents at the time it was read.
  , ReadFile -> Word
readFileEra  :: !Word
    -- ^ The "era" during which the file was read. See 'ReadFileCache'.
  }
  deriving (Int -> ReadFile -> ShowS
[ReadFile] -> ShowS
ReadFile -> String
(Int -> ReadFile -> ShowS)
-> (ReadFile -> String) -> ([ReadFile] -> ShowS) -> Show ReadFile
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ReadFile -> ShowS
showsPrec :: Int -> ReadFile -> ShowS
$cshow :: ReadFile -> String
show :: ReadFile -> String
$cshowList :: [ReadFile] -> ShowS
showList :: [ReadFile] -> ShowS
Show, (forall x. ReadFile -> Rep ReadFile x)
-> (forall x. Rep ReadFile x -> ReadFile) -> Generic ReadFile
forall x. Rep ReadFile x -> ReadFile
forall x. ReadFile -> Rep ReadFile x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ReadFile -> Rep ReadFile x
from :: forall x. ReadFile -> Rep ReadFile x
$cto :: forall x. Rep ReadFile x -> ReadFile
to :: forall x. Rep ReadFile x -> ReadFile
Generic)

-- | A cache for reading and hashing files.
data ReadFileCache = ReadFileCache
  { ReadFileCache -> Word
rfcEra   :: !Word
    -- ^ The "era" we are currently in.
    --
    -- Read files are stamped with this value to know when there is a
    -- possibility that our view of the file system has gone stale and
    -- needs to be updated.
    -- The 'rfcEra' value is incremented whenever we call
    -- 'typeCheckMain'.
  , ReadFileCache -> HashMap AbsolutePath ReadFile
rfcFiles :: !(HashMap AbsolutePath ReadFile)
    -- ^ The actual mapping from 'AbsolutePaths' to 'ReadFile's.
    --
    -- Because it uses 'AbsolutePaths', it does not need to be
    -- invalidated when include paths change.
  }
  deriving (Int -> ReadFileCache -> ShowS
[ReadFileCache] -> ShowS
ReadFileCache -> String
(Int -> ReadFileCache -> ShowS)
-> (ReadFileCache -> String)
-> ([ReadFileCache] -> ShowS)
-> Show ReadFileCache
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ReadFileCache -> ShowS
showsPrec :: Int -> ReadFileCache -> ShowS
$cshow :: ReadFileCache -> String
show :: ReadFileCache -> String
$cshowList :: [ReadFileCache] -> ShowS
showList :: [ReadFileCache] -> ShowS
Show, (forall x. ReadFileCache -> Rep ReadFileCache x)
-> (forall x. Rep ReadFileCache x -> ReadFileCache)
-> Generic ReadFileCache
forall x. Rep ReadFileCache x -> ReadFileCache
forall x. ReadFileCache -> Rep ReadFileCache x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ReadFileCache -> Rep ReadFileCache x
from :: forall x. ReadFileCache -> Rep ReadFileCache x
$cto :: forall x. Rep ReadFileCache x -> ReadFileCache
to :: forall x. Rep ReadFileCache x -> ReadFileCache
Generic)

instance Null ReadFileCache where
  empty :: ReadFileCache
empty = Word -> HashMap AbsolutePath ReadFile -> ReadFileCache
ReadFileCache Word
0 HashMap AbsolutePath ReadFile
forall a. Null a => a
empty
  null :: ReadFileCache -> Bool
null (ReadFileCache Word
n HashMap AbsolutePath ReadFile
m) = Word
n Word -> Word -> Bool
forall a. Eq a => a -> a -> Bool
== Word
0 Bool -> Bool -> Bool
&& HashMap AbsolutePath ReadFile -> Bool
forall a. Null a => a -> Bool
null HashMap AbsolutePath ReadFile
m

class HasFileEra a where
  lensEra :: Lens' a Word

instance HasFileEra ReadFile where
  {-# INLINE lensEra #-}
  lensEra :: Lens' ReadFile Word
lensEra Word -> f Word
f ReadFile
s = Word -> f Word
f (ReadFile -> Word
readFileEra ReadFile
s) f Word -> (Word -> ReadFile) -> f ReadFile
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \Word
e -> ReadFile
s { readFileEra = e }

instance HasFileEra ReadFileCache where
  {-# INLINE lensEra #-}
  lensEra :: Lens' ReadFileCache Word
lensEra Word -> f Word
f ReadFileCache
s = Word -> f Word
f (ReadFileCache -> Word
rfcEra ReadFileCache
s) f Word -> (Word -> ReadFileCache) -> f ReadFileCache
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \Word
e -> ReadFileCache
s { rfcEra = e }

lensRfcFiles :: Lens' ReadFileCache (HashMap AbsolutePath ReadFile)
lensRfcFiles :: Lens' ReadFileCache (HashMap AbsolutePath ReadFile)
lensRfcFiles HashMap AbsolutePath ReadFile -> f (HashMap AbsolutePath ReadFile)
f ReadFileCache
s = HashMap AbsolutePath ReadFile -> f (HashMap AbsolutePath ReadFile)
f (ReadFileCache -> HashMap AbsolutePath ReadFile
rfcFiles ReadFileCache
s) f (HashMap AbsolutePath ReadFile)
-> (HashMap AbsolutePath ReadFile -> ReadFileCache)
-> f ReadFileCache
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \HashMap AbsolutePath ReadFile
e -> ReadFileCache
s { rfcFiles = e }

type instance Index ReadFileCache = AbsolutePath
type instance IxValue ReadFileCache = ReadFile
instance Ixed ReadFileCache where
  ix :: Index ReadFileCache
-> Traversal' ReadFileCache (IxValue ReadFileCache)
ix Index ReadFileCache
k = Index ReadFileCache
-> Lens' ReadFileCache (Maybe (IxValue ReadFileCache))
forall m. At m => Index m -> Lens' m (Maybe (IxValue m))
at Index ReadFileCache
k ((Maybe ReadFile -> f (Maybe ReadFile))
 -> ReadFileCache -> f ReadFileCache)
-> ((ReadFile -> f ReadFile)
    -> Maybe ReadFile -> f (Maybe ReadFile))
-> (ReadFile -> f ReadFile)
-> ReadFileCache
-> f ReadFileCache
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ReadFile -> f ReadFile) -> Maybe ReadFile -> f (Maybe ReadFile)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Maybe a -> f (Maybe b)
traverse
  {-# INLINE ix #-}

instance At ReadFileCache where
  -- The Control.Lens.At impl for HashMap is lazy.
  -- Also, HMap.alterF (both versions) have crazy RULES for turning into
  -- the other combinators instead of the naïve implementation from
  -- lens.
  at :: Index ReadFileCache
-> Lens' ReadFileCache (Maybe (IxValue ReadFileCache))
at Index ReadFileCache
k = (HashMap AbsolutePath ReadFile
 -> f (HashMap AbsolutePath ReadFile))
-> ReadFileCache -> f ReadFileCache
Lens' ReadFileCache (HashMap AbsolutePath ReadFile)
lensRfcFiles ((HashMap AbsolutePath ReadFile
  -> f (HashMap AbsolutePath ReadFile))
 -> ReadFileCache -> f ReadFileCache)
-> ((Maybe ReadFile -> f (Maybe ReadFile))
    -> HashMap AbsolutePath ReadFile
    -> f (HashMap AbsolutePath ReadFile))
-> (Maybe ReadFile -> f (Maybe ReadFile))
-> ReadFileCache
-> f ReadFileCache
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Maybe ReadFile -> f (Maybe ReadFile))
 -> AbsolutePath
 -> HashMap AbsolutePath ReadFile
 -> f (HashMap AbsolutePath ReadFile))
-> AbsolutePath
-> (Maybe ReadFile -> f (Maybe ReadFile))
-> HashMap AbsolutePath ReadFile
-> f (HashMap AbsolutePath ReadFile)
forall a b c. (a -> b -> c) -> b -> a -> c
flip (Maybe ReadFile -> f (Maybe ReadFile))
-> AbsolutePath
-> HashMap AbsolutePath ReadFile
-> f (HashMap AbsolutePath ReadFile)
forall (f :: * -> *) k v.
(Functor f, Eq k, Hashable k) =>
(Maybe v -> f (Maybe v)) -> k -> HashMap k v -> f (HashMap k v)
HMap.alterF Index ReadFileCache
AbsolutePath
k
  {-# INLINE at #-}

----------------------------------------------------------------------------------------------------
-- * Interface
----------------------------------------------------------------------------------------------------

-- | Distinguishes between type-checked and scope-checked interfaces
--   when stored in the map of `VisitedModules`.
data ModuleCheckMode
  = ModuleScopeChecked
  | ModuleTypeChecked
  deriving (ModuleCheckMode -> ModuleCheckMode -> Bool
(ModuleCheckMode -> ModuleCheckMode -> Bool)
-> (ModuleCheckMode -> ModuleCheckMode -> Bool)
-> Eq ModuleCheckMode
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ModuleCheckMode -> ModuleCheckMode -> Bool
== :: ModuleCheckMode -> ModuleCheckMode -> Bool
$c/= :: ModuleCheckMode -> ModuleCheckMode -> Bool
/= :: ModuleCheckMode -> ModuleCheckMode -> Bool
Eq, Eq ModuleCheckMode
Eq ModuleCheckMode =>
(ModuleCheckMode -> ModuleCheckMode -> Ordering)
-> (ModuleCheckMode -> ModuleCheckMode -> Bool)
-> (ModuleCheckMode -> ModuleCheckMode -> Bool)
-> (ModuleCheckMode -> ModuleCheckMode -> Bool)
-> (ModuleCheckMode -> ModuleCheckMode -> Bool)
-> (ModuleCheckMode -> ModuleCheckMode -> ModuleCheckMode)
-> (ModuleCheckMode -> ModuleCheckMode -> ModuleCheckMode)
-> Ord ModuleCheckMode
ModuleCheckMode -> ModuleCheckMode -> Bool
ModuleCheckMode -> ModuleCheckMode -> Ordering
ModuleCheckMode -> ModuleCheckMode -> ModuleCheckMode
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: ModuleCheckMode -> ModuleCheckMode -> Ordering
compare :: ModuleCheckMode -> ModuleCheckMode -> Ordering
$c< :: ModuleCheckMode -> ModuleCheckMode -> Bool
< :: ModuleCheckMode -> ModuleCheckMode -> Bool
$c<= :: ModuleCheckMode -> ModuleCheckMode -> Bool
<= :: ModuleCheckMode -> ModuleCheckMode -> Bool
$c> :: ModuleCheckMode -> ModuleCheckMode -> Bool
> :: ModuleCheckMode -> ModuleCheckMode -> Bool
$c>= :: ModuleCheckMode -> ModuleCheckMode -> Bool
>= :: ModuleCheckMode -> ModuleCheckMode -> Bool
$cmax :: ModuleCheckMode -> ModuleCheckMode -> ModuleCheckMode
max :: ModuleCheckMode -> ModuleCheckMode -> ModuleCheckMode
$cmin :: ModuleCheckMode -> ModuleCheckMode -> ModuleCheckMode
min :: ModuleCheckMode -> ModuleCheckMode -> ModuleCheckMode
Ord, ModuleCheckMode
ModuleCheckMode -> ModuleCheckMode -> Bounded ModuleCheckMode
forall a. a -> a -> Bounded a
$cminBound :: ModuleCheckMode
minBound :: ModuleCheckMode
$cmaxBound :: ModuleCheckMode
maxBound :: ModuleCheckMode
Bounded, Int -> ModuleCheckMode
ModuleCheckMode -> Int
ModuleCheckMode -> [ModuleCheckMode]
ModuleCheckMode -> ModuleCheckMode
ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode]
ModuleCheckMode
-> ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode]
(ModuleCheckMode -> ModuleCheckMode)
-> (ModuleCheckMode -> ModuleCheckMode)
-> (Int -> ModuleCheckMode)
-> (ModuleCheckMode -> Int)
-> (ModuleCheckMode -> [ModuleCheckMode])
-> (ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode])
-> (ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode])
-> (ModuleCheckMode
    -> ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode])
-> Enum ModuleCheckMode
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: ModuleCheckMode -> ModuleCheckMode
succ :: ModuleCheckMode -> ModuleCheckMode
$cpred :: ModuleCheckMode -> ModuleCheckMode
pred :: ModuleCheckMode -> ModuleCheckMode
$ctoEnum :: Int -> ModuleCheckMode
toEnum :: Int -> ModuleCheckMode
$cfromEnum :: ModuleCheckMode -> Int
fromEnum :: ModuleCheckMode -> Int
$cenumFrom :: ModuleCheckMode -> [ModuleCheckMode]
enumFrom :: ModuleCheckMode -> [ModuleCheckMode]
$cenumFromThen :: ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode]
enumFromThen :: ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode]
$cenumFromTo :: ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode]
enumFromTo :: ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode]
$cenumFromThenTo :: ModuleCheckMode
-> ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode]
enumFromThenTo :: ModuleCheckMode
-> ModuleCheckMode -> ModuleCheckMode -> [ModuleCheckMode]
Enum, Int -> ModuleCheckMode -> ShowS
[ModuleCheckMode] -> ShowS
ModuleCheckMode -> String
(Int -> ModuleCheckMode -> ShowS)
-> (ModuleCheckMode -> String)
-> ([ModuleCheckMode] -> ShowS)
-> Show ModuleCheckMode
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ModuleCheckMode -> ShowS
showsPrec :: Int -> ModuleCheckMode -> ShowS
$cshow :: ModuleCheckMode -> String
show :: ModuleCheckMode -> String
$cshowList :: [ModuleCheckMode] -> ShowS
showList :: [ModuleCheckMode] -> ShowS
Show, (forall x. ModuleCheckMode -> Rep ModuleCheckMode x)
-> (forall x. Rep ModuleCheckMode x -> ModuleCheckMode)
-> Generic ModuleCheckMode
forall x. Rep ModuleCheckMode x -> ModuleCheckMode
forall x. ModuleCheckMode -> Rep ModuleCheckMode x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ModuleCheckMode -> Rep ModuleCheckMode x
from :: forall x. ModuleCheckMode -> Rep ModuleCheckMode x
$cto :: forall x. Rep ModuleCheckMode x -> ModuleCheckMode
to :: forall x. Rep ModuleCheckMode x -> ModuleCheckMode
Generic)


data ModuleInfo = ModuleInfo
  { ModuleInfo -> Interface
miInterface  :: Interface
  , ModuleInfo -> Set TCWarning
miWarnings   :: Set TCWarning
    -- ^ Warnings were encountered when the module was type checked.
    --   These might include warnings not stored in the interface itself,
    --   specifically unsolved interaction metas.
    --   See "Agda.Interaction.Imports"
  , ModuleInfo -> Bool
miPrimitive  :: Bool
    -- ^ 'True' if the module is a primitive module, which should always
    -- be importable.
  , ModuleInfo -> ModuleCheckMode
miMode       :: ModuleCheckMode
    -- ^ The `ModuleCheckMode` used to create the `Interface`
  , ModuleInfo -> SourceFile
miSourceFile :: SourceFile
    -- ^ The file belonging to the module.
  }
  deriving (forall x. ModuleInfo -> Rep ModuleInfo x)
-> (forall x. Rep ModuleInfo x -> ModuleInfo) -> Generic ModuleInfo
forall x. Rep ModuleInfo x -> ModuleInfo
forall x. ModuleInfo -> Rep ModuleInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ModuleInfo -> Rep ModuleInfo x
from :: forall x. ModuleInfo -> Rep ModuleInfo x
$cto :: forall x. Rep ModuleInfo x -> ModuleInfo
to :: forall x. Rep ModuleInfo x -> ModuleInfo
Generic

type VisitedModules = Map TopLevelModuleName ModuleInfo
type DecodedModules = Map TopLevelModuleName ModuleInfo

data ForeignCode = ForeignCode Range String
  deriving (Int -> ForeignCode -> ShowS
[ForeignCode] -> ShowS
ForeignCode -> String
(Int -> ForeignCode -> ShowS)
-> (ForeignCode -> String)
-> ([ForeignCode] -> ShowS)
-> Show ForeignCode
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ForeignCode -> ShowS
showsPrec :: Int -> ForeignCode -> ShowS
$cshow :: ForeignCode -> String
show :: ForeignCode -> String
$cshowList :: [ForeignCode] -> ShowS
showList :: [ForeignCode] -> ShowS
Show, (forall x. ForeignCode -> Rep ForeignCode x)
-> (forall x. Rep ForeignCode x -> ForeignCode)
-> Generic ForeignCode
forall x. Rep ForeignCode x -> ForeignCode
forall x. ForeignCode -> Rep ForeignCode x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ForeignCode -> Rep ForeignCode x
from :: forall x. ForeignCode -> Rep ForeignCode x
$cto :: forall x. Rep ForeignCode x -> ForeignCode
to :: forall x. Rep ForeignCode x -> ForeignCode
Generic)

-- | Foreign code fragments are stored in reversed order to support efficient appending:
--   head points to the latest pragma in module.
newtype ForeignCodeStack = ForeignCodeStack
  { ForeignCodeStack -> [ForeignCode]
getForeignCodeStack :: [ForeignCode]
  } deriving (Int -> ForeignCodeStack -> ShowS
[ForeignCodeStack] -> ShowS
ForeignCodeStack -> String
(Int -> ForeignCodeStack -> ShowS)
-> (ForeignCodeStack -> String)
-> ([ForeignCodeStack] -> ShowS)
-> Show ForeignCodeStack
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ForeignCodeStack -> ShowS
showsPrec :: Int -> ForeignCodeStack -> ShowS
$cshow :: ForeignCodeStack -> String
show :: ForeignCodeStack -> String
$cshowList :: [ForeignCodeStack] -> ShowS
showList :: [ForeignCodeStack] -> ShowS
Show, (forall x. ForeignCodeStack -> Rep ForeignCodeStack x)
-> (forall x. Rep ForeignCodeStack x -> ForeignCodeStack)
-> Generic ForeignCodeStack
forall x. Rep ForeignCodeStack x -> ForeignCodeStack
forall x. ForeignCodeStack -> Rep ForeignCodeStack x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ForeignCodeStack -> Rep ForeignCodeStack x
from :: forall x. ForeignCodeStack -> Rep ForeignCodeStack x
$cto :: forall x. Rep ForeignCodeStack x -> ForeignCodeStack
to :: forall x. Rep ForeignCodeStack x -> ForeignCodeStack
Generic, ForeignCodeStack -> ()
(ForeignCodeStack -> ()) -> NFData ForeignCodeStack
forall a. (a -> ()) -> NFData a
$crnf :: ForeignCodeStack -> ()
rnf :: ForeignCodeStack -> ()
NFData)

data Interface = Interface
  { Interface -> Word64
iSourceHash      :: !Hash
    -- ^ Hash of the source code.
  , Interface -> Text
iSource          :: Text
    -- ^ The source code. The source code is stored so that the HTML
    -- and LaTeX backends can generate their output without having to
    -- re-read the (possibly out of date) source code.
  , Interface -> FileType
iFileType        :: FileType
    -- ^ Source file type, determined from the file extension
  , Interface -> [(TopLevelModuleName, Word64)]
iImportedModules :: [(TopLevelModuleName, Hash)]
    -- ^ Imported modules and their hashes.
  , Interface -> ModuleName
iModuleName      :: ModuleName
    -- ^ Module name of this interface.
  , Interface -> TopLevelModuleName
iTopLevelModuleName :: TopLevelModuleName
    -- ^ The module's top-level module name.
  , Interface -> Map ModuleName Scope
iScope           :: Map ModuleName Scope
    -- ^ Scope defined by this module.
    --
    --   Andreas, AIM XX: Too avoid duplicate serialization, this field is
    --   not serialized, so if you deserialize an interface, @iScope@
    --   will be empty.
    --   But 'constructIScope' constructs 'iScope' from 'iInsideScope'.
  , Interface -> ScopeInfo
iInsideScope     :: ScopeInfo
    -- ^ Scope after we loaded this interface.
    --   Used in 'Agda.Interaction.BasicOps.AtTopLevel'
    --   and     'Agda.Interaction.CommandLine.interactionLoop'.
  , Interface -> Signature
iSignature       :: Signature
  , Interface -> RemoteMetaStore
iMetaBindings    :: RemoteMetaStore
    -- ^ Instantiations for meta-variables that come from this module.
  , Interface -> DisplayForms
iDisplayForms    :: DisplayForms
    -- ^ Display forms added for imported identifiers.
  , Interface -> UserWarnings
iUserWarnings    :: UserWarnings
    -- ^ User warnings for imported identifiers
  , Interface -> Maybe ShortText
iImportWarning   :: Maybe ShortText
    -- ^ Whether this module should raise a warning when imported
  , Interface -> BuiltinThings' (PrimitiveId, QName)
iBuiltin         :: BuiltinThings' (PrimitiveId, QName)
  , Interface -> BackendForeignCode
iForeignCode     :: Map BackendName ForeignCodeStack
  , Interface -> HighlightingInfo
iHighlighting    :: HighlightingInfo
  , Interface -> [OptionsPragma]
iDefaultPragmaOptions :: [OptionsPragma]
    -- ^ Pragma options set in library files.
  , Interface -> [OptionsPragma]
iFilePragmaOptions    :: [OptionsPragma]
    -- ^ Pragma options set in the file.
  , Interface -> PragmaOptions
iOptionsUsed     :: PragmaOptions
    -- ^ Options/features used when checking the file (can be different
    --   from options set directly in the file).
  , Interface -> PatternSynDefns
iPatternSyns     :: A.PatternSynDefns
  , Interface -> Set (TCWarning' EncodedDiagnostic)
iWarnings        :: Set (TCWarning' EncodedDiagnostic)
  , Interface -> Set QName
iPartialDefs     :: Set QName
  , Interface -> Map OpaqueId OpaqueBlock
iOpaqueBlocks    :: Map OpaqueId OpaqueBlock
  , Interface -> Map QName OpaqueId
iOpaqueNames     :: Map QName OpaqueId
  }
  deriving (Int -> Interface -> ShowS
[Interface] -> ShowS
Interface -> String
(Int -> Interface -> ShowS)
-> (Interface -> String)
-> ([Interface] -> ShowS)
-> Show Interface
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Interface -> ShowS
showsPrec :: Int -> Interface -> ShowS
$cshow :: Interface -> String
show :: Interface -> String
$cshowList :: [Interface] -> ShowS
showList :: [Interface] -> ShowS
Show, (forall x. Interface -> Rep Interface x)
-> (forall x. Rep Interface x -> Interface) -> Generic Interface
forall x. Rep Interface x -> Interface
forall x. Interface -> Rep Interface x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Interface -> Rep Interface x
from :: forall x. Interface -> Rep Interface x
$cto :: forall x. Rep Interface x -> Interface
to :: forall x. Rep Interface x -> Interface
Generic)

instance Pretty Interface where
  pretty :: Interface -> Doc
pretty (Interface
            Word64
sourceH Text
source FileType
fileT [(TopLevelModuleName, Word64)]
importedM ModuleName
moduleN TopLevelModuleName
topModN Map ModuleName Scope
scope ScopeInfo
insideS
            Signature
signature RemoteMetaStore
metas DisplayForms
display UserWarnings
userwarn Maybe ShortText
importwarn BuiltinThings' (PrimitiveId, QName)
builtin
            BackendForeignCode
foreignCode HighlightingInfo
highlighting [OptionsPragma]
libPragmaO [OptionsPragma]
filePragmaO PragmaOptions
oUsed
            PatternSynDefns
patternS Set (TCWarning' EncodedDiagnostic)
warnings Set QName
partialdefs Map OpaqueId OpaqueBlock
oblocks Map QName OpaqueId
onames) =

    Doc -> Int -> Doc -> Doc
forall a. Doc a -> Int -> Doc a -> Doc a
hang Doc
"Interface" Int
2 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"source hash:"         Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc) -> (Word64 -> String) -> Word64 -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word64 -> String
forall a. Show a => a -> String
show) Word64
sourceH
      , Doc
"source:"              Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
$$  Int -> Doc -> Doc
forall a. Int -> Doc a -> Doc a
nest Int
2 (String -> Doc
forall a. String -> Doc a
text (String -> Doc) -> String -> Doc
forall a b. (a -> b) -> a -> b
$ Text -> String
T.unpack Text
source)
      , Doc
"file type:"           Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc) -> (FileType -> String) -> FileType -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileType -> String
forall a. Show a => a -> String
show) FileType
fileT
      , Doc
"imported modules:"    Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> ([(TopLevelModuleName, Word64)] -> String)
-> [(TopLevelModuleName, Word64)]
-> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(TopLevelModuleName, Word64)] -> String
forall a. Show a => a -> String
show) [(TopLevelModuleName, Word64)]
importedM
      , Doc
"module name:"         Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> ModuleName -> Doc
forall a. Pretty a => a -> Doc
pretty ModuleName
moduleN
      , Doc
"top-level module name:" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> TopLevelModuleName -> Doc
forall a. Pretty a => a -> Doc
pretty TopLevelModuleName
topModN
      , Doc
"scope:"               Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (Map ModuleName Scope -> String) -> Map ModuleName Scope -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map ModuleName Scope -> String
forall a. Show a => a -> String
show) Map ModuleName Scope
scope
      , Doc
"inside scope:"        Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc) -> (ScopeInfo -> String) -> ScopeInfo -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ScopeInfo -> String
forall a. Show a => a -> String
show) ScopeInfo
insideS
      , Doc
"signature:"           Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc) -> (Signature -> String) -> Signature -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Signature -> String
forall a. Show a => a -> String
show) Signature
signature
      , Doc
"meta-variables:"      Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (RemoteMetaStore -> String) -> RemoteMetaStore -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RemoteMetaStore -> String
forall a. Show a => a -> String
show) RemoteMetaStore
metas
      , Doc
"display:"             Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc) -> (DisplayForms -> String) -> DisplayForms -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DisplayForms -> String
forall a. Show a => a -> String
show) DisplayForms
display
      , Doc
"user warnings:"       Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc) -> (UserWarnings -> String) -> UserWarnings -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UserWarnings -> String
forall a. Show a => a -> String
show) UserWarnings
userwarn
      , Doc
"import warning:"      Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (Maybe ShortText -> String) -> Maybe ShortText -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe ShortText -> String
forall a. Show a => a -> String
show) Maybe ShortText
importwarn
      , Doc
"builtin:"             Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (BuiltinThings' (PrimitiveId, QName) -> String)
-> BuiltinThings' (PrimitiveId, QName)
-> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BuiltinThings' (PrimitiveId, QName) -> String
forall a. Show a => a -> String
show) BuiltinThings' (PrimitiveId, QName)
builtin
      , Doc
"Foreign code:"        Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (BackendForeignCode -> String) -> BackendForeignCode -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BackendForeignCode -> String
forall a. Show a => a -> String
show) BackendForeignCode
foreignCode
      , Doc
"highlighting:"        Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (HighlightingInfo -> String) -> HighlightingInfo -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HighlightingInfo -> String
forall a. Show a => a -> String
show) HighlightingInfo
highlighting
      , Doc
"library pragma options:" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> ([OptionsPragma] -> String) -> [OptionsPragma] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [OptionsPragma] -> String
forall a. Show a => a -> String
show) [OptionsPragma]
libPragmaO
      , Doc
"file pragma options:" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> ([OptionsPragma] -> String) -> [OptionsPragma] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [OptionsPragma] -> String
forall a. Show a => a -> String
show) [OptionsPragma]
filePragmaO
      , Doc
"options used:"        Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (PragmaOptions -> String) -> PragmaOptions -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PragmaOptions -> String
forall a. Show a => a -> String
show) PragmaOptions
oUsed
      , Doc
"pattern syns:"        Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (PatternSynDefns -> String) -> PatternSynDefns -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PatternSynDefns -> String
forall a. Show a => a -> String
show) PatternSynDefns
patternS
      , Doc
"warnings:"            Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc)
-> (Set (TCWarning' EncodedDiagnostic) -> String)
-> Set (TCWarning' EncodedDiagnostic)
-> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Set (TCWarning' EncodedDiagnostic) -> String
forall a. Show a => a -> String
show) Set (TCWarning' EncodedDiagnostic)
warnings
      , Doc
"partial definitions:" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> (String -> Doc
forall a. Pretty a => a -> Doc
pretty (String -> Doc) -> (Set QName -> String) -> Set QName -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Set QName -> String
forall a. Show a => a -> String
show) Set QName
partialdefs
      , Doc
"opaque blocks:"       Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Map OpaqueId OpaqueBlock -> Doc
forall a. Pretty a => a -> Doc
pretty Map OpaqueId OpaqueBlock
oblocks
      , Doc
"opaque names"         Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Map QName OpaqueId -> Doc
forall a. Pretty a => a -> Doc
pretty Map QName OpaqueId
onames
      ]

-- | Combines the source hash and the (full) hashes of the imported modules.
iFullHash :: Interface -> Hash
iFullHash :: Interface -> Word64
iFullHash Interface
i = [Word64] -> Word64
combineHashes ([Word64] -> Word64) -> [Word64] -> Word64
forall a b. (a -> b) -> a -> b
$ Interface -> Word64
iSourceHash Interface
i Word64 -> [Word64] -> [Word64]
forall a. a -> [a] -> [a]
: ((TopLevelModuleName, Word64) -> Word64)
-> [(TopLevelModuleName, Word64)] -> [Word64]
forall a b. (a -> b) -> [a] -> [b]
List.map (TopLevelModuleName, Word64) -> Word64
forall a b. (a, b) -> b
snd (Interface -> [(TopLevelModuleName, Word64)]
iImportedModules Interface
i)

-- | A lens for the 'iSignature' field of the 'Interface' type.

intSignature :: Lens' Interface Signature
intSignature :: Lens' Interface Signature
intSignature Signature -> f Signature
f Interface
i = Signature -> f Signature
f (Interface -> Signature
iSignature Interface
i) f Signature -> (Signature -> Interface) -> f Interface
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \Signature
s -> Interface
i { iSignature = s }

----------------------------------------------------------------------------------------------------
-- ** Closure
----------------------------------------------------------------------------------------------------

data Closure a = Closure
  { forall a. Closure a -> Signature
clSignature         :: Signature
  , forall a. Closure a -> TCEnv
clEnv               :: TCEnv
  , forall a. Closure a -> ScopeInfo
clScope             :: ScopeInfo
  , forall a. Closure a -> ModuleCheckpoints
clModuleCheckpoints :: ModuleCheckpoints
  , forall a. Closure a -> a
clValue             :: a
  }
    deriving ((forall a b. (a -> b) -> Closure a -> Closure b)
-> (forall a b. a -> Closure b -> Closure a) -> Functor Closure
forall a b. a -> Closure b -> Closure a
forall a b. (a -> b) -> Closure a -> Closure b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall a b. (a -> b) -> Closure a -> Closure b
fmap :: forall a b. (a -> b) -> Closure a -> Closure b
$c<$ :: forall a b. a -> Closure b -> Closure a
<$ :: forall a b. a -> Closure b -> Closure a
Functor, (forall m. Monoid m => Closure m -> m)
-> (forall m a. Monoid m => (a -> m) -> Closure a -> m)
-> (forall m a. Monoid m => (a -> m) -> Closure a -> m)
-> (forall a b. (a -> b -> b) -> b -> Closure a -> b)
-> (forall a b. (a -> b -> b) -> b -> Closure a -> b)
-> (forall b a. (b -> a -> b) -> b -> Closure a -> b)
-> (forall b a. (b -> a -> b) -> b -> Closure a -> b)
-> (forall a. (a -> a -> a) -> Closure a -> a)
-> (forall a. (a -> a -> a) -> Closure a -> a)
-> (forall a. Closure a -> [a])
-> (forall a. Closure a -> Bool)
-> (forall a. Closure a -> Int)
-> (forall a. Eq a => a -> Closure a -> Bool)
-> (forall a. Ord a => Closure a -> a)
-> (forall a. Ord a => Closure a -> a)
-> (forall a. Num a => Closure a -> a)
-> (forall a. Num a => Closure a -> a)
-> Foldable Closure
forall a. Eq a => a -> Closure a -> Bool
forall a. Num a => Closure a -> a
forall a. Ord a => Closure a -> a
forall m. Monoid m => Closure m -> m
forall a. Closure a -> Bool
forall a. Closure a -> Int
forall a. Closure a -> [a]
forall a. (a -> a -> a) -> Closure a -> a
forall m a. Monoid m => (a -> m) -> Closure a -> m
forall b a. (b -> a -> b) -> b -> Closure a -> b
forall a b. (a -> b -> b) -> b -> Closure a -> b
forall (t :: * -> *).
(forall m. Monoid m => t m -> m)
-> (forall m a. Monoid m => (a -> m) -> t a -> m)
-> (forall m a. Monoid m => (a -> m) -> t a -> m)
-> (forall a b. (a -> b -> b) -> b -> t a -> b)
-> (forall a b. (a -> b -> b) -> b -> t a -> b)
-> (forall b a. (b -> a -> b) -> b -> t a -> b)
-> (forall b a. (b -> a -> b) -> b -> t a -> b)
-> (forall a. (a -> a -> a) -> t a -> a)
-> (forall a. (a -> a -> a) -> t a -> a)
-> (forall a. t a -> [a])
-> (forall a. t a -> Bool)
-> (forall a. t a -> Int)
-> (forall a. Eq a => a -> t a -> Bool)
-> (forall a. Ord a => t a -> a)
-> (forall a. Ord a => t a -> a)
-> (forall a. Num a => t a -> a)
-> (forall a. Num a => t a -> a)
-> Foldable t
$cfold :: forall m. Monoid m => Closure m -> m
fold :: forall m. Monoid m => Closure m -> m
$cfoldMap :: forall m a. Monoid m => (a -> m) -> Closure a -> m
foldMap :: forall m a. Monoid m => (a -> m) -> Closure a -> m
$cfoldMap' :: forall m a. Monoid m => (a -> m) -> Closure a -> m
foldMap' :: forall m a. Monoid m => (a -> m) -> Closure a -> m
$cfoldr :: forall a b. (a -> b -> b) -> b -> Closure a -> b
foldr :: forall a b. (a -> b -> b) -> b -> Closure a -> b
$cfoldr' :: forall a b. (a -> b -> b) -> b -> Closure a -> b
foldr' :: forall a b. (a -> b -> b) -> b -> Closure a -> b
$cfoldl :: forall b a. (b -> a -> b) -> b -> Closure a -> b
foldl :: forall b a. (b -> a -> b) -> b -> Closure a -> b
$cfoldl' :: forall b a. (b -> a -> b) -> b -> Closure a -> b
foldl' :: forall b a. (b -> a -> b) -> b -> Closure a -> b
$cfoldr1 :: forall a. (a -> a -> a) -> Closure a -> a
foldr1 :: forall a. (a -> a -> a) -> Closure a -> a
$cfoldl1 :: forall a. (a -> a -> a) -> Closure a -> a
foldl1 :: forall a. (a -> a -> a) -> Closure a -> a
$ctoList :: forall a. Closure a -> [a]
toList :: forall a. Closure a -> [a]
$cnull :: forall a. Closure a -> Bool
null :: forall a. Closure a -> Bool
$clength :: forall a. Closure a -> Int
length :: forall a. Closure a -> Int
$celem :: forall a. Eq a => a -> Closure a -> Bool
elem :: forall a. Eq a => a -> Closure a -> Bool
$cmaximum :: forall a. Ord a => Closure a -> a
maximum :: forall a. Ord a => Closure a -> a
$cminimum :: forall a. Ord a => Closure a -> a
minimum :: forall a. Ord a => Closure a -> a
$csum :: forall a. Num a => Closure a -> a
sum :: forall a. Num a => Closure a -> a
$cproduct :: forall a. Num a => Closure a -> a
product :: forall a. Num a => Closure a -> a
Foldable, (forall x. Closure a -> Rep (Closure a) x)
-> (forall x. Rep (Closure a) x -> Closure a)
-> Generic (Closure a)
forall x. Rep (Closure a) x -> Closure a
forall x. Closure a -> Rep (Closure a) x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
forall a x. Rep (Closure a) x -> Closure a
forall a x. Closure a -> Rep (Closure a) x
$cfrom :: forall a x. Closure a -> Rep (Closure a) x
from :: forall x. Closure a -> Rep (Closure a) x
$cto :: forall a x. Rep (Closure a) x -> Closure a
to :: forall x. Rep (Closure a) x -> Closure a
Generic)

instance Show a => Show (Closure a) where
  show :: Closure a -> String
show Closure a
cl = String
"Closure { clValue = " String -> ShowS
forall a. [a] -> [a] -> [a]
++ a -> String
forall a. Show a => a -> String
show (Closure a -> a
forall a. Closure a -> a
clValue Closure a
cl) String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
" }"

instance HasRange a => HasRange (Closure a) where
  getRange :: Closure a -> Range
getRange = a -> Range
forall a. HasRange a => a -> Range
getRange (a -> Range) -> (Closure a -> a) -> Closure a -> Range
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Closure a -> a
forall a. Closure a -> a
clValue

class LensClosure b a | b -> a where
  lensClosure :: Lens' b (Closure a)

instance LensClosure (Closure a) a where
  lensClosure :: Lens' (Closure a) (Closure a)
lensClosure = (Closure a -> f (Closure a)) -> Closure a -> f (Closure a)
forall a. a -> a
id

instance LensTCEnv (Closure a) where
  lensTCEnv :: Lens' (Closure a) TCEnv
lensTCEnv TCEnv -> f TCEnv
f Closure a
cl = (TCEnv -> f TCEnv
f (TCEnv -> f TCEnv) -> TCEnv -> f TCEnv
forall a b. (a -> b) -> a -> b
$! Closure a -> TCEnv
forall a. Closure a -> TCEnv
clEnv Closure a
cl) f TCEnv -> (TCEnv -> Closure a) -> f (Closure a)
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ TCEnv
env -> Closure a
cl { clEnv = env }

{-# SPECIALIZE buildClosure :: a -> TCM (Closure a)  #-}
buildClosure :: (MonadTCEnv m, ReadTCState m) => a -> m (Closure a)
buildClosure :: forall (m :: * -> *) a.
(MonadTCEnv m, ReadTCState m) =>
a -> m (Closure a)
buildClosure a
x = do
    env   <- m TCEnv
forall (m :: * -> *). MonadTCEnv m => m TCEnv
askTC
    sig   <- useR stSignature
    scope <- useR stScope
    cps   <- useR stModuleCheckpoints
    return $ Closure sig env scope cps x

----------------------------------------------------------------------------------------------------
-- ** Constraints
----------------------------------------------------------------------------------------------------

type Constraints = [ProblemConstraint]

data ProblemConstraint = PConstr
  { ProblemConstraint -> Set ProblemId
constraintProblems  :: Set ProblemId
  , ProblemConstraint -> Blocker
constraintUnblocker :: Blocker
  , ProblemConstraint -> Closure Constraint
theConstraint       :: Closure Constraint
  }
  deriving (Int -> ProblemConstraint -> ShowS
Constraints -> ShowS
ProblemConstraint -> String
(Int -> ProblemConstraint -> ShowS)
-> (ProblemConstraint -> String)
-> (Constraints -> ShowS)
-> Show ProblemConstraint
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ProblemConstraint -> ShowS
showsPrec :: Int -> ProblemConstraint -> ShowS
$cshow :: ProblemConstraint -> String
show :: ProblemConstraint -> String
$cshowList :: Constraints -> ShowS
showList :: Constraints -> ShowS
Show, (forall x. ProblemConstraint -> Rep ProblemConstraint x)
-> (forall x. Rep ProblemConstraint x -> ProblemConstraint)
-> Generic ProblemConstraint
forall x. Rep ProblemConstraint x -> ProblemConstraint
forall x. ProblemConstraint -> Rep ProblemConstraint x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ProblemConstraint -> Rep ProblemConstraint x
from :: forall x. ProblemConstraint -> Rep ProblemConstraint x
$cto :: forall x. Rep ProblemConstraint x -> ProblemConstraint
to :: forall x. Rep ProblemConstraint x -> ProblemConstraint
Generic)

instance HasRange ProblemConstraint where
  getRange :: ProblemConstraint -> Range
getRange = Closure Constraint -> Range
forall a. HasRange a => a -> Range
getRange (Closure Constraint -> Range)
-> (ProblemConstraint -> Closure Constraint)
-> ProblemConstraint
-> Range
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ProblemConstraint -> Closure Constraint
theConstraint

data Constraint
  = ValueCmp Comparison CompareAs Term Term
  | ValueCmpOnFace Comparison Term Type Term Term
  | ElimCmp [Polarity] [IsForced] Type Term [Elim] [Elim]
  | SortCmp Comparison Sort Sort
  | LevelCmp Comparison Level Level
--  | ShortCut MetaId Term Type
--    -- ^ A delayed instantiation.  Replaces @ValueCmp@ in 'postponeTypeCheckingProblem'.
  | HasPTSRule (Dom Type) (Abs Sort)
  | CheckDataSort QName Sort
    -- ^ Check that the sort 'Sort' of data type 'QName' admits data/record types.
    -- E.g., sorts @IUniv@, etc. do not admit such constructions.
    -- See 'Agda.TypeChecking.Rules.Data.checkDataSort'.
  | CheckMetaInst MetaId
  | CheckType Type
  | UnBlock MetaId
    -- ^ Meta created for a term blocked by a postponed type checking problem or unsolved
    --   constraints. The 'MetaInstantiation' for the meta (when unsolved) is either 'BlockedConst'
    --   or 'PostponedTypeCheckingProblem'.
  | IsEmpty Range Type
    -- ^ The range is the one of the absurd pattern.
  | FindInstance Range MetaId (Maybe [Candidate])
    -- ^ the second argument is the instance argument and the third one is dhe list of candidates
    --   (or Nothing if we haven’t determined the list of candidates yet)
  | ResolveInstanceHead KwRange QName
    -- ^ Resolve the head symbol of the type that the given instance targets
    --   The 'KwRange' is the range of the @instance@ keyword.
  | CheckFunDef A.DefInfo QName [A.Clause] TCErr
    -- ^ Last argument is the error causing us to postpone.
  | UnquoteTactic Term Term Type
    -- ^ First argument is computation and the others are hole and goal type.
  deriving (Int -> Constraint -> ShowS
[Constraint] -> ShowS
Constraint -> String
(Int -> Constraint -> ShowS)
-> (Constraint -> String)
-> ([Constraint] -> ShowS)
-> Show Constraint
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Constraint -> ShowS
showsPrec :: Int -> Constraint -> ShowS
$cshow :: Constraint -> String
show :: Constraint -> String
$cshowList :: [Constraint] -> ShowS
showList :: [Constraint] -> ShowS
Show, (forall x. Constraint -> Rep Constraint x)
-> (forall x. Rep Constraint x -> Constraint) -> Generic Constraint
forall x. Rep Constraint x -> Constraint
forall x. Constraint -> Rep Constraint x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Constraint -> Rep Constraint x
from :: forall x. Constraint -> Rep Constraint x
$cto :: forall x. Rep Constraint x -> Constraint
to :: forall x. Rep Constraint x -> Constraint
Generic)

-- It's important to have a proper range for constraints that can remain unsolved
-- without a corresponding unsolved meta to point to the location of the constraint.
instance HasRange Constraint where
  getRange :: Constraint -> Range
getRange (IsEmpty Range
r Type
t)         = Range
r
  getRange (FindInstance Range
r MetaId
_ Maybe [Candidate]
_)  = Range
r
  getRange ValueCmp{}            = Range
forall a. Range' a
noRange
  getRange ElimCmp{}             = Range
forall a. Range' a
noRange
  getRange SortCmp{}             = Range
forall a. Range' a
noRange
  getRange LevelCmp{}            = Range
forall a. Range' a
noRange
  getRange UnBlock{}             = Range
forall a. Range' a
noRange
  getRange ValueCmpOnFace{}      = Range
forall a. Range' a
noRange
  getRange HasPTSRule{}          = Range
forall a. Range' a
noRange
  getRange CheckDataSort{}       = Range
forall a. Range' a
noRange
  getRange CheckMetaInst{}       = Range
forall a. Range' a
noRange
  getRange CheckType{}           = Range
forall a. Range' a
noRange
  getRange CheckFunDef{}         = Range
forall a. Range' a
noRange
  getRange ResolveInstanceHead{} = Range
forall a. Range' a
noRange
  getRange UnquoteTactic{}       = Range
forall a. Range' a
noRange

instance Free Constraint where
  freeVars :: forall r. ComputeFree r => Constraint -> Reader r (Collect r)
freeVars Constraint
c = ((Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
 -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r)
forall a.
ExpandCase LiftedRep a =>
((a -> Result LiftedRep a) -> Result LiftedRep a) -> a
expand \Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret -> case Constraint
c of
    ValueCmp Comparison
_ CompareAs
t Term
u Term
v            -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ (CompareAs, Term, Term) -> Reader r (Collect r)
forall r.
ComputeFree r =>
(CompareAs, Term, Term) -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars (CompareAs
t, Term
u, Term
v)
    ValueCmpOnFace Comparison
_ Term
p Type
t Term
u Term
v    -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ (Term, Type, Term, Term) -> Reader r (Collect r)
forall r.
ComputeFree r =>
(Term, Type, Term, Term) -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars (Term
p, Type
t, Term
u, Term
v)
    ElimCmp [Polarity]
_ [IsForced]
_ Type
t Term
u [Elim]
es [Elim]
es'      -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ (Type, Term, [Elim], [Elim]) -> Reader r (Collect r)
forall r.
ComputeFree r =>
(Type, Term, [Elim], [Elim]) -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars (Type
t, Term
u, [Elim]
es, [Elim]
es')
    SortCmp Comparison
_ Sort
s Sort
s'              -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ (Sort, Sort) -> Reader r (Collect r)
forall r. ComputeFree r => (Sort, Sort) -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars (Sort
s, Sort
s')
    LevelCmp Comparison
_ Level
l Level
l'             -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ (Level, Level) -> Reader r (Collect r)
forall r. ComputeFree r => (Level, Level) -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars (Level
l, Level
l')
    UnBlock MetaId
_                   -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Reader r (Collect r)
forall a. Monoid a => a
mempty
    IsEmpty Range
_ Type
t                 -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Type -> Reader r (Collect r)
forall r. ComputeFree r => Type -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars Type
t
    FindInstance Range
_ MetaId
_ Maybe [Candidate]
cs         -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Maybe [Candidate] -> Reader r (Collect r)
forall r.
ComputeFree r =>
Maybe [Candidate] -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars Maybe [Candidate]
cs
    ResolveInstanceHead KwRange
_ QName
_     -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Reader r (Collect r)
forall a. Monoid a => a
mempty
    CheckFunDef{}               -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Reader r (Collect r)
forall a. Monoid a => a
mempty
    HasPTSRule Dom Type
a Abs Sort
s              -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ (Dom Type, Abs Sort) -> Reader r (Collect r)
forall r.
ComputeFree r =>
(Dom Type, Abs Sort) -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars (Dom Type
a , Abs Sort
s)
    UnquoteTactic Term
t Term
h Type
g         -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ (Term, Term, Type) -> Reader r (Collect r)
forall r.
ComputeFree r =>
(Term, Term, Type) -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars (Term
t, Term
h, Type
g)
    CheckDataSort QName
_ Sort
s           -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Sort -> Reader r (Collect r)
forall r. ComputeFree r => Sort -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars Sort
s
    CheckMetaInst MetaId
m             -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Reader r (Collect r)
forall a. Monoid a => a
mempty
    CheckType Type
t                 -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Type -> Reader r (Collect r)
forall r. ComputeFree r => Type -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars Type
t

{-# SPECIALIZE closed :: Constraint -> Bool #-}
{-# SPECIALIZE freeVarSet :: Constraint -> VarSet #-}

instance TermLike Constraint where
  foldTerm :: forall m. Monoid m => (Term -> m) -> Constraint -> m
foldTerm Term -> m
f = \case
      ValueCmp Comparison
_ CompareAs
t Term
u Term
v       -> (Term -> m) -> (CompareAs, Term, Term) -> m
forall m. Monoid m => (Term -> m) -> (CompareAs, Term, Term) -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f (CompareAs
t, Term
u, Term
v)
      ValueCmpOnFace Comparison
_ Term
p Type
t Term
u Term
v -> (Term -> m) -> (Term, Type, Term, Term) -> m
forall m. Monoid m => (Term -> m) -> (Term, Type, Term, Term) -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f (Term
p, Type
t, Term
u, Term
v)
      ElimCmp [Polarity]
_ [IsForced]
_ Type
t Term
u [Elim]
es [Elim]
es' -> (Term -> m) -> (Type, Term, [Elim], [Elim]) -> m
forall m.
Monoid m =>
(Term -> m) -> (Type, Term, [Elim], [Elim]) -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f (Type
t, Term
u, [Elim]
es, [Elim]
es')
      LevelCmp Comparison
_ Level
l Level
l'        -> (Term -> m) -> (Term, Term) -> m
forall m. Monoid m => (Term -> m) -> (Term, Term) -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f (Level -> Term
Level Level
l, Level -> Term
Level Level
l')  -- Note wrapping as term, to ensure f gets to act on l and l'
      IsEmpty Range
_ Type
t            -> (Term -> m) -> Type -> m
forall m. Monoid m => (Term -> m) -> Type -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f Type
t
      UnquoteTactic Term
t Term
h Type
g    -> (Term -> m) -> (Term, Term, Type) -> m
forall m. Monoid m => (Term -> m) -> (Term, Term, Type) -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f (Term
t, Term
h, Type
g)
      SortCmp Comparison
_ Sort
s1 Sort
s2        -> (Term -> m) -> (Term, Term) -> m
forall m. Monoid m => (Term -> m) -> (Term, Term) -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f (Sort -> Term
Sort Sort
s1, Sort -> Term
Sort Sort
s2)   -- Same as LevelCmp case
      UnBlock MetaId
_              -> m
forall a. Monoid a => a
mempty
      FindInstance Range
_ MetaId
_ Maybe [Candidate]
_     -> m
forall a. Monoid a => a
mempty
      ResolveInstanceHead KwRange
_ QName
_  -> m
forall a. Monoid a => a
mempty
      CheckFunDef{}          -> m
forall a. Monoid a => a
mempty
      HasPTSRule Dom Type
a Abs Sort
s         -> (Term -> m) -> (Dom Type, Abs Term) -> m
forall m. Monoid m => (Term -> m) -> (Dom Type, Abs Term) -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f (Dom Type
a, Sort -> Term
Sort (Sort -> Term) -> Abs Sort -> Abs Term
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Abs Sort
s)
      CheckDataSort QName
_ Sort
s      -> (Term -> m) -> Sort -> m
forall m. Monoid m => (Term -> m) -> Sort -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f Sort
s
      CheckMetaInst MetaId
m        -> m
forall a. Monoid a => a
mempty
      CheckType Type
t            -> (Term -> m) -> Type -> m
forall m. Monoid m => (Term -> m) -> Type -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f Type
t

  traverseTermM :: forall (m :: * -> *).
Monad m =>
(Term -> m Term) -> Constraint -> m Constraint
traverseTermM Term -> m Term
f Constraint
c = m Constraint
forall a. HasCallStack => a
__IMPOSSIBLE__ -- Not yet implemented

instance AllMetas Constraint

instance Pretty Comparison where
  pretty :: Comparison -> Doc
pretty Comparison
CmpEq  = Doc
"="
  pretty Comparison
CmpLeq = Doc
"=<"

-- | An extension of 'Comparison' to @>=@.
data CompareDirection = DirEq | DirLeq | DirGeq
  deriving (CompareDirection -> CompareDirection -> Bool
(CompareDirection -> CompareDirection -> Bool)
-> (CompareDirection -> CompareDirection -> Bool)
-> Eq CompareDirection
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CompareDirection -> CompareDirection -> Bool
== :: CompareDirection -> CompareDirection -> Bool
$c/= :: CompareDirection -> CompareDirection -> Bool
/= :: CompareDirection -> CompareDirection -> Bool
Eq, Int -> CompareDirection -> ShowS
[CompareDirection] -> ShowS
CompareDirection -> String
(Int -> CompareDirection -> ShowS)
-> (CompareDirection -> String)
-> ([CompareDirection] -> ShowS)
-> Show CompareDirection
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CompareDirection -> ShowS
showsPrec :: Int -> CompareDirection -> ShowS
$cshow :: CompareDirection -> String
show :: CompareDirection -> String
$cshowList :: [CompareDirection] -> ShowS
showList :: [CompareDirection] -> ShowS
Show)

instance Pretty CompareDirection where
  pretty :: CompareDirection -> Doc
pretty = String -> Doc
forall a. String -> Doc a
text (String -> Doc)
-> (CompareDirection -> String) -> CompareDirection -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. \case
    CompareDirection
DirEq  -> String
"="
    CompareDirection
DirLeq -> String
"=<"
    CompareDirection
DirGeq -> String
">="

-- | Embed 'Comparison' into 'CompareDirection'.
fromCmp :: Comparison -> CompareDirection
fromCmp :: Comparison -> CompareDirection
fromCmp Comparison
CmpEq  = CompareDirection
DirEq
fromCmp Comparison
CmpLeq = CompareDirection
DirLeq

-- | Flip the direction of comparison.
flipCmp :: CompareDirection -> CompareDirection
flipCmp :: CompareDirection -> CompareDirection
flipCmp CompareDirection
DirEq  = CompareDirection
DirEq
flipCmp CompareDirection
DirLeq = CompareDirection
DirGeq
flipCmp CompareDirection
DirGeq = CompareDirection
DirLeq

-- | Turn a 'Comparison' function into a 'CompareDirection' function.
--
--   Property: @dirToCmp f (fromCmp cmp) = f cmp@
dirToCmp :: (Comparison -> a -> a -> c) -> CompareDirection -> a -> a -> c
dirToCmp :: forall a c.
(Comparison -> a -> a -> c) -> CompareDirection -> a -> a -> c
dirToCmp Comparison -> a -> a -> c
cont CompareDirection
DirEq  = Comparison -> a -> a -> c
cont Comparison
CmpEq
dirToCmp Comparison -> a -> a -> c
cont CompareDirection
DirLeq = Comparison -> a -> a -> c
cont Comparison
CmpLeq
dirToCmp Comparison -> a -> a -> c
cont CompareDirection
DirGeq = (a -> a -> c) -> a -> a -> c
forall a b c. (a -> b -> c) -> b -> a -> c
flip ((a -> a -> c) -> a -> a -> c) -> (a -> a -> c) -> a -> a -> c
forall a b. (a -> b) -> a -> b
$ Comparison -> a -> a -> c
cont Comparison
CmpLeq

-- | We can either compare two terms at a given type, or compare two
--   types without knowing (or caring about) their sorts.
data CompareAs
  = AsTermsOf Type
  | AsTypes
  deriving (Int -> CompareAs -> ShowS
[CompareAs] -> ShowS
CompareAs -> String
(Int -> CompareAs -> ShowS)
-> (CompareAs -> String)
-> ([CompareAs] -> ShowS)
-> Show CompareAs
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CompareAs -> ShowS
showsPrec :: Int -> CompareAs -> ShowS
$cshow :: CompareAs -> String
show :: CompareAs -> String
$cshowList :: [CompareAs] -> ShowS
showList :: [CompareAs] -> ShowS
Show, (forall x. CompareAs -> Rep CompareAs x)
-> (forall x. Rep CompareAs x -> CompareAs) -> Generic CompareAs
forall x. Rep CompareAs x -> CompareAs
forall x. CompareAs -> Rep CompareAs x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. CompareAs -> Rep CompareAs x
from :: forall x. CompareAs -> Rep CompareAs x
$cto :: forall x. Rep CompareAs x -> CompareAs
to :: forall x. Rep CompareAs x -> CompareAs
Generic)

instance Free CompareAs where
  freeVars :: forall r. ComputeFree r => CompareAs -> Reader r (Collect r)
freeVars CompareAs
ca = ((Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
 -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r)
forall a.
ExpandCase LiftedRep a =>
((a -> Result LiftedRep a) -> Result LiftedRep a) -> a
expand \Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret -> case CompareAs
ca of
    (AsTermsOf Type
a) -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Type -> Reader r (Collect r)
forall r. ComputeFree r => Type -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars Type
a
    CompareAs
AsTypes       -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ Reader r (Collect r)
forall a. Monoid a => a
mempty

instance TermLike CompareAs where
  foldTerm :: forall m. Monoid m => (Term -> m) -> CompareAs -> m
foldTerm Term -> m
f (AsTermsOf Type
a) = (Term -> m) -> Type -> m
forall m. Monoid m => (Term -> m) -> Type -> m
forall a m. (TermLike a, Monoid m) => (Term -> m) -> a -> m
foldTerm Term -> m
f Type
a
  foldTerm Term -> m
f CompareAs
AsTypes       = m
forall a. Monoid a => a
mempty

  traverseTermM :: forall (m :: * -> *).
Monad m =>
(Term -> m Term) -> CompareAs -> m CompareAs
traverseTermM Term -> m Term
f = \case
    AsTermsOf Type
a -> Type -> CompareAs
AsTermsOf (Type -> CompareAs) -> m Type -> m CompareAs
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Term -> m Term) -> Type -> m Type
forall a (m :: * -> *).
(TermLike a, Monad m) =>
(Term -> m Term) -> a -> m a
forall (m :: * -> *). Monad m => (Term -> m Term) -> Type -> m Type
traverseTermM Term -> m Term
f Type
a
    CompareAs
AsTypes     -> CompareAs -> m CompareAs
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return CompareAs
AsTypes

instance AllMetas CompareAs

instance Pretty CompareAs where
  pretty :: CompareAs -> Doc
pretty (AsTermsOf Type
a) = Doc
":" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Type -> Doc
forall a. Pretty a => a -> Doc
pretty Type
a
  pretty CompareAs
AsTypes       = Doc
forall a. Null a => a
empty

----------------------------------------------------------------------------------------------------
-- * Open things
----------------------------------------------------------------------------------------------------

-- | A thing tagged with the context it came from. Also keeps the substitution from previous
--   checkpoints. This lets us handle the case when an open thing was created in a context that we
--   have since exited. Remember which module it's from to make sure we don't get confused by
--   checkpoints from other files.
data Open a = OpenThing { forall a. Open a -> CheckpointId
openThingCheckpoint    :: CheckpointId
                        , forall a. Open a -> Map CheckpointId Substitution
openThingCheckpointMap :: Map CheckpointId Substitution
                        , forall a. Open a -> ModuleNameHash
openThingModule        :: ModuleNameHash
                        , forall a. Open a -> a
openThing              :: a }
    deriving (Int -> Open a -> ShowS
[Open a] -> ShowS
Open a -> String
(Int -> Open a -> ShowS)
-> (Open a -> String) -> ([Open a] -> ShowS) -> Show (Open a)
forall a. Show a => Int -> Open a -> ShowS
forall a. Show a => [Open a] -> ShowS
forall a. Show a => Open a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall a. Show a => Int -> Open a -> ShowS
showsPrec :: Int -> Open a -> ShowS
$cshow :: forall a. Show a => Open a -> String
show :: Open a -> String
$cshowList :: forall a. Show a => [Open a] -> ShowS
showList :: [Open a] -> ShowS
Show, (forall a b. (a -> b) -> Open a -> Open b)
-> (forall a b. a -> Open b -> Open a) -> Functor Open
forall a b. a -> Open b -> Open a
forall a b. (a -> b) -> Open a -> Open b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall a b. (a -> b) -> Open a -> Open b
fmap :: forall a b. (a -> b) -> Open a -> Open b
$c<$ :: forall a b. a -> Open b -> Open a
<$ :: forall a b. a -> Open b -> Open a
Functor, (forall m. Monoid m => Open m -> m)
-> (forall m a. Monoid m => (a -> m) -> Open a -> m)
-> (forall m a. Monoid m => (a -> m) -> Open a -> m)
-> (forall a b. (a -> b -> b) -> b -> Open a -> b)
-> (forall a b. (a -> b -> b) -> b -> Open a -> b)
-> (forall b a. (b -> a -> b) -> b -> Open a -> b)
-> (forall b a. (b -> a -> b) -> b -> Open a -> b)
-> (forall a. (a -> a -> a) -> Open a -> a)
-> (forall a. (a -> a -> a) -> Open a -> a)
-> (forall a. Open a -> [a])
-> (forall a. Open a -> Bool)
-> (forall a. Open a -> Int)
-> (forall a. Eq a => a -> Open a -> Bool)
-> (forall a. Ord a => Open a -> a)
-> (forall a. Ord a => Open a -> a)
-> (forall a. Num a => Open a -> a)
-> (forall a. Num a => Open a -> a)
-> Foldable Open
forall a. Eq a => a -> Open a -> Bool
forall a. Num a => Open a -> a
forall a. Ord a => Open a -> a
forall m. Monoid m => Open m -> m
forall a. Open a -> Bool
forall a. Open a -> Int
forall a. Open a -> [a]
forall a. (a -> a -> a) -> Open a -> a
forall m a. Monoid m => (a -> m) -> Open a -> m
forall b a. (b -> a -> b) -> b -> Open a -> b
forall a b. (a -> b -> b) -> b -> Open a -> b
forall (t :: * -> *).
(forall m. Monoid m => t m -> m)
-> (forall m a. Monoid m => (a -> m) -> t a -> m)
-> (forall m a. Monoid m => (a -> m) -> t a -> m)
-> (forall a b. (a -> b -> b) -> b -> t a -> b)
-> (forall a b. (a -> b -> b) -> b -> t a -> b)
-> (forall b a. (b -> a -> b) -> b -> t a -> b)
-> (forall b a. (b -> a -> b) -> b -> t a -> b)
-> (forall a. (a -> a -> a) -> t a -> a)
-> (forall a. (a -> a -> a) -> t a -> a)
-> (forall a. t a -> [a])
-> (forall a. t a -> Bool)
-> (forall a. t a -> Int)
-> (forall a. Eq a => a -> t a -> Bool)
-> (forall a. Ord a => t a -> a)
-> (forall a. Ord a => t a -> a)
-> (forall a. Num a => t a -> a)
-> (forall a. Num a => t a -> a)
-> Foldable t
$cfold :: forall m. Monoid m => Open m -> m
fold :: forall m. Monoid m => Open m -> m
$cfoldMap :: forall m a. Monoid m => (a -> m) -> Open a -> m
foldMap :: forall m a. Monoid m => (a -> m) -> Open a -> m
$cfoldMap' :: forall m a. Monoid m => (a -> m) -> Open a -> m
foldMap' :: forall m a. Monoid m => (a -> m) -> Open a -> m
$cfoldr :: forall a b. (a -> b -> b) -> b -> Open a -> b
foldr :: forall a b. (a -> b -> b) -> b -> Open a -> b
$cfoldr' :: forall a b. (a -> b -> b) -> b -> Open a -> b
foldr' :: forall a b. (a -> b -> b) -> b -> Open a -> b
$cfoldl :: forall b a. (b -> a -> b) -> b -> Open a -> b
foldl :: forall b a. (b -> a -> b) -> b -> Open a -> b
$cfoldl' :: forall b a. (b -> a -> b) -> b -> Open a -> b
foldl' :: forall b a. (b -> a -> b) -> b -> Open a -> b
$cfoldr1 :: forall a. (a -> a -> a) -> Open a -> a
foldr1 :: forall a. (a -> a -> a) -> Open a -> a
$cfoldl1 :: forall a. (a -> a -> a) -> Open a -> a
foldl1 :: forall a. (a -> a -> a) -> Open a -> a
$ctoList :: forall a. Open a -> [a]
toList :: forall a. Open a -> [a]
$cnull :: forall a. Open a -> Bool
null :: forall a. Open a -> Bool
$clength :: forall a. Open a -> Int
length :: forall a. Open a -> Int
$celem :: forall a. Eq a => a -> Open a -> Bool
elem :: forall a. Eq a => a -> Open a -> Bool
$cmaximum :: forall a. Ord a => Open a -> a
maximum :: forall a. Ord a => Open a -> a
$cminimum :: forall a. Ord a => Open a -> a
minimum :: forall a. Ord a => Open a -> a
$csum :: forall a. Num a => Open a -> a
sum :: forall a. Num a => Open a -> a
$cproduct :: forall a. Num a => Open a -> a
product :: forall a. Num a => Open a -> a
Foldable, Functor Open
Foldable Open
(Functor Open, Foldable Open) =>
(forall (f :: * -> *) a b.
 Applicative f =>
 (a -> f b) -> Open a -> f (Open b))
-> (forall (f :: * -> *) a.
    Applicative f =>
    Open (f a) -> f (Open a))
-> (forall (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> Open a -> m (Open b))
-> (forall (m :: * -> *) a. Monad m => Open (m a) -> m (Open a))
-> Traversable Open
forall (t :: * -> *).
(Functor t, Foldable t) =>
(forall (f :: * -> *) a b.
 Applicative f =>
 (a -> f b) -> t a -> f (t b))
-> (forall (f :: * -> *) a. Applicative f => t (f a) -> f (t a))
-> (forall (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> t a -> m (t b))
-> (forall (m :: * -> *) a. Monad m => t (m a) -> m (t a))
-> Traversable t
forall (m :: * -> *) a. Monad m => Open (m a) -> m (Open a)
forall (f :: * -> *) a. Applicative f => Open (f a) -> f (Open a)
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Open a -> m (Open b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Open a -> f (Open b)
$ctraverse :: forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Open a -> f (Open b)
traverse :: forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Open a -> f (Open b)
$csequenceA :: forall (f :: * -> *) a. Applicative f => Open (f a) -> f (Open a)
sequenceA :: forall (f :: * -> *) a. Applicative f => Open (f a) -> f (Open a)
$cmapM :: forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Open a -> m (Open b)
mapM :: forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Open a -> m (Open b)
$csequence :: forall (m :: * -> *) a. Monad m => Open (m a) -> m (Open a)
sequence :: forall (m :: * -> *) a. Monad m => Open (m a) -> m (Open a)
Traversable, (forall x. Open a -> Rep (Open a) x)
-> (forall x. Rep (Open a) x -> Open a) -> Generic (Open a)
forall x. Rep (Open a) x -> Open a
forall x. Open a -> Rep (Open a) x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
forall a x. Rep (Open a) x -> Open a
forall a x. Open a -> Rep (Open a) x
$cfrom :: forall a x. Open a -> Rep (Open a) x
from :: forall x. Open a -> Rep (Open a) x
$cto :: forall a x. Rep (Open a) x -> Open a
to :: forall x. Rep (Open a) x -> Open a
Generic)

instance Decoration Open where
  traverseF :: forall (m :: * -> *) a b.
Functor m =>
(a -> m b) -> Open a -> m (Open b)
traverseF a -> m b
f (OpenThing CheckpointId
cp Map CheckpointId Substitution
env ModuleNameHash
m a
x) = CheckpointId
-> Map CheckpointId Substitution -> ModuleNameHash -> b -> Open b
forall a.
CheckpointId
-> Map CheckpointId Substitution -> ModuleNameHash -> a -> Open a
OpenThing CheckpointId
cp Map CheckpointId Substitution
env ModuleNameHash
m (b -> Open b) -> m b -> m (Open b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> a -> m b
f a
x

instance Pretty a => Pretty (Open a) where
  prettyPrec :: Int -> Open a -> Doc
prettyPrec Int
p (OpenThing CheckpointId
cp Map CheckpointId Substitution
env ModuleNameHash
_ a
x) = Bool -> Doc -> Doc
mparens (Int
p Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
9) (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$
    Doc
"OpenThing" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> CheckpointId -> Doc
forall a. Pretty a => a -> Doc
pretty CheckpointId
cp Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> [(CheckpointId, Substitution)] -> Doc
forall a. Pretty a => a -> Doc
pretty (Map CheckpointId Substitution -> [(CheckpointId, Substitution)]
forall k a. Map k a -> [(k, a)]
Map.toList Map CheckpointId Substitution
env) Doc -> Doc -> Doc
<?> Int -> a -> Doc
forall a. Pretty a => Int -> a -> Doc
prettyPrec Int
10 a
x

----------------------------------------------------------------------------------------------------
-- * Judgements
--
-- Used exclusively for typing of meta variables.
----------------------------------------------------------------------------------------------------

-- | Parametrized since it is used without MetaId when creating a new meta.
data Judgement a
  = HasType
    { forall a. Judgement a -> a
jMetaId     :: a
    , forall a. Judgement a -> Comparison
jComparison :: Comparison -- ^ are we checking (@CmpLeq@) or inferring (@CmpEq@) the type?
    , forall a. Judgement a -> Teletype
jMetaType   :: Teletype
    }
  | IsSort
    { jMetaId   :: a
    , jMetaType :: Teletype -- Andreas, 2011-04-26: type needed for higher-order sort metas
    }
  deriving (Int -> Judgement a -> ShowS
[Judgement a] -> ShowS
Judgement a -> String
(Int -> Judgement a -> ShowS)
-> (Judgement a -> String)
-> ([Judgement a] -> ShowS)
-> Show (Judgement a)
forall a. Show a => Int -> Judgement a -> ShowS
forall a. Show a => [Judgement a] -> ShowS
forall a. Show a => Judgement a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall a. Show a => Int -> Judgement a -> ShowS
showsPrec :: Int -> Judgement a -> ShowS
$cshow :: forall a. Show a => Judgement a -> String
show :: Judgement a -> String
$cshowList :: forall a. Show a => [Judgement a] -> ShowS
showList :: [Judgement a] -> ShowS
Show, (forall x. Judgement a -> Rep (Judgement a) x)
-> (forall x. Rep (Judgement a) x -> Judgement a)
-> Generic (Judgement a)
forall x. Rep (Judgement a) x -> Judgement a
forall x. Judgement a -> Rep (Judgement a) x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
forall a x. Rep (Judgement a) x -> Judgement a
forall a x. Judgement a -> Rep (Judgement a) x
$cfrom :: forall a x. Judgement a -> Rep (Judgement a) x
from :: forall x. Judgement a -> Rep (Judgement a) x
$cto :: forall a x. Rep (Judgement a) x -> Judgement a
to :: forall x. Rep (Judgement a) x -> Judgement a
Generic)

instance Pretty a => Pretty (Judgement a) where
    pretty :: Judgement a -> Doc
pretty (HasType a
a Comparison
cmp Teletype
t) = [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
hsep [ a -> Doc
forall a. Pretty a => a -> Doc
pretty a
a, Doc
":"    , Teletype -> Doc
forall a. Pretty a => a -> Doc
pretty Teletype
t ]
    pretty (IsSort  a
a Teletype
t)     = [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
hsep [ a -> Doc
forall a. Pretty a => a -> Doc
pretty a
a, Doc
":sort", Teletype -> Doc
forall a. Pretty a => a -> Doc
pretty Teletype
t ]

------------------------------------------------------------------------------------------------------
-- ** Generalizable variables
------------------------------------------------------------------------------------------------------

data DoGeneralize
  = YesGeneralize -- ^ Generalize.
  | NoGeneralize  -- ^ Don't generalize.
  deriving (DoGeneralize -> DoGeneralize -> Bool
(DoGeneralize -> DoGeneralize -> Bool)
-> (DoGeneralize -> DoGeneralize -> Bool) -> Eq DoGeneralize
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DoGeneralize -> DoGeneralize -> Bool
== :: DoGeneralize -> DoGeneralize -> Bool
$c/= :: DoGeneralize -> DoGeneralize -> Bool
/= :: DoGeneralize -> DoGeneralize -> Bool
Eq, Eq DoGeneralize
Eq DoGeneralize =>
(DoGeneralize -> DoGeneralize -> Ordering)
-> (DoGeneralize -> DoGeneralize -> Bool)
-> (DoGeneralize -> DoGeneralize -> Bool)
-> (DoGeneralize -> DoGeneralize -> Bool)
-> (DoGeneralize -> DoGeneralize -> Bool)
-> (DoGeneralize -> DoGeneralize -> DoGeneralize)
-> (DoGeneralize -> DoGeneralize -> DoGeneralize)
-> Ord DoGeneralize
DoGeneralize -> DoGeneralize -> Bool
DoGeneralize -> DoGeneralize -> Ordering
DoGeneralize -> DoGeneralize -> DoGeneralize
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: DoGeneralize -> DoGeneralize -> Ordering
compare :: DoGeneralize -> DoGeneralize -> Ordering
$c< :: DoGeneralize -> DoGeneralize -> Bool
< :: DoGeneralize -> DoGeneralize -> Bool
$c<= :: DoGeneralize -> DoGeneralize -> Bool
<= :: DoGeneralize -> DoGeneralize -> Bool
$c> :: DoGeneralize -> DoGeneralize -> Bool
> :: DoGeneralize -> DoGeneralize -> Bool
$c>= :: DoGeneralize -> DoGeneralize -> Bool
>= :: DoGeneralize -> DoGeneralize -> Bool
$cmax :: DoGeneralize -> DoGeneralize -> DoGeneralize
max :: DoGeneralize -> DoGeneralize -> DoGeneralize
$cmin :: DoGeneralize -> DoGeneralize -> DoGeneralize
min :: DoGeneralize -> DoGeneralize -> DoGeneralize
Ord, Int -> DoGeneralize -> ShowS
[DoGeneralize] -> ShowS
DoGeneralize -> String
(Int -> DoGeneralize -> ShowS)
-> (DoGeneralize -> String)
-> ([DoGeneralize] -> ShowS)
-> Show DoGeneralize
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DoGeneralize -> ShowS
showsPrec :: Int -> DoGeneralize -> ShowS
$cshow :: DoGeneralize -> String
show :: DoGeneralize -> String
$cshowList :: [DoGeneralize] -> ShowS
showList :: [DoGeneralize] -> ShowS
Show, (forall x. DoGeneralize -> Rep DoGeneralize x)
-> (forall x. Rep DoGeneralize x -> DoGeneralize)
-> Generic DoGeneralize
forall x. Rep DoGeneralize x -> DoGeneralize
forall x. DoGeneralize -> Rep DoGeneralize x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. DoGeneralize -> Rep DoGeneralize x
from :: forall x. DoGeneralize -> Rep DoGeneralize x
$cto :: forall x. Rep DoGeneralize x -> DoGeneralize
to :: forall x. Rep DoGeneralize x -> DoGeneralize
Generic)

-- | The value of a generalizable variable. This is created to be a
--   generalizable meta before checking the type to be generalized.
data GeneralizedValue = GeneralizedValue
  { GeneralizedValue -> CheckpointId
genvalCheckpoint :: CheckpointId
  , GeneralizedValue -> Term
genvalTerm       :: Term
  , GeneralizedValue -> Type
genvalType       :: Type
  } deriving (Int -> GeneralizedValue -> ShowS
[GeneralizedValue] -> ShowS
GeneralizedValue -> String
(Int -> GeneralizedValue -> ShowS)
-> (GeneralizedValue -> String)
-> ([GeneralizedValue] -> ShowS)
-> Show GeneralizedValue
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> GeneralizedValue -> ShowS
showsPrec :: Int -> GeneralizedValue -> ShowS
$cshow :: GeneralizedValue -> String
show :: GeneralizedValue -> String
$cshowList :: [GeneralizedValue] -> ShowS
showList :: [GeneralizedValue] -> ShowS
Show, (forall x. GeneralizedValue -> Rep GeneralizedValue x)
-> (forall x. Rep GeneralizedValue x -> GeneralizedValue)
-> Generic GeneralizedValue
forall x. Rep GeneralizedValue x -> GeneralizedValue
forall x. GeneralizedValue -> Rep GeneralizedValue x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. GeneralizedValue -> Rep GeneralizedValue x
from :: forall x. GeneralizedValue -> Rep GeneralizedValue x
$cto :: forall x. Rep GeneralizedValue x -> GeneralizedValue
to :: forall x. Rep GeneralizedValue x -> GeneralizedValue
Generic)

----------------------------------------------------------------------------------------------------
-- ** Meta variables
----------------------------------------------------------------------------------------------------

-- | Information about local meta-variables.

data MetaVariable =
        MetaVar { MetaVariable -> MetaInfo
mvInfo          :: MetaInfo
                , MetaVariable -> MetaPriority
mvPriority      :: MetaPriority -- ^ some metavariables are more eager to be instantiated
                , MetaVariable -> Permutation
mvPermutation   :: Permutation
                  -- ^ A metavariable doesn't have to depend on all variables
                  --   in its original context (stored in mvInfo.miClosRange);
                  --   this thinning (on de Bruijn levels) will throw away the ones
                  --   it does not depend on.
                , MetaVariable -> Judgement MetaId
mvJudgement     :: Judgement MetaId
                , MetaVariable -> MetaInstantiation
mvInstantiation :: MetaInstantiation
                , MetaVariable -> Set Listener
mvListeners     :: Set Listener -- ^ meta variables scheduled for eta-expansion but blocked by this one
                , MetaVariable -> Frozen
mvFrozen        :: Frozen -- ^ are we past the point where we can instantiate this meta variable?
                , MetaVariable -> Maybe MetaId
mvTwin          :: Maybe MetaId
                  -- ^ @Just m@ means that this meta-variable will be
                  -- equated to @m@ when the latter is unblocked. See
                  -- 'Agda.TypeChecking.MetaVars.blockTermOnProblem'.
                , MetaVariable -> Bool
mvError         :: !Bool
                  -- ^ 'True' if this meta was created to recover from a
                  -- type error, and thus should be suppressed from the
                  -- unsolved metas warning.
                }
  deriving (forall x. MetaVariable -> Rep MetaVariable x)
-> (forall x. Rep MetaVariable x -> MetaVariable)
-> Generic MetaVariable
forall x. Rep MetaVariable x -> MetaVariable
forall x. MetaVariable -> Rep MetaVariable x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. MetaVariable -> Rep MetaVariable x
from :: forall x. MetaVariable -> Rep MetaVariable x
$cto :: forall x. Rep MetaVariable x -> MetaVariable
to :: forall x. Rep MetaVariable x -> MetaVariable
Generic

data Listener = EtaExpand MetaId
              | CheckConstraint Nat ProblemConstraint
  deriving (forall x. Listener -> Rep Listener x)
-> (forall x. Rep Listener x -> Listener) -> Generic Listener
forall x. Rep Listener x -> Listener
forall x. Listener -> Rep Listener x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Listener -> Rep Listener x
from :: forall x. Listener -> Rep Listener x
$cto :: forall x. Rep Listener x -> Listener
to :: forall x. Rep Listener x -> Listener
Generic

instance Eq Listener where
  EtaExpand       MetaId
x   == :: Listener -> Listener -> Bool
== EtaExpand       MetaId
y   = MetaId
x MetaId -> MetaId -> Bool
forall a. Eq a => a -> a -> Bool
== MetaId
y
  CheckConstraint Int
x ProblemConstraint
_ == CheckConstraint Int
y ProblemConstraint
_ = Int
x Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
y
  Listener
_ == Listener
_ = Bool
False

instance Ord Listener where
  EtaExpand       MetaId
x   compare :: Listener -> Listener -> Ordering
`compare` EtaExpand       MetaId
y   = MetaId
x MetaId -> MetaId -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` MetaId
y
  CheckConstraint Int
x ProblemConstraint
_ `compare` CheckConstraint Int
y ProblemConstraint
_ = Int
x Int -> Int -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Int
y
  EtaExpand{} `compare` CheckConstraint{} = Ordering
LT
  CheckConstraint{} `compare` EtaExpand{} = Ordering
GT

-- | Frozen meta variable cannot be instantiated by unification.
--   This serves to prevent the completion of a definition by its use
--   outside of the current block.
--   (See issues 118, 288, 399).
data Frozen
  = Frozen        -- ^ Do not instantiate.
  | Instantiable
    deriving (Frozen -> Frozen -> Bool
(Frozen -> Frozen -> Bool)
-> (Frozen -> Frozen -> Bool) -> Eq Frozen
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Frozen -> Frozen -> Bool
== :: Frozen -> Frozen -> Bool
$c/= :: Frozen -> Frozen -> Bool
/= :: Frozen -> Frozen -> Bool
Eq, Int -> Frozen -> ShowS
[Frozen] -> ShowS
Frozen -> String
(Int -> Frozen -> ShowS)
-> (Frozen -> String) -> ([Frozen] -> ShowS) -> Show Frozen
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Frozen -> ShowS
showsPrec :: Int -> Frozen -> ShowS
$cshow :: Frozen -> String
show :: Frozen -> String
$cshowList :: [Frozen] -> ShowS
showList :: [Frozen] -> ShowS
Show, (forall x. Frozen -> Rep Frozen x)
-> (forall x. Rep Frozen x -> Frozen) -> Generic Frozen
forall x. Rep Frozen x -> Frozen
forall x. Frozen -> Rep Frozen x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Frozen -> Rep Frozen x
from :: forall x. Frozen -> Rep Frozen x
$cto :: forall x. Rep Frozen x -> Frozen
to :: forall x. Rep Frozen x -> Frozen
Generic)

-- | Solution status of meta.
data MetaInstantiation
  = InstV Instantiation -- ^ Solved by 'Instantiation'.
  | OpenMeta MetaKind   -- ^ Unsolved (open to solutions).
  | BlockedConst Term   -- ^ Solved, but solution blocked by unsolved constraints.
  | PostponedTypeCheckingProblem (Closure TypeCheckingProblem)
      -- ^ Meta stands for value of the expression that is still to be type checked.
  deriving (forall x. MetaInstantiation -> Rep MetaInstantiation x)
-> (forall x. Rep MetaInstantiation x -> MetaInstantiation)
-> Generic MetaInstantiation
forall x. Rep MetaInstantiation x -> MetaInstantiation
forall x. MetaInstantiation -> Rep MetaInstantiation x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. MetaInstantiation -> Rep MetaInstantiation x
from :: forall x. MetaInstantiation -> Rep MetaInstantiation x
$cto :: forall x. Rep MetaInstantiation x -> MetaInstantiation
to :: forall x. Rep MetaInstantiation x -> MetaInstantiation
Generic

-- | Meta-variable instantiations.

data Instantiation = Instantiation
  { Instantiation -> [Arg ShortText]
instTel :: [Arg ShortText]
    -- ^ The solution is abstracted over these free variables.
  , Instantiation -> Term
instBody :: Term
    -- ^ The body of the solution.
  }
  deriving (Int -> Instantiation -> ShowS
[Instantiation] -> ShowS
Instantiation -> String
(Int -> Instantiation -> ShowS)
-> (Instantiation -> String)
-> ([Instantiation] -> ShowS)
-> Show Instantiation
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Instantiation -> ShowS
showsPrec :: Int -> Instantiation -> ShowS
$cshow :: Instantiation -> String
show :: Instantiation -> String
$cshowList :: [Instantiation] -> ShowS
showList :: [Instantiation] -> ShowS
Show, (forall x. Instantiation -> Rep Instantiation x)
-> (forall x. Rep Instantiation x -> Instantiation)
-> Generic Instantiation
forall x. Rep Instantiation x -> Instantiation
forall x. Instantiation -> Rep Instantiation x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Instantiation -> Rep Instantiation x
from :: forall x. Instantiation -> Rep Instantiation x
$cto :: forall x. Rep Instantiation x -> Instantiation
to :: forall x. Rep Instantiation x -> Instantiation
Generic)

-- | Information about remote meta-variables.
--
-- Remote meta-variables are meta-variables originating in other
-- modules. These meta-variables are always instantiated. We do not
-- retain all the information about a local meta-variable when
-- creating an interface:
--
-- * The 'mvPriority' field is not needed, because the meta-variable
--   cannot be instantiated.
-- * The 'mvFrozen' field is not needed, because there is no point in
--   freezing instantiated meta-variables.
-- * The 'mvListeners' field is not needed, because no meta-variable
--   should be listening to this one.
-- * The 'mvTwin' field is not needed, because the meta-variable has
--   already been instantiated.
-- * The 'mvPermutation' is currently removed, but could be retained
--   if it turns out to be useful for something.
-- * No part of the 'mvInfo' field is kept. The 'miMetaOccursCheck' and 'miGeneralizable'
--   fields are omitted, because the meta-variable has already been
--   instantiated. The 'Range' that is part of the 'miClosRange' field
--   and the 'miNameSuggestion' field are omitted because instantiated
--   meta-variables are typically not presented to users. Finally the
--   'Closure' part of the 'miClosRange' field is omitted because it
--   can be large (at least if we ignore potential sharing).

data RemoteMetaVariable = RemoteMetaVariable
  { RemoteMetaVariable -> Instantiation
rmvInstantiation :: Instantiation
  , RemoteMetaVariable -> Judgement MetaId
rmvJudgement     :: Judgement MetaId
  }
  deriving (Int -> RemoteMetaVariable -> ShowS
[RemoteMetaVariable] -> ShowS
RemoteMetaVariable -> String
(Int -> RemoteMetaVariable -> ShowS)
-> (RemoteMetaVariable -> String)
-> ([RemoteMetaVariable] -> ShowS)
-> Show RemoteMetaVariable
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RemoteMetaVariable -> ShowS
showsPrec :: Int -> RemoteMetaVariable -> ShowS
$cshow :: RemoteMetaVariable -> String
show :: RemoteMetaVariable -> String
$cshowList :: [RemoteMetaVariable] -> ShowS
showList :: [RemoteMetaVariable] -> ShowS
Show, (forall x. RemoteMetaVariable -> Rep RemoteMetaVariable x)
-> (forall x. Rep RemoteMetaVariable x -> RemoteMetaVariable)
-> Generic RemoteMetaVariable
forall x. Rep RemoteMetaVariable x -> RemoteMetaVariable
forall x. RemoteMetaVariable -> Rep RemoteMetaVariable x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. RemoteMetaVariable -> Rep RemoteMetaVariable x
from :: forall x. RemoteMetaVariable -> Rep RemoteMetaVariable x
$cto :: forall x. Rep RemoteMetaVariable x -> RemoteMetaVariable
to :: forall x. Rep RemoteMetaVariable x -> RemoteMetaVariable
Generic)

-- | Solving a 'CheckArgs' constraint may or may not check the target type. If
--   it did, it returns a handle to any unsolved constraints.
data CheckedTarget = CheckedTarget (Maybe ProblemId)
                   | NotCheckedTarget
  deriving Int -> CheckedTarget -> ShowS
[CheckedTarget] -> ShowS
CheckedTarget -> String
(Int -> CheckedTarget -> ShowS)
-> (CheckedTarget -> String)
-> ([CheckedTarget] -> ShowS)
-> Show CheckedTarget
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CheckedTarget -> ShowS
showsPrec :: Int -> CheckedTarget -> ShowS
$cshow :: CheckedTarget -> String
show :: CheckedTarget -> String
$cshowList :: [CheckedTarget] -> ShowS
showList :: [CheckedTarget] -> ShowS
Show

data PrincipalArgTypeMetas = PrincipalArgTypeMetas
  { PrincipalArgTypeMetas -> Args
patmMetas     :: Args -- ^ metas created for hidden and instance arguments
                          --   in the principal argument's type
  , PrincipalArgTypeMetas -> Type
patmRemainder :: Type -- ^ principal argument's type, stripped of hidden and
                          --   instance arguments
  }
  deriving (forall x. PrincipalArgTypeMetas -> Rep PrincipalArgTypeMetas x)
-> (forall x. Rep PrincipalArgTypeMetas x -> PrincipalArgTypeMetas)
-> Generic PrincipalArgTypeMetas
forall x. Rep PrincipalArgTypeMetas x -> PrincipalArgTypeMetas
forall x. PrincipalArgTypeMetas -> Rep PrincipalArgTypeMetas x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PrincipalArgTypeMetas -> Rep PrincipalArgTypeMetas x
from :: forall x. PrincipalArgTypeMetas -> Rep PrincipalArgTypeMetas x
$cto :: forall x. Rep PrincipalArgTypeMetas x -> PrincipalArgTypeMetas
to :: forall x. Rep PrincipalArgTypeMetas x -> PrincipalArgTypeMetas
Generic

instance AllMetas PrincipalArgTypeMetas where
  allMetas :: forall m. Monoid m => (MetaId -> m) -> PrincipalArgTypeMetas -> m
allMetas MetaId -> m
f (PrincipalArgTypeMetas Args
vs Type
ty) = (MetaId -> m) -> (Args, Type) -> m
forall m. Monoid m => (MetaId -> m) -> (Args, Type) -> m
forall t m. (AllMetas t, Monoid m) => (MetaId -> m) -> t -> m
allMetas MetaId -> m
f (Args
vs,Type
ty)

-- | Data needed for error reporting while type-checking a @with@ application.
data WithAppHead = WithAppHead
  { WithAppHead -> QName
wahTopName :: QName
    -- ^ The name of the top-level function we're checking.
  , WithAppHead -> Expr
wahExpr    :: A.Expr
    -- ^ The checked expression to the left of the pipes.
  }
  deriving (Int -> WithAppHead -> ShowS
[WithAppHead] -> ShowS
WithAppHead -> String
(Int -> WithAppHead -> ShowS)
-> (WithAppHead -> String)
-> ([WithAppHead] -> ShowS)
-> Show WithAppHead
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> WithAppHead -> ShowS
showsPrec :: Int -> WithAppHead -> ShowS
$cshow :: WithAppHead -> String
show :: WithAppHead -> String
$cshowList :: [WithAppHead] -> ShowS
showList :: [WithAppHead] -> ShowS
Show, (forall x. WithAppHead -> Rep WithAppHead x)
-> (forall x. Rep WithAppHead x -> WithAppHead)
-> Generic WithAppHead
forall x. Rep WithAppHead x -> WithAppHead
forall x. WithAppHead -> Rep WithAppHead x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. WithAppHead -> Rep WithAppHead x
from :: forall x. WithAppHead -> Rep WithAppHead x
$cto :: forall x. Rep WithAppHead x -> WithAppHead
to :: forall x. Rep WithAppHead x -> WithAppHead
Generic)

-- | An elaboration problem that can not make progress without further
-- metavariable instantiation.
--
-- This type is essentially a defunctionalisation of those elaboration
-- functions which can not decide on the shape of the output term when
-- the expected type is blocked.
-- The constructors store all the arguments necessary to make a resuming
-- function call when progress has been made on the blocker (which is
-- computed in 'Mikan.TypeChecking.MetaVars.postponeTypeCheckingProblem_').
data TypeCheckingProblem
  = CheckExpr Comparison A.Expr Type
    -- ^ A postponed call to 'Mikan.TypeChecking.Rules.Term.checkExpr''.
  | CheckArgs Comparison ExpandHidden A.Expr [NamedArg A.Expr] Type Type (ArgsCheckState CheckedTarget -> TCM Term)
    -- ^ A postponed call to 'Mikan.TypeChecking.Rules.Application.checkArguments'.
  | CheckProjAppToKnownPrincipalArg Comparison A.Expr ProjOrigin AmbiguousQName A.Expr A.Args Type Int Term Type PrincipalArgTypeMetas
    -- ^ A postponed call to 'Mikan.TypeChecking.Rules.Application.checkProjAppToKnownPrincipalArg'.
  | CheckWithApp     Comparison Type WithAppHead QName Elims (List1 A.Expr)
    -- ^ A postponed call to 'Mikan.TypeChecking.Rules.WithApp.checkWithApplication'.
  | CheckWithAppHead Comparison Type A.Expr Term (List1 A.Expr)
    -- ^ A postponed call to 'Mikan.TypeChecking.Rules.WithApp.checkWithAppHead'.
  | DisambiguateConstructor ConstructorDisambiguationData (ConHead -> TCM Term)
    -- ^ A postponed call to 'Mikan.TypeChecking.Rules.Application.disambiguateConstructor''
  | DoQuoteTerm Comparison Term Type
    -- ^ A postponed call to 'Mikan.TypeChecking.Rules.Term.doQuoteTerm'.
  deriving (forall x. TypeCheckingProblem -> Rep TypeCheckingProblem x)
-> (forall x. Rep TypeCheckingProblem x -> TypeCheckingProblem)
-> Generic TypeCheckingProblem
forall x. Rep TypeCheckingProblem x -> TypeCheckingProblem
forall x. TypeCheckingProblem -> Rep TypeCheckingProblem x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TypeCheckingProblem -> Rep TypeCheckingProblem x
from :: forall x. TypeCheckingProblem -> Rep TypeCheckingProblem x
$cto :: forall x. Rep TypeCheckingProblem x -> TypeCheckingProblem
to :: forall x. Rep TypeCheckingProblem x -> TypeCheckingProblem
Generic

-- | The state required for resuming a postponed constructor
-- disambiguation problem.
--
-- The @bcd@ prefix is short for "blocked constructor disambiguation".
data ConstructorDisambiguationData
  = ConstructorDisambiguationData
    { ConstructorDisambiguationData -> QName
bcdConName    :: QName
      -- ^ An arbitrary choice among the eligible ambiguous names (for error messages).
    , ConstructorDisambiguationData -> List1 (QName, Type, ConHead)
bcdCandidates :: List1 (QName, Type, ConHead)
      -- ^ The possible candidates for disambiguation.
      --
      -- The 'QName' is the name of the data type which the candidate
      -- constructs; the actual candidate name can be found in the
      -- 'ConHead'.
      --
      -- The 'Type' is the type of the candidate, including the parameter
      -- telescope (including parameters introduced by lifting out of a
      -- parametrised module).
    , ConstructorDisambiguationData -> Args
bcdArguments  :: A.Args
      -- ^ The arguments given to the constructor, to be checked.
    , ConstructorDisambiguationData -> Type
bcdType       :: Type
      -- ^ The expected type for this constructor application.
    }
  deriving (forall x.
 ConstructorDisambiguationData
 -> Rep ConstructorDisambiguationData x)
-> (forall x.
    Rep ConstructorDisambiguationData x
    -> ConstructorDisambiguationData)
-> Generic ConstructorDisambiguationData
forall x.
Rep ConstructorDisambiguationData x
-> ConstructorDisambiguationData
forall x.
ConstructorDisambiguationData
-> Rep ConstructorDisambiguationData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x.
ConstructorDisambiguationData
-> Rep ConstructorDisambiguationData x
from :: forall x.
ConstructorDisambiguationData
-> Rep ConstructorDisambiguationData x
$cto :: forall x.
Rep ConstructorDisambiguationData x
-> ConstructorDisambiguationData
to :: forall x.
Rep ConstructorDisambiguationData x
-> ConstructorDisambiguationData
Generic

instance Pretty MetaInstantiation where
  pretty :: MetaInstantiation -> Doc
pretty = \case
    OpenMeta MetaKind
UnificationMeta                 -> Doc
"Open"
    OpenMeta MetaKind
InstanceMeta                    -> Doc
"OpenInstance"
    PostponedTypeCheckingProblem{}           -> Doc
"PostponedTypeCheckingProblem (...)"
    BlockedConst Term
t                           -> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
hsep [ Doc
"BlockedConst", Doc -> Doc
parens (Term -> Doc
forall a. Pretty a => a -> Doc
pretty Term
t) ]
    InstV Instantiation{ [Arg ShortText]
instTel :: Instantiation -> [Arg ShortText]
instTel :: [Arg ShortText]
instTel, Term
instBody :: Instantiation -> Term
instBody :: Term
instBody } -> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
hsep [ Doc
"InstV", [Arg ShortText] -> Doc
forall a. Pretty a => a -> Doc
pretty [Arg ShortText]
instTel, Doc -> Doc
parens (Term -> Doc
forall a. Pretty a => a -> Doc
pretty Term
instBody) ]

-- | Meta variable priority:
--   When we have an equation between meta-variables, which one
--   should be instantiated?
--
--   Higher value means higher priority to be instantiated.
newtype MetaPriority = MetaPriority Int
    deriving (MetaPriority -> MetaPriority -> Bool
(MetaPriority -> MetaPriority -> Bool)
-> (MetaPriority -> MetaPriority -> Bool) -> Eq MetaPriority
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: MetaPriority -> MetaPriority -> Bool
== :: MetaPriority -> MetaPriority -> Bool
$c/= :: MetaPriority -> MetaPriority -> Bool
/= :: MetaPriority -> MetaPriority -> Bool
Eq, Eq MetaPriority
Eq MetaPriority =>
(MetaPriority -> MetaPriority -> Ordering)
-> (MetaPriority -> MetaPriority -> Bool)
-> (MetaPriority -> MetaPriority -> Bool)
-> (MetaPriority -> MetaPriority -> Bool)
-> (MetaPriority -> MetaPriority -> Bool)
-> (MetaPriority -> MetaPriority -> MetaPriority)
-> (MetaPriority -> MetaPriority -> MetaPriority)
-> Ord MetaPriority
MetaPriority -> MetaPriority -> Bool
MetaPriority -> MetaPriority -> Ordering
MetaPriority -> MetaPriority -> MetaPriority
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: MetaPriority -> MetaPriority -> Ordering
compare :: MetaPriority -> MetaPriority -> Ordering
$c< :: MetaPriority -> MetaPriority -> Bool
< :: MetaPriority -> MetaPriority -> Bool
$c<= :: MetaPriority -> MetaPriority -> Bool
<= :: MetaPriority -> MetaPriority -> Bool
$c> :: MetaPriority -> MetaPriority -> Bool
> :: MetaPriority -> MetaPriority -> Bool
$c>= :: MetaPriority -> MetaPriority -> Bool
>= :: MetaPriority -> MetaPriority -> Bool
$cmax :: MetaPriority -> MetaPriority -> MetaPriority
max :: MetaPriority -> MetaPriority -> MetaPriority
$cmin :: MetaPriority -> MetaPriority -> MetaPriority
min :: MetaPriority -> MetaPriority -> MetaPriority
Ord, Int -> MetaPriority -> ShowS
[MetaPriority] -> ShowS
MetaPriority -> String
(Int -> MetaPriority -> ShowS)
-> (MetaPriority -> String)
-> ([MetaPriority] -> ShowS)
-> Show MetaPriority
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MetaPriority -> ShowS
showsPrec :: Int -> MetaPriority -> ShowS
$cshow :: MetaPriority -> String
show :: MetaPriority -> String
$cshowList :: [MetaPriority] -> ShowS
showList :: [MetaPriority] -> ShowS
Show, MetaPriority -> ()
(MetaPriority -> ()) -> NFData MetaPriority
forall a. (a -> ()) -> NFData a
$crnf :: MetaPriority -> ()
rnf :: MetaPriority -> ()
NFData)

data RunMetaOccursCheck
  = RunMetaOccursCheck
  | DontRunMetaOccursCheck
  deriving (RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
(RunMetaOccursCheck -> RunMetaOccursCheck -> Bool)
-> (RunMetaOccursCheck -> RunMetaOccursCheck -> Bool)
-> Eq RunMetaOccursCheck
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
== :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
$c/= :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
/= :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
Eq, Eq RunMetaOccursCheck
Eq RunMetaOccursCheck =>
(RunMetaOccursCheck -> RunMetaOccursCheck -> Ordering)
-> (RunMetaOccursCheck -> RunMetaOccursCheck -> Bool)
-> (RunMetaOccursCheck -> RunMetaOccursCheck -> Bool)
-> (RunMetaOccursCheck -> RunMetaOccursCheck -> Bool)
-> (RunMetaOccursCheck -> RunMetaOccursCheck -> Bool)
-> (RunMetaOccursCheck -> RunMetaOccursCheck -> RunMetaOccursCheck)
-> (RunMetaOccursCheck -> RunMetaOccursCheck -> RunMetaOccursCheck)
-> Ord RunMetaOccursCheck
RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
RunMetaOccursCheck -> RunMetaOccursCheck -> Ordering
RunMetaOccursCheck -> RunMetaOccursCheck -> RunMetaOccursCheck
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: RunMetaOccursCheck -> RunMetaOccursCheck -> Ordering
compare :: RunMetaOccursCheck -> RunMetaOccursCheck -> Ordering
$c< :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
< :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
$c<= :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
<= :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
$c> :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
> :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
$c>= :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
>= :: RunMetaOccursCheck -> RunMetaOccursCheck -> Bool
$cmax :: RunMetaOccursCheck -> RunMetaOccursCheck -> RunMetaOccursCheck
max :: RunMetaOccursCheck -> RunMetaOccursCheck -> RunMetaOccursCheck
$cmin :: RunMetaOccursCheck -> RunMetaOccursCheck -> RunMetaOccursCheck
min :: RunMetaOccursCheck -> RunMetaOccursCheck -> RunMetaOccursCheck
Ord, Int -> RunMetaOccursCheck -> ShowS
[RunMetaOccursCheck] -> ShowS
RunMetaOccursCheck -> String
(Int -> RunMetaOccursCheck -> ShowS)
-> (RunMetaOccursCheck -> String)
-> ([RunMetaOccursCheck] -> ShowS)
-> Show RunMetaOccursCheck
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RunMetaOccursCheck -> ShowS
showsPrec :: Int -> RunMetaOccursCheck -> ShowS
$cshow :: RunMetaOccursCheck -> String
show :: RunMetaOccursCheck -> String
$cshowList :: [RunMetaOccursCheck] -> ShowS
showList :: [RunMetaOccursCheck] -> ShowS
Show, (forall x. RunMetaOccursCheck -> Rep RunMetaOccursCheck x)
-> (forall x. Rep RunMetaOccursCheck x -> RunMetaOccursCheck)
-> Generic RunMetaOccursCheck
forall x. Rep RunMetaOccursCheck x -> RunMetaOccursCheck
forall x. RunMetaOccursCheck -> Rep RunMetaOccursCheck x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. RunMetaOccursCheck -> Rep RunMetaOccursCheck x
from :: forall x. RunMetaOccursCheck -> Rep RunMetaOccursCheck x
$cto :: forall x. Rep RunMetaOccursCheck x -> RunMetaOccursCheck
to :: forall x. Rep RunMetaOccursCheck x -> RunMetaOccursCheck
Generic)

-- | @MetaInfo@ is cloned from one meta to the next during pruning.
data MetaInfo = MetaInfo
  { MetaInfo -> Closure Range
miClosRange       :: Closure Range -- TODO: Not so nice. But we want both to have the environment of the meta (Closure) and its range.
  , MetaInfo -> RunMetaOccursCheck
miMetaOccursCheck :: RunMetaOccursCheck -- ^ Run the extended occurs check that goes in definitions?
  , MetaInfo -> ShortText
miNameSuggestion  :: MetaNameSuggestion
    -- ^ Used for printing.
    --   @Just x@ if meta-variable comes from omitted argument with name @x@.
  , MetaInfo -> Arg DoGeneralize
miGeneralizable   :: Arg DoGeneralize
    -- ^ Should this meta be generalized if unsolved? If so, at what ArgInfo?
    -- If visible, it will be made hidden before generalising.
  }
  deriving (forall x. MetaInfo -> Rep MetaInfo x)
-> (forall x. Rep MetaInfo x -> MetaInfo) -> Generic MetaInfo
forall x. Rep MetaInfo x -> MetaInfo
forall x. MetaInfo -> Rep MetaInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. MetaInfo -> Rep MetaInfo x
from :: forall x. MetaInfo -> Rep MetaInfo x
$cto :: forall x. Rep MetaInfo x -> MetaInfo
to :: forall x. Rep MetaInfo x -> MetaInfo
Generic

-- | Append an 'ArgName' to a 'MetaNameSuggestion', for computing the
-- name suggestions of eta-expansion metas. If the 'MetaNameSuggestion'
-- is empty or an underscore, the field name is taken as the suggestion.
suffixNameSuggestion :: MetaNameSuggestion -> ArgName -> MetaNameSuggestion
suffixNameSuggestion :: ShortText -> ShortText -> ShortText
suffixNameSuggestion ShortText
"_"    ShortText
field = ShortText
field
suffixNameSuggestion ShortText
""     ShortText
field = ShortText
field
suffixNameSuggestion ShortText
record ShortText
field = ShortText
record ShortText -> ShortText -> ShortText
forall a. Semigroup a => a -> a -> a
<> ShortText
"." ShortText -> ShortText -> ShortText
forall a. Semigroup a => a -> a -> a
<> ShortText
field

instance Pretty NamedMeta where
  pretty :: NamedMeta -> Doc
pretty (NamedMeta ShortText
"" MetaId
x) = MetaId -> Doc
forall a. Pretty a => a -> Doc
pretty MetaId
x
  pretty (NamedMeta ShortText
"_" MetaId
x) = MetaId -> Doc
forall a. Pretty a => a -> Doc
pretty MetaId
x
  pretty (NamedMeta ShortText
s  MetaId
x) = String -> Doc
forall a. String -> Doc a
text (String -> Doc) -> String -> Doc
forall a b. (a -> b) -> a -> b
$ String
"_" String -> ShowS
forall a. [a] -> [a] -> [a]
++ ShortText -> String
TS.unpack ShortText
s String -> ShowS
forall a. [a] -> [a] -> [a]
++ MetaId -> String
forall a. Pretty a => a -> String
prettyShow MetaId
x

-- | Used for meta-variables from the current module.

type LocalMetaStore = Map MetaId MetaVariable

{-# SPECIALIZE Map.insert :: MetaId -> v -> Map MetaId v -> Map MetaId v #-}
{-# SPECIALIZE Map.lookup :: MetaId -> Map MetaId v -> Maybe v #-}

-- | Used for meta-variables from other modules (and in 'Interface's).

type RemoteMetaStore = HashMap MetaId RemoteMetaVariable

instance HasRange MetaInfo where
  getRange :: MetaInfo -> Range
getRange = Closure Range -> Range
forall a. Closure a -> a
clValue (Closure Range -> Range)
-> (MetaInfo -> Closure Range) -> MetaInfo -> Range
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MetaInfo -> Closure Range
miClosRange

instance HasRange MetaVariable where
    getRange :: MetaVariable -> Range
getRange MetaVariable
m = Closure Range -> Range
forall a. HasRange a => a -> Range
getRange (Closure Range -> Range) -> Closure Range -> Range
forall a b. (a -> b) -> a -> b
$ MetaVariable -> Closure Range
getMetaInfo MetaVariable
m

instance SetRange MetaInfo where
  setRange :: Range -> MetaInfo -> MetaInfo
setRange Range
r MetaInfo
m = MetaInfo
m { miClosRange = (miClosRange m) { clValue = r }}

instance SetRange MetaVariable where
  setRange :: Range -> MetaVariable -> MetaVariable
setRange Range
r MetaVariable
m = MetaVariable
m { mvInfo = setRange r (mvInfo m) }

normalMetaPriority :: MetaPriority
normalMetaPriority :: MetaPriority
normalMetaPriority = Int -> MetaPriority
MetaPriority Int
0

lowMetaPriority :: MetaPriority
lowMetaPriority :: MetaPriority
lowMetaPriority = Int -> MetaPriority
MetaPriority (-Int
10)

highMetaPriority :: MetaPriority
highMetaPriority :: MetaPriority
highMetaPriority = Int -> MetaPriority
MetaPriority Int
10

getMetaInfo :: MetaVariable -> Closure Range
getMetaInfo :: MetaVariable -> Closure Range
getMetaInfo = MetaInfo -> Closure Range
miClosRange (MetaInfo -> Closure Range)
-> (MetaVariable -> MetaInfo) -> MetaVariable -> Closure Range
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MetaVariable -> MetaInfo
mvInfo

getMetaScope :: MetaVariable -> ScopeInfo
getMetaScope :: MetaVariable -> ScopeInfo
getMetaScope MetaVariable
m = Closure Range -> ScopeInfo
forall a. Closure a -> ScopeInfo
clScope (Closure Range -> ScopeInfo) -> Closure Range -> ScopeInfo
forall a b. (a -> b) -> a -> b
$ MetaVariable -> Closure Range
getMetaInfo MetaVariable
m

getMetaEnv :: MetaVariable -> TCEnv
getMetaEnv :: MetaVariable -> TCEnv
getMetaEnv MetaVariable
m = Closure Range -> TCEnv
forall a. Closure a -> TCEnv
clEnv (Closure Range -> TCEnv) -> Closure Range -> TCEnv
forall a b. (a -> b) -> a -> b
$ MetaVariable -> Closure Range
getMetaInfo MetaVariable
m

getMetaSig :: MetaVariable -> Signature
getMetaSig :: MetaVariable -> Signature
getMetaSig MetaVariable
m = Closure Range -> Signature
forall a. Closure a -> Signature
clSignature (Closure Range -> Signature) -> Closure Range -> Signature
forall a b. (a -> b) -> a -> b
$ MetaVariable -> Closure Range
getMetaInfo MetaVariable
m

-- Lenses

metaFrozen :: Lens' MetaVariable Frozen
metaFrozen :: Lens' MetaVariable Frozen
metaFrozen Frozen -> f Frozen
f MetaVariable
mv = Frozen -> f Frozen
f (MetaVariable -> Frozen
mvFrozen MetaVariable
mv) f Frozen -> (Frozen -> MetaVariable) -> f MetaVariable
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Frozen
x -> MetaVariable
mv { mvFrozen = x }

_mvInfo :: Lens' MetaVariable MetaInfo
_mvInfo :: Lens' MetaVariable MetaInfo
_mvInfo MetaInfo -> f MetaInfo
f MetaVariable
mv = (MetaInfo -> f MetaInfo
f (MetaInfo -> f MetaInfo) -> MetaInfo -> f MetaInfo
forall a b. (a -> b) -> a -> b
$! MetaVariable -> MetaInfo
mvInfo MetaVariable
mv) f MetaInfo -> (MetaInfo -> MetaVariable) -> f MetaVariable
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ MetaInfo
mi -> MetaVariable
mv { mvInfo = mi }

-- Lenses onto Closure Range

instance LensClosure MetaInfo Range where
  lensClosure :: Lens' MetaInfo (Closure Range)
lensClosure Closure Range -> f (Closure Range)
f MetaInfo
mi = (Closure Range -> f (Closure Range)
f (Closure Range -> f (Closure Range))
-> Closure Range -> f (Closure Range)
forall a b. (a -> b) -> a -> b
$! MetaInfo -> Closure Range
miClosRange MetaInfo
mi) f (Closure Range) -> (Closure Range -> MetaInfo) -> f MetaInfo
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Closure Range
cl -> MetaInfo
mi { miClosRange = cl }

instance LensClosure MetaVariable Range where
  lensClosure :: Lens' MetaVariable (Closure Range)
lensClosure = (MetaInfo -> f MetaInfo) -> MetaVariable -> f MetaVariable
Lens' MetaVariable MetaInfo
_mvInfo ((MetaInfo -> f MetaInfo) -> MetaVariable -> f MetaVariable)
-> ((Closure Range -> f (Closure Range)) -> MetaInfo -> f MetaInfo)
-> (Closure Range -> f (Closure Range))
-> MetaVariable
-> f MetaVariable
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Closure Range -> f (Closure Range)) -> MetaInfo -> f MetaInfo
forall b a. LensClosure b a => Lens' b (Closure a)
Lens' MetaInfo (Closure Range)
lensClosure

-- Lenses onto IsAbstract

instance LensIsAbstract TCEnv where
  lensIsAbstract :: Lens' TCEnv IsAbstract
lensIsAbstract IsAbstract -> f IsAbstract
f TCEnv
env =
     -- Andreas, 2019-08-19
     -- Using $! to prevent space leaks like #1829.
     -- This can crash when trying to get IsAbstract from IgnoreAbstractMode.
    (IsAbstract -> f IsAbstract
f (IsAbstract -> f IsAbstract) -> IsAbstract -> f IsAbstract
forall a b. (a -> b) -> a -> b
$! IsAbstract -> Maybe IsAbstract -> IsAbstract
forall a. a -> Maybe a -> a
fromMaybe IsAbstract
forall a. HasCallStack => a
__IMPOSSIBLE__ (AbstractMode -> Maybe IsAbstract
aModeToDef (AbstractMode -> Maybe IsAbstract)
-> AbstractMode -> Maybe IsAbstract
forall a b. (a -> b) -> a -> b
$ TCEnv
env TCEnv -> Getting AbstractMode TCEnv AbstractMode -> AbstractMode
forall s a. s -> Getting a s a -> a
^. Getting AbstractMode TCEnv AbstractMode
Lens' TCEnv AbstractMode
eAbstractMode))
    f IsAbstract -> (IsAbstract -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \IsAbstract
a -> TCEnv
env TCEnv -> (TCEnv -> TCEnv) -> TCEnv
forall a b. a -> (a -> b) -> b
& (AbstractMode -> Identity AbstractMode) -> TCEnv -> Identity TCEnv
Lens' TCEnv AbstractMode
eAbstractMode ((AbstractMode -> Identity AbstractMode)
 -> TCEnv -> Identity TCEnv)
-> AbstractMode -> TCEnv -> TCEnv
forall s t a b. ASetter s t a b -> b -> s -> t
.~ IsAbstract -> AbstractMode
aDefToMode IsAbstract
a

instance LensIsAbstract (Closure a) where
  lensIsAbstract :: Lens' (Closure a) IsAbstract
lensIsAbstract = (TCEnv -> f TCEnv) -> Closure a -> f (Closure a)
forall a. LensTCEnv a => Lens' a TCEnv
Lens' (Closure a) TCEnv
lensTCEnv ((TCEnv -> f TCEnv) -> Closure a -> f (Closure a))
-> ((IsAbstract -> f IsAbstract) -> TCEnv -> f TCEnv)
-> (IsAbstract -> f IsAbstract)
-> Closure a
-> f (Closure a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (IsAbstract -> f IsAbstract) -> TCEnv -> f TCEnv
forall a. LensIsAbstract a => Lens' a IsAbstract
Lens' TCEnv IsAbstract
lensIsAbstract

instance LensIsAbstract MetaInfo where
  lensIsAbstract :: Lens' MetaInfo IsAbstract
lensIsAbstract = (Closure Range -> f (Closure Range)) -> MetaInfo -> f MetaInfo
forall b a. LensClosure b a => Lens' b (Closure a)
Lens' MetaInfo (Closure Range)
lensClosure ((Closure Range -> f (Closure Range)) -> MetaInfo -> f MetaInfo)
-> ((IsAbstract -> f IsAbstract)
    -> Closure Range -> f (Closure Range))
-> (IsAbstract -> f IsAbstract)
-> MetaInfo
-> f MetaInfo
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (IsAbstract -> f IsAbstract) -> Closure Range -> f (Closure Range)
forall a. LensIsAbstract a => Lens' a IsAbstract
Lens' (Closure Range) IsAbstract
lensIsAbstract

instance LensIsOpaque TCEnv where
  lensIsOpaque :: Lens' TCEnv IsOpaque
lensIsOpaque IsOpaque -> f IsOpaque
f TCEnv
env =
    (IsOpaque -> f IsOpaque
f (IsOpaque -> f IsOpaque) -> IsOpaque -> f IsOpaque
forall a b. (a -> b) -> a -> b
$! case TCEnv
env TCEnv
-> Getting (Maybe OpaqueId) TCEnv (Maybe OpaqueId)
-> Maybe OpaqueId
forall s a. s -> Getting a s a -> a
^. Getting (Maybe OpaqueId) TCEnv (Maybe OpaqueId)
Lens' TCEnv (Maybe OpaqueId)
eCurrentOpaqueId of { Just OpaqueId
x -> OpaqueId -> IsOpaque
OpaqueDef OpaqueId
x ; Maybe OpaqueId
Nothing -> IsOpaque
TransparentDef })
    f IsOpaque -> (IsOpaque -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \case OpaqueDef OpaqueId
x    -> TCEnv
env TCEnv -> (TCEnv -> TCEnv) -> TCEnv
forall a b. a -> (a -> b) -> b
& (Maybe OpaqueId -> Identity (Maybe OpaqueId))
-> TCEnv -> Identity TCEnv
Lens' TCEnv (Maybe OpaqueId)
eCurrentOpaqueId ((Maybe OpaqueId -> Identity (Maybe OpaqueId))
 -> TCEnv -> Identity TCEnv)
-> Maybe OpaqueId -> TCEnv -> TCEnv
forall s t a b. ASetter s t a b -> b -> s -> t
.~ OpaqueId -> Maybe OpaqueId
forall a. a -> Maybe a
Just OpaqueId
x
              IsOpaque
TransparentDef -> TCEnv
env TCEnv -> (TCEnv -> TCEnv) -> TCEnv
forall a b. a -> (a -> b) -> b
& (Maybe OpaqueId -> Identity (Maybe OpaqueId))
-> TCEnv -> Identity TCEnv
Lens' TCEnv (Maybe OpaqueId)
eCurrentOpaqueId ((Maybe OpaqueId -> Identity (Maybe OpaqueId))
 -> TCEnv -> Identity TCEnv)
-> Maybe OpaqueId -> TCEnv -> TCEnv
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Maybe OpaqueId
forall a. Maybe a
Nothing

instance LensIsOpaque (Closure a) where
  lensIsOpaque :: Lens' (Closure a) IsOpaque
lensIsOpaque = (TCEnv -> f TCEnv) -> Closure a -> f (Closure a)
forall a. LensTCEnv a => Lens' a TCEnv
Lens' (Closure a) TCEnv
lensTCEnv ((TCEnv -> f TCEnv) -> Closure a -> f (Closure a))
-> ((IsOpaque -> f IsOpaque) -> TCEnv -> f TCEnv)
-> (IsOpaque -> f IsOpaque)
-> Closure a
-> f (Closure a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (IsOpaque -> f IsOpaque) -> TCEnv -> f TCEnv
forall a. LensIsOpaque a => Lens' a IsOpaque
Lens' TCEnv IsOpaque
lensIsOpaque

instance LensIsOpaque MetaInfo where
  lensIsOpaque :: Lens' MetaInfo IsOpaque
lensIsOpaque = (Closure Range -> f (Closure Range)) -> MetaInfo -> f MetaInfo
forall b a. LensClosure b a => Lens' b (Closure a)
Lens' MetaInfo (Closure Range)
lensClosure ((Closure Range -> f (Closure Range)) -> MetaInfo -> f MetaInfo)
-> ((IsOpaque -> f IsOpaque) -> Closure Range -> f (Closure Range))
-> (IsOpaque -> f IsOpaque)
-> MetaInfo
-> f MetaInfo
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (IsOpaque -> f IsOpaque) -> Closure Range -> f (Closure Range)
forall a. LensIsOpaque a => Lens' a IsOpaque
Lens' (Closure Range) IsOpaque
lensIsOpaque

----------------------------------------------------------------------------------------------------
-- ** Interaction meta variables
----------------------------------------------------------------------------------------------------

-- | Interaction points are created by the scope checker who sets the range.
--   The meta variable is created by the type checker and then hooked up to the
--   interaction point.
data InteractionPoint = InteractionPoint
  { InteractionPoint -> Range
ipRange    :: Range        -- ^ The position of the interaction point.
  , InteractionPoint -> Maybe MetaId
ipMeta     :: Maybe MetaId -- ^ The meta variable, if any, holding the type etc.
  , InteractionPoint -> Bool
ipSolved   :: Bool         -- ^ Has this interaction point already been solved?
  , InteractionPoint -> IPClause
ipClause   :: IPClause
    -- ^ The clause of the interaction point (if any).
    --   Used for case splitting.
  , InteractionPoint -> IPBoundary
ipBoundary :: IPBoundary
  }
  deriving (forall x. InteractionPoint -> Rep InteractionPoint x)
-> (forall x. Rep InteractionPoint x -> InteractionPoint)
-> Generic InteractionPoint
forall x. Rep InteractionPoint x -> InteractionPoint
forall x. InteractionPoint -> Rep InteractionPoint x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. InteractionPoint -> Rep InteractionPoint x
from :: forall x. InteractionPoint -> Rep InteractionPoint x
$cto :: forall x. Rep InteractionPoint x -> InteractionPoint
to :: forall x. Rep InteractionPoint x -> InteractionPoint
Generic

instance Eq InteractionPoint where == :: InteractionPoint -> InteractionPoint -> Bool
(==) = Maybe MetaId -> Maybe MetaId -> Bool
forall a. Eq a => a -> a -> Bool
(==) (Maybe MetaId -> Maybe MetaId -> Bool)
-> (InteractionPoint -> Maybe MetaId)
-> InteractionPoint
-> InteractionPoint
-> Bool
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` InteractionPoint -> Maybe MetaId
ipMeta

instance HasTag InteractionPoint where
  type Tag InteractionPoint = MetaId
  tag :: InteractionPoint -> Maybe (Tag InteractionPoint)
tag = InteractionPoint -> Maybe (Tag InteractionPoint)
InteractionPoint -> Maybe MetaId
ipMeta

-- | Data structure managing the interaction points.
--
--   We never remove interaction points from this map, only set their
--   'ipSolved' to @True@.  (Issue #2368)
type InteractionPoints = BiMap InteractionId InteractionPoint

-- | Flag to indicate whether the meta is overapplied in the
--   constraint.  A meta is overapplied if it has more arguments than
--   the size of the telescope in its creation environment
--   (as stored in MetaInfo).
data Overapplied = Overapplied | NotOverapplied
  deriving (Overapplied -> Overapplied -> Bool
(Overapplied -> Overapplied -> Bool)
-> (Overapplied -> Overapplied -> Bool) -> Eq Overapplied
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Overapplied -> Overapplied -> Bool
== :: Overapplied -> Overapplied -> Bool
$c/= :: Overapplied -> Overapplied -> Bool
/= :: Overapplied -> Overapplied -> Bool
Eq, Int -> Overapplied -> ShowS
[Overapplied] -> ShowS
Overapplied -> String
(Int -> Overapplied -> ShowS)
-> (Overapplied -> String)
-> ([Overapplied] -> ShowS)
-> Show Overapplied
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Overapplied -> ShowS
showsPrec :: Int -> Overapplied -> ShowS
$cshow :: Overapplied -> String
show :: Overapplied -> String
$cshowList :: [Overapplied] -> ShowS
showList :: [Overapplied] -> ShowS
Show, (forall x. Overapplied -> Rep Overapplied x)
-> (forall x. Rep Overapplied x -> Overapplied)
-> Generic Overapplied
forall x. Rep Overapplied x -> Overapplied
forall x. Overapplied -> Rep Overapplied x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Overapplied -> Rep Overapplied x
from :: forall x. Overapplied -> Rep Overapplied x
$cto :: forall x. Rep Overapplied x -> Overapplied
to :: forall x. Rep Overapplied x -> Overapplied
Generic)

newtype IPBoundary' t = IPBoundary
  { forall t. IPBoundary' t -> Map (IntMap Bool) t
getBoundary :: Map (IntMap Bool) t
  }
  deriving (Int -> IPBoundary' t -> ShowS
[IPBoundary' t] -> ShowS
IPBoundary' t -> String
(Int -> IPBoundary' t -> ShowS)
-> (IPBoundary' t -> String)
-> ([IPBoundary' t] -> ShowS)
-> Show (IPBoundary' t)
forall t. Show t => Int -> IPBoundary' t -> ShowS
forall t. Show t => [IPBoundary' t] -> ShowS
forall t. Show t => IPBoundary' t -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall t. Show t => Int -> IPBoundary' t -> ShowS
showsPrec :: Int -> IPBoundary' t -> ShowS
$cshow :: forall t. Show t => IPBoundary' t -> String
show :: IPBoundary' t -> String
$cshowList :: forall t. Show t => [IPBoundary' t] -> ShowS
showList :: [IPBoundary' t] -> ShowS
Show, (forall a b. (a -> b) -> IPBoundary' a -> IPBoundary' b)
-> (forall a b. a -> IPBoundary' b -> IPBoundary' a)
-> Functor IPBoundary'
forall a b. a -> IPBoundary' b -> IPBoundary' a
forall a b. (a -> b) -> IPBoundary' a -> IPBoundary' b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall a b. (a -> b) -> IPBoundary' a -> IPBoundary' b
fmap :: forall a b. (a -> b) -> IPBoundary' a -> IPBoundary' b
$c<$ :: forall a b. a -> IPBoundary' b -> IPBoundary' a
<$ :: forall a b. a -> IPBoundary' b -> IPBoundary' a
Functor, (forall m. Monoid m => IPBoundary' m -> m)
-> (forall m a. Monoid m => (a -> m) -> IPBoundary' a -> m)
-> (forall m a. Monoid m => (a -> m) -> IPBoundary' a -> m)
-> (forall a b. (a -> b -> b) -> b -> IPBoundary' a -> b)
-> (forall a b. (a -> b -> b) -> b -> IPBoundary' a -> b)
-> (forall b a. (b -> a -> b) -> b -> IPBoundary' a -> b)
-> (forall b a. (b -> a -> b) -> b -> IPBoundary' a -> b)
-> (forall a. (a -> a -> a) -> IPBoundary' a -> a)
-> (forall a. (a -> a -> a) -> IPBoundary' a -> a)
-> (forall a. IPBoundary' a -> [a])
-> (forall a. IPBoundary' a -> Bool)
-> (forall a. IPBoundary' a -> Int)
-> (forall a. Eq a => a -> IPBoundary' a -> Bool)
-> (forall a. Ord a => IPBoundary' a -> a)
-> (forall a. Ord a => IPBoundary' a -> a)
-> (forall a. Num a => IPBoundary' a -> a)
-> (forall a. Num a => IPBoundary' a -> a)
-> Foldable IPBoundary'
forall a. Eq a => a -> IPBoundary' a -> Bool
forall a. Num a => IPBoundary' a -> a
forall a. Ord a => IPBoundary' a -> a
forall m. Monoid m => IPBoundary' m -> m
forall a. IPBoundary' a -> Bool
forall a. IPBoundary' a -> Int
forall a. IPBoundary' a -> [a]
forall a. (a -> a -> a) -> IPBoundary' a -> a
forall m a. Monoid m => (a -> m) -> IPBoundary' a -> m
forall b a. (b -> a -> b) -> b -> IPBoundary' a -> b
forall a b. (a -> b -> b) -> b -> IPBoundary' a -> b
forall (t :: * -> *).
(forall m. Monoid m => t m -> m)
-> (forall m a. Monoid m => (a -> m) -> t a -> m)
-> (forall m a. Monoid m => (a -> m) -> t a -> m)
-> (forall a b. (a -> b -> b) -> b -> t a -> b)
-> (forall a b. (a -> b -> b) -> b -> t a -> b)
-> (forall b a. (b -> a -> b) -> b -> t a -> b)
-> (forall b a. (b -> a -> b) -> b -> t a -> b)
-> (forall a. (a -> a -> a) -> t a -> a)
-> (forall a. (a -> a -> a) -> t a -> a)
-> (forall a. t a -> [a])
-> (forall a. t a -> Bool)
-> (forall a. t a -> Int)
-> (forall a. Eq a => a -> t a -> Bool)
-> (forall a. Ord a => t a -> a)
-> (forall a. Ord a => t a -> a)
-> (forall a. Num a => t a -> a)
-> (forall a. Num a => t a -> a)
-> Foldable t
$cfold :: forall m. Monoid m => IPBoundary' m -> m
fold :: forall m. Monoid m => IPBoundary' m -> m
$cfoldMap :: forall m a. Monoid m => (a -> m) -> IPBoundary' a -> m
foldMap :: forall m a. Monoid m => (a -> m) -> IPBoundary' a -> m
$cfoldMap' :: forall m a. Monoid m => (a -> m) -> IPBoundary' a -> m
foldMap' :: forall m a. Monoid m => (a -> m) -> IPBoundary' a -> m
$cfoldr :: forall a b. (a -> b -> b) -> b -> IPBoundary' a -> b
foldr :: forall a b. (a -> b -> b) -> b -> IPBoundary' a -> b
$cfoldr' :: forall a b. (a -> b -> b) -> b -> IPBoundary' a -> b
foldr' :: forall a b. (a -> b -> b) -> b -> IPBoundary' a -> b
$cfoldl :: forall b a. (b -> a -> b) -> b -> IPBoundary' a -> b
foldl :: forall b a. (b -> a -> b) -> b -> IPBoundary' a -> b
$cfoldl' :: forall b a. (b -> a -> b) -> b -> IPBoundary' a -> b
foldl' :: forall b a. (b -> a -> b) -> b -> IPBoundary' a -> b
$cfoldr1 :: forall a. (a -> a -> a) -> IPBoundary' a -> a
foldr1 :: forall a. (a -> a -> a) -> IPBoundary' a -> a
$cfoldl1 :: forall a. (a -> a -> a) -> IPBoundary' a -> a
foldl1 :: forall a. (a -> a -> a) -> IPBoundary' a -> a
$ctoList :: forall a. IPBoundary' a -> [a]
toList :: forall a. IPBoundary' a -> [a]
$cnull :: forall a. IPBoundary' a -> Bool
null :: forall a. IPBoundary' a -> Bool
$clength :: forall a. IPBoundary' a -> Int
length :: forall a. IPBoundary' a -> Int
$celem :: forall a. Eq a => a -> IPBoundary' a -> Bool
elem :: forall a. Eq a => a -> IPBoundary' a -> Bool
$cmaximum :: forall a. Ord a => IPBoundary' a -> a
maximum :: forall a. Ord a => IPBoundary' a -> a
$cminimum :: forall a. Ord a => IPBoundary' a -> a
minimum :: forall a. Ord a => IPBoundary' a -> a
$csum :: forall a. Num a => IPBoundary' a -> a
sum :: forall a. Num a => IPBoundary' a -> a
$cproduct :: forall a. Num a => IPBoundary' a -> a
product :: forall a. Num a => IPBoundary' a -> a
Foldable, Functor IPBoundary'
Foldable IPBoundary'
(Functor IPBoundary', Foldable IPBoundary') =>
(forall (f :: * -> *) a b.
 Applicative f =>
 (a -> f b) -> IPBoundary' a -> f (IPBoundary' b))
-> (forall (f :: * -> *) a.
    Applicative f =>
    IPBoundary' (f a) -> f (IPBoundary' a))
-> (forall (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> IPBoundary' a -> m (IPBoundary' b))
-> (forall (m :: * -> *) a.
    Monad m =>
    IPBoundary' (m a) -> m (IPBoundary' a))
-> Traversable IPBoundary'
forall (t :: * -> *).
(Functor t, Foldable t) =>
(forall (f :: * -> *) a b.
 Applicative f =>
 (a -> f b) -> t a -> f (t b))
-> (forall (f :: * -> *) a. Applicative f => t (f a) -> f (t a))
-> (forall (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> t a -> m (t b))
-> (forall (m :: * -> *) a. Monad m => t (m a) -> m (t a))
-> Traversable t
forall (m :: * -> *) a.
Monad m =>
IPBoundary' (m a) -> m (IPBoundary' a)
forall (f :: * -> *) a.
Applicative f =>
IPBoundary' (f a) -> f (IPBoundary' a)
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> IPBoundary' a -> m (IPBoundary' b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> IPBoundary' a -> f (IPBoundary' b)
$ctraverse :: forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> IPBoundary' a -> f (IPBoundary' b)
traverse :: forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> IPBoundary' a -> f (IPBoundary' b)
$csequenceA :: forall (f :: * -> *) a.
Applicative f =>
IPBoundary' (f a) -> f (IPBoundary' a)
sequenceA :: forall (f :: * -> *) a.
Applicative f =>
IPBoundary' (f a) -> f (IPBoundary' a)
$cmapM :: forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> IPBoundary' a -> m (IPBoundary' b)
mapM :: forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> IPBoundary' a -> m (IPBoundary' b)
$csequence :: forall (m :: * -> *) a.
Monad m =>
IPBoundary' (m a) -> m (IPBoundary' a)
sequence :: forall (m :: * -> *) a.
Monad m =>
IPBoundary' (m a) -> m (IPBoundary' a)
Traversable, (forall x. IPBoundary' t -> Rep (IPBoundary' t) x)
-> (forall x. Rep (IPBoundary' t) x -> IPBoundary' t)
-> Generic (IPBoundary' t)
forall x. Rep (IPBoundary' t) x -> IPBoundary' t
forall x. IPBoundary' t -> Rep (IPBoundary' t) x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
forall t x. Rep (IPBoundary' t) x -> IPBoundary' t
forall t x. IPBoundary' t -> Rep (IPBoundary' t) x
$cfrom :: forall t x. IPBoundary' t -> Rep (IPBoundary' t) x
from :: forall x. IPBoundary' t -> Rep (IPBoundary' t) x
$cto :: forall t x. Rep (IPBoundary' t) x -> IPBoundary' t
to :: forall x. Rep (IPBoundary' t) x -> IPBoundary' t
Generic)

type IPBoundary = IPBoundary' Term

-- | Which clause is an interaction point located in?
data IPClause = IPClause
  { IPClause -> QName
ipcQName    :: QName              -- ^ The name of the function.
  , IPClause -> Int
ipcClauseNo :: ClauseNumber       -- ^ The number of the clause of this function.
  , IPClause -> Type
ipcType     :: Type               -- ^ The type of the function
  , IPClause -> Maybe Substitution
ipcWithSub  :: Maybe Substitution -- ^ Module parameter substitution
  , IPClause -> SpineClause
ipcClause   :: A.SpineClause      -- ^ The original AST clause.
  , IPClause -> Closure ()
ipcClosure  :: Closure ()         -- ^ Environment for rechecking the clause.
  }
  | IPNoClause -- ^ The interaction point is not in the rhs of a clause.
  deriving ((forall x. IPClause -> Rep IPClause x)
-> (forall x. Rep IPClause x -> IPClause) -> Generic IPClause
forall x. Rep IPClause x -> IPClause
forall x. IPClause -> Rep IPClause x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. IPClause -> Rep IPClause x
from :: forall x. IPClause -> Rep IPClause x
$cto :: forall x. Rep IPClause x -> IPClause
to :: forall x. Rep IPClause x -> IPClause
Generic)

instance Eq IPClause where
  IPClause
IPNoClause           == :: IPClause -> IPClause -> Bool
== IPClause
IPNoClause             = Bool
True
  IPClause QName
x Int
i Type
_ Maybe Substitution
_ SpineClause
_ Closure ()
_ == IPClause QName
x' Int
i' Type
_ Maybe Substitution
_ SpineClause
_ Closure ()
_ = QName
x QName -> QName -> Bool
forall a. Eq a => a -> a -> Bool
== QName
x' Bool -> Bool -> Bool
&& Int
i Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
i'
  IPClause
_                    == IPClause
_                      = Bool
False

----------------------------------------------------------------------------------------------------
-- ** Signature
----------------------------------------------------------------------------------------------------

data Signature = Sig
      { Signature -> Sections
_sigSections     :: !Sections
      , Signature -> Definitions
_sigDefinitions  :: !Definitions
      , Signature -> InstanceTable
_sigInstances    :: !InstanceTable
      }
  deriving (Int -> Signature -> ShowS
[Signature] -> ShowS
Signature -> String
(Int -> Signature -> ShowS)
-> (Signature -> String)
-> ([Signature] -> ShowS)
-> Show Signature
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Signature -> ShowS
showsPrec :: Int -> Signature -> ShowS
$cshow :: Signature -> String
show :: Signature -> String
$cshowList :: [Signature] -> ShowS
showList :: [Signature] -> ShowS
Show, (forall x. Signature -> Rep Signature x)
-> (forall x. Rep Signature x -> Signature) -> Generic Signature
forall x. Rep Signature x -> Signature
forall x. Signature -> Rep Signature x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Signature -> Rep Signature x
from :: forall x. Signature -> Rep Signature x
$cto :: forall x. Rep Signature x -> Signature
to :: forall x. Rep Signature x -> Signature
Generic)

instance Null Signature where
  empty :: Signature
empty = Sections -> Definitions -> InstanceTable -> Signature
Sig Sections
forall a. Null a => a
empty Definitions
forall a. Null a => a
empty InstanceTable
forall a. Null a => a
empty
  null :: Signature -> Bool
null (Sig Sections
a Definitions
b InstanceTable
c) = Sections -> Bool
forall a. Null a => a -> Bool
null Sections
a Bool -> Bool -> Bool
&& Definitions -> Bool
forall a. Null a => a -> Bool
null Definitions
b Bool -> Bool -> Bool
&& InstanceTable -> Bool
forall a. Null a => a -> Bool
null InstanceTable
c

sigSections :: Lens' Signature Sections
sigSections :: Lens' Signature Sections
sigSections Sections -> f Sections
f Signature
s =
  Sections -> f Sections
f (Signature -> Sections
_sigSections Signature
s) f Sections -> (Sections -> Signature) -> f Signature
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&>
  \Sections
x -> Signature
s {_sigSections = x}

sigDefinitions :: Lens' Signature Definitions
sigDefinitions :: Lens' Signature Definitions
sigDefinitions Definitions -> f Definitions
f Signature
s =
  Definitions -> f Definitions
f (Signature -> Definitions
_sigDefinitions Signature
s) f Definitions -> (Definitions -> Signature) -> f Signature
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&>
  \Definitions
x -> Signature
s {_sigDefinitions = x}

sigInstances :: Lens' Signature InstanceTable
sigInstances :: Lens' Signature InstanceTable
sigInstances InstanceTable -> f InstanceTable
f Signature
s = InstanceTable -> f InstanceTable
f (Signature -> InstanceTable
_sigInstances Signature
s) f InstanceTable -> (InstanceTable -> Signature) -> f Signature
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \InstanceTable
x -> Signature
s {_sigInstances = x}

type Sections    = Map ModuleName Section
type Definitions = HashMap QName Definition
type DisplayForms = HashMap QName (List1 LocalDisplayForm)

{-# SPECIALIZE HMap.insert :: QName -> v -> HashMap QName v -> HashMap QName v #-}
{-# SPECIALIZE HMap.lookup :: QName -> HashMap QName v -> Maybe v #-}
{-# SPECIALIZE HMap.adjust :: (v -> v) -> QName -> HashMap QName v -> HashMap QName v #-}

type instance Index Signature = QName
type instance IxValue Signature = Definition
instance Ixed Signature where
  ix :: Index Signature -> Traversal' Signature (IxValue Signature)
ix Index Signature
k = Index Signature -> Lens' Signature (Maybe (IxValue Signature))
forall m. At m => Index m -> Lens' m (Maybe (IxValue m))
at Index Signature
k ((Maybe Definition -> f (Maybe Definition))
 -> Signature -> f Signature)
-> ((Definition -> f Definition)
    -> Maybe Definition -> f (Maybe Definition))
-> (Definition -> f Definition)
-> Signature
-> f Signature
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Definition -> f Definition)
-> Maybe Definition -> f (Maybe Definition)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Maybe a -> f (Maybe b)
traverse
  {-# INLINE ix #-}

instance At Signature where
  -- The Control.Lens.At impl for HashMap is lazy.
  -- Also, HMap.alterF (both versions) have crazy RULES for turning into
  -- the other combinators instead of the naïve implementation from
  -- lens.
  at :: Index Signature -> Lens' Signature (Maybe (IxValue Signature))
at Index Signature
k = (Definitions -> f Definitions) -> Signature -> f Signature
Lens' Signature Definitions
sigDefinitions ((Definitions -> f Definitions) -> Signature -> f Signature)
-> ((Maybe Definition -> f (Maybe Definition))
    -> Definitions -> f Definitions)
-> (Maybe Definition -> f (Maybe Definition))
-> Signature
-> f Signature
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Maybe Definition -> f (Maybe Definition))
 -> QName -> Definitions -> f Definitions)
-> QName
-> (Maybe Definition -> f (Maybe Definition))
-> Definitions
-> f Definitions
forall a b c. (a -> b -> c) -> b -> a -> c
flip (Maybe Definition -> f (Maybe Definition))
-> QName -> Definitions -> f Definitions
forall (f :: * -> *) k v.
(Functor f, Eq k, Hashable k) =>
(Maybe v -> f (Maybe v)) -> k -> HashMap k v -> f (HashMap k v)
HMap.alterF Index Signature
QName
k
  {-# INLINE at #-}

newtype Section = Section { Section -> Telescope
_secTelescope :: Telescope }
  deriving (Int -> Section -> ShowS
[Section] -> ShowS
Section -> String
(Int -> Section -> ShowS)
-> (Section -> String) -> ([Section] -> ShowS) -> Show Section
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Section -> ShowS
showsPrec :: Int -> Section -> ShowS
$cshow :: Section -> String
show :: Section -> String
$cshowList :: [Section] -> ShowS
showList :: [Section] -> ShowS
Show, Section -> ()
(Section -> ()) -> NFData Section
forall a. (a -> ()) -> NFData a
$crnf :: Section -> ()
rnf :: Section -> ()
NFData)

instance Pretty Section where
  pretty :: Section -> Doc
pretty = Telescope -> Doc
forall a. Pretty a => a -> Doc
pretty (Telescope -> Doc) -> (Section -> Telescope) -> Section -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Section -> Telescope
_secTelescope

secTelescope :: Lens' Section Telescope
secTelescope :: Lens' Section Telescope
secTelescope Telescope -> f Telescope
f Section
s =
  Telescope -> f Telescope
f (Section -> Telescope
_secTelescope Section
s) f Telescope -> (Telescope -> Section) -> f Section
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&>
  \Telescope
x -> Section
s {_secTelescope = x}

emptySignature :: Signature
emptySignature :: Signature
emptySignature = Sections -> Definitions -> InstanceTable -> Signature
Sig Sections
forall k a. Map k a
Map.empty Definitions
forall k v. HashMap k v
HMap.empty InstanceTable
forall a. Monoid a => a
mempty

-- | A @DisplayForm@ is in essence a rewrite rule @q ts --> dt@ for a defined symbol (could be a
--   constructor as well) @q@. The right hand side is a 'DisplayTerm' which is used to 'reify' to a
--   more readable 'Abstract.Syntax'.
--
--   The patterns @ts@ are just terms, but the first @dfPatternVars@ variables are pattern variables
--   that matches any term.
data DisplayForm = Display
  { DisplayForm -> Int
dfPatternVars :: Nat
    -- ^ Number @n@ of pattern variables in 'dfPats'.
  , DisplayForm -> [Elim]
dfPats :: Elims
    -- ^ Left hand side patterns, the @n@ first free variables are pattern variables,
    --   any variables above @n@ are fixed and only match that particular variable. This
    --   happens when you have display forms inside parameterised modules that match on the module
    --   parameters. The 'ArgInfo' is ignored in these patterns.
  , DisplayForm -> DisplayTerm
dfRHS :: DisplayTerm
    -- ^ Right hand side.
  }
  deriving (Int -> DisplayForm -> ShowS
[DisplayForm] -> ShowS
DisplayForm -> String
(Int -> DisplayForm -> ShowS)
-> (DisplayForm -> String)
-> ([DisplayForm] -> ShowS)
-> Show DisplayForm
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DisplayForm -> ShowS
showsPrec :: Int -> DisplayForm -> ShowS
$cshow :: DisplayForm -> String
show :: DisplayForm -> String
$cshowList :: [DisplayForm] -> ShowS
showList :: [DisplayForm] -> ShowS
Show, (forall x. DisplayForm -> Rep DisplayForm x)
-> (forall x. Rep DisplayForm x -> DisplayForm)
-> Generic DisplayForm
forall x. Rep DisplayForm x -> DisplayForm
forall x. DisplayForm -> Rep DisplayForm x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. DisplayForm -> Rep DisplayForm x
from :: forall x. DisplayForm -> Rep DisplayForm x
$cto :: forall x. Rep DisplayForm x -> DisplayForm
to :: forall x. Rep DisplayForm x -> DisplayForm
Generic)

type LocalDisplayForm = Open DisplayForm

-- | A structured presentation of a 'Term' for reification into
--   'Abstract.Syntax'.
data DisplayTerm
  = DWithApp DisplayTerm (List1 DisplayTerm) Elims
    -- ^ @(f vs | ws) es@.
    --   The first 'DisplayTerm' is the parent function @f@ with its args @vs@.
    --   The list of 'DisplayTerm's are the with expressions @ws@.
    --   The 'Elims' are additional arguments @es@
    --   (possible in case the with-application is of function type)
    --   or projections (if it is of record type).
  | DCon ConHead ConInfo [Arg DisplayTerm]
    -- ^ @c vs@.
  | DDef QName [Elim' DisplayTerm]
    -- ^ @d vs@.
  | DDot' Term Elims
    -- ^ @.(v es)@.  See 'DTerm''.
  | DTerm' Term Elims
    -- ^ @v es@.
    --   This is a frozen elimination that is not always safe to run,
    --   because display forms may be ill-typed.
    --   (See issue #6476.)
  deriving (Int -> DisplayTerm -> ShowS
[DisplayTerm] -> ShowS
DisplayTerm -> String
(Int -> DisplayTerm -> ShowS)
-> (DisplayTerm -> String)
-> ([DisplayTerm] -> ShowS)
-> Show DisplayTerm
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DisplayTerm -> ShowS
showsPrec :: Int -> DisplayTerm -> ShowS
$cshow :: DisplayTerm -> String
show :: DisplayTerm -> String
$cshowList :: [DisplayTerm] -> ShowS
showList :: [DisplayTerm] -> ShowS
Show, (forall x. DisplayTerm -> Rep DisplayTerm x)
-> (forall x. Rep DisplayTerm x -> DisplayTerm)
-> Generic DisplayTerm
forall x. Rep DisplayTerm x -> DisplayTerm
forall x. DisplayTerm -> Rep DisplayTerm x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. DisplayTerm -> Rep DisplayTerm x
from :: forall x. DisplayTerm -> Rep DisplayTerm x
$cto :: forall x. Rep DisplayTerm x -> DisplayTerm
to :: forall x. Rep DisplayTerm x -> DisplayTerm
Generic)

pattern DDot :: Term -> DisplayTerm
pattern $bDDot :: Term -> DisplayTerm
$mDDot :: forall {r}. DisplayTerm -> (Term -> r) -> ((# #) -> r) -> r
DDot v = DDot' v []

pattern DTerm :: Term -> DisplayTerm
pattern $bDTerm :: Term -> DisplayTerm
$mDTerm :: forall {r}. DisplayTerm -> (Term -> r) -> ((# #) -> r) -> r
DTerm v = DTerm' v []

instance Pretty DisplayTerm where
  prettyPrec :: Int -> DisplayTerm -> Doc
prettyPrec Int
p DisplayTerm
v =
    case DisplayTerm
v of
      DTerm Term
v           -> Int -> Term -> Doc
forall a. Pretty a => Int -> a -> Doc
prettyPrec Int
p Term
v
      DTerm' Term
v [Elim]
es       -> Int -> Term -> Doc
forall a. Pretty a => Int -> a -> Doc
prettyPrec Int
9 Term
v Doc -> [Elim] -> Doc
forall el. Pretty el => Doc -> [el] -> Doc
`pApp` [Elim]
es
      DDot Term
v            -> Doc
"." Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Int -> Term -> Doc
forall a. Pretty a => Int -> a -> Doc
prettyPrec Int
10 Term
v
      DDot' Term
v [Elim]
es        -> Doc
"." Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc -> Doc
parens (Int -> Term -> Doc
forall a. Pretty a => Int -> a -> Doc
prettyPrec Int
9 Term
v Doc -> [Elim] -> Doc
forall el. Pretty el => Doc -> [el] -> Doc
`pAp` [Elim]
es)
      DDef QName
f [Elim' DisplayTerm]
es        -> QName -> Doc
forall a. Pretty a => a -> Doc
pretty QName
f Doc -> [Elim' DisplayTerm] -> Doc
forall el. Pretty el => Doc -> [el] -> Doc
`pApp` [Elim' DisplayTerm]
es
      DCon ConHead
c ConInfo
_ [Arg DisplayTerm]
vs      -> QName -> Doc
forall a. Pretty a => a -> Doc
pretty (ConHead -> QName
conName ConHead
c) Doc -> [Elim' DisplayTerm] -> Doc
forall el. Pretty el => Doc -> [el] -> Doc
`pApp` (Arg DisplayTerm -> Elim' DisplayTerm)
-> [Arg DisplayTerm] -> [Elim' DisplayTerm]
forall a b. (a -> b) -> [a] -> [b]
map Arg DisplayTerm -> Elim' DisplayTerm
forall a. Arg a -> Elim' a
Apply [Arg DisplayTerm]
vs
      DWithApp DisplayTerm
h List1 DisplayTerm
ws [Elim]
es ->
        Bool -> Doc -> Doc
mparens (Int
p Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0)
          ([Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
sep [ DisplayTerm -> Doc
forall a. Pretty a => a -> Doc
pretty DisplayTerm
h
               , Int -> Doc -> Doc
forall a. Int -> Doc a -> Doc a
nest Int
2 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ NonEmpty Doc -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
fsep (NonEmpty Doc -> Doc) -> NonEmpty Doc -> Doc
forall a b. (a -> b) -> a -> b
$ (DisplayTerm -> Doc) -> List1 DisplayTerm -> NonEmpty Doc
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\ DisplayTerm
w -> Doc
"|" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> DisplayTerm -> Doc
forall a. Pretty a => a -> Doc
pretty DisplayTerm
w) List1 DisplayTerm
ws
               ])
        Doc -> [Elim] -> Doc
forall el. Pretty el => Doc -> [el] -> Doc
`pApp` [Elim]
es
    where
      pApp :: Pretty el => Doc -> [el] -> Doc
      pApp :: forall el. Pretty el => Doc -> [el] -> Doc
pApp Doc
d [el]
els = Bool -> Doc -> Doc
mparens (Bool -> Bool
not ([el] -> Bool
forall a. Null a => a -> Bool
null [el]
els) Bool -> Bool -> Bool
&& Int
p Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
9) (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ Doc -> [el] -> Doc
forall el. Pretty el => Doc -> [el] -> Doc
pAp Doc
d [el]
els
      pAp :: Pretty el => Doc -> [el] -> Doc
      pAp :: forall el. Pretty el => Doc -> [el] -> Doc
pAp Doc
d [el]
els = [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
sep [Doc
d, Int -> Doc -> Doc
forall a. Int -> Doc a -> Doc a
nest Int
2 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
fsep ((el -> Doc) -> [el] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> el -> Doc
forall a. Pretty a => Int -> a -> Doc
prettyPrec Int
10) [el]
els)]

instance Pretty DisplayForm where
  prettyPrec :: Int -> DisplayForm -> Doc
prettyPrec Int
p (Display Int
fv [Elim]
lhs DisplayTerm
rhs) = Bool -> Doc -> Doc
mparens (Int
p Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
9) (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$
    Doc
"Display" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
fsep [ Int -> Doc
forall a. Show a => a -> Doc
pshow Int
fv, Int -> [Elim] -> Doc
forall a. Pretty a => Int -> a -> Doc
prettyPrec Int
10 [Elim]
lhs, Int -> DisplayTerm -> Doc
forall a. Pretty a => Int -> a -> Doc
prettyPrec Int
10 DisplayTerm
rhs ]

-- | By default, we have no display form.
defaultDisplayForm :: QName -> [LocalDisplayForm]
defaultDisplayForm :: QName -> [LocalDisplayForm]
defaultDisplayForm QName
c = []

-- | Information about an @instance@ definition.
data InstanceInfo = InstanceInfo
  { InstanceInfo -> QName
instanceClass   :: QName       -- ^ Name of the "class" this is an instance for
  , InstanceInfo -> OverlapMode
instanceOverlap :: OverlapMode -- ^ Does this instance have a specified overlap mode?
  }
    deriving (Int -> InstanceInfo -> ShowS
[InstanceInfo] -> ShowS
InstanceInfo -> String
(Int -> InstanceInfo -> ShowS)
-> (InstanceInfo -> String)
-> ([InstanceInfo] -> ShowS)
-> Show InstanceInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> InstanceInfo -> ShowS
showsPrec :: Int -> InstanceInfo -> ShowS
$cshow :: InstanceInfo -> String
show :: InstanceInfo -> String
$cshowList :: [InstanceInfo] -> ShowS
showList :: [InstanceInfo] -> ShowS
Show, (forall x. InstanceInfo -> Rep InstanceInfo x)
-> (forall x. Rep InstanceInfo x -> InstanceInfo)
-> Generic InstanceInfo
forall x. Rep InstanceInfo x -> InstanceInfo
forall x. InstanceInfo -> Rep InstanceInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. InstanceInfo -> Rep InstanceInfo x
from :: forall x. InstanceInfo -> Rep InstanceInfo x
$cto :: forall x. Rep InstanceInfo x -> InstanceInfo
to :: forall x. Rep InstanceInfo x -> InstanceInfo
Generic)

data Definition = Defn
  { Definition -> ArgInfo
defArgInfo        :: ArgInfo -- ^ Used for generalisable variables and record fields (and possibly other things).
  , Definition -> QName
defName           :: QName   -- ^ The canonical name, used e.g. in compilation.
  , Definition -> Type
defType           :: Type    -- ^ Type of the lifted definition.
  , Definition -> [Polarity]
defPolarity       :: [Polarity]
    -- ^ Variance information on arguments of the definition.
    --
    -- The main use of 'defPolarity' is to guide subtyping during
    -- conversion of elimination spines in 'Mikan.TypeChecking.Conversion.compareElims'.
    -- In particular, when we are faced with subtyping problems like
    --
    -- > f x <= f y
    --
    -- we need to know the variance of the argument to @f@ to determine
    -- if we should check @x <= y@, @y <= x@, or @x = y@. We can also
    -- shortcut conversion if we notice that an argument is 'Nonvariant'.
    --
    -- Polarity information is derived from 'defArgOccurrences' in
    -- "Mikan.TypeChecking.Polarity"; see there for more details on the
    -- polarity inference algorithm.
    --
    -- __Warning__: This does not include polarity info for dropped parameters to
    -- projection(-like) functions and constructors.
  , Definition -> [Occurrence]
defArgOccurrences :: [Occurrence]
    -- ^ Positivity information on arguments of the definition.
    --
    -- We use 'defArgOccurrences' in two ways:
    --
    -- 1. Positivity checking inductive types.
    -- 2. Computing 'defPolarity'.
    --
    -- These both happen during of 'Mikan.TypeChecking.Decls.checkPositivity_'.
    -- For more defails on the occurrence analysis algorithm, see "Mikan.TypeChecking.Positivity.OccurrenceAnalysis".
    --
    -- __Warning__: Does not include info for dropped parameters to
    -- projection(-like) functions and constructors.
    --
    -- == __Performance__
    --
    --   Sometimes Agda looks up 'Occurrence's in these lists based on
    --   their position, so one might consider replacing the list
    --   with, say, an 'IntMap'. However, these lists tend
    --   to be short, in which case 'IntMap's could be slower than
    --   lists.
  , Definition -> [Maybe Name]
defGeneralizedParams :: [Maybe Name]
    -- ^ Gives the name of the (bound variable) parameter for named generalized
    --   parameters. This is needed to bring it into scope when type checking
    --   the data/record definition corresponding to a type with generalized
    --   parameters.
  , Definition -> [LocalDisplayForm]
defDisplay        :: [LocalDisplayForm]
  , Definition -> MutualId
defMutual         :: MutualId
  , Definition -> CompiledRepresentation
defCompiledRep    :: CompiledRepresentation
  , Definition -> Maybe InstanceInfo
defInstance       :: Maybe InstanceInfo
    -- ^ @Just q@ when this definition is an instance.
  , Definition -> Maybe QName
defCopy           :: Maybe QName
    -- ^ Has this function been created by a module instantiation?
    --
    -- Stores the name of the original definition if so.
  , Definition -> Bool
defNoCompilation  :: Bool
    -- ^ should compilers skip this? Used for e.g. cubical's comp
  , Definition -> Bool
defInjective      :: Bool
    -- ^ Should the def be treated as injective by the pattern matching unifier?
  , Definition -> Bool
defCopatternLHS   :: Bool
    -- ^ Is this a function defined by copatterns?
  , Definition -> Blocked_
defBlocked        :: Blocked_
    -- ^ What blocking tag to use when we cannot reduce this def?
    --   Used when checking a function definition is blocked on a meta
    --   in the type.
  , Definition -> Bool
defMightContainMetas :: !Bool
    -- ^ If this is 'False', the definition doesn't contain metavariables. If 'True', the definition
    -- may or may not contain metavariables. This field is updated by 'TypeChecking.DeadCode', and
    -- it's used to avoid unnecessary 'instantiateFull' on the definition before serialization.
  , Definition -> Defn
theDef               :: Defn
  }
    deriving (Int -> Definition -> ShowS
[Definition] -> ShowS
Definition -> String
(Int -> Definition -> ShowS)
-> (Definition -> String)
-> ([Definition] -> ShowS)
-> Show Definition
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Definition -> ShowS
showsPrec :: Int -> Definition -> ShowS
$cshow :: Definition -> String
show :: Definition -> String
$cshowList :: [Definition] -> ShowS
showList :: [Definition] -> ShowS
Show, (forall x. Definition -> Rep Definition x)
-> (forall x. Rep Definition x -> Definition) -> Generic Definition
forall x. Rep Definition x -> Definition
forall x. Definition -> Rep Definition x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Definition -> Rep Definition x
from :: forall x. Definition -> Rep Definition x
$cto :: forall x. Rep Definition x -> Definition
to :: forall x. Rep Definition x -> Definition
Generic)

instance LensArgInfo Definition where
  getArgInfo :: Definition -> ArgInfo
getArgInfo = Definition -> ArgInfo
defArgInfo
  mapArgInfo :: (ArgInfo -> ArgInfo) -> Definition -> Definition
mapArgInfo ArgInfo -> ArgInfo
f Definition
def = Definition
def { defArgInfo = f $ defArgInfo def }

newtype NumGeneralizableArgs = SomeGeneralizableArgs Int
  deriving Int -> NumGeneralizableArgs -> ShowS
[NumGeneralizableArgs] -> ShowS
NumGeneralizableArgs -> String
(Int -> NumGeneralizableArgs -> ShowS)
-> (NumGeneralizableArgs -> String)
-> ([NumGeneralizableArgs] -> ShowS)
-> Show NumGeneralizableArgs
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> NumGeneralizableArgs -> ShowS
showsPrec :: Int -> NumGeneralizableArgs -> ShowS
$cshow :: NumGeneralizableArgs -> String
show :: NumGeneralizableArgs -> String
$cshowList :: [NumGeneralizableArgs] -> ShowS
showList :: [NumGeneralizableArgs] -> ShowS
Show

lensTheDef :: Lens' Definition Defn
lensTheDef :: Lens' Definition Defn
lensTheDef Defn -> f Defn
f Definition
d = Defn -> f Defn
f (Definition -> Defn
theDef Definition
d) f Defn -> (Defn -> Definition) -> f Definition
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Defn
df -> Definition
d { theDef = df }

-- | Create a definition with sensible defaults.
defaultDefn ::
  ArgInfo -> QName -> Type -> Defn -> Definition
defaultDefn :: ArgInfo -> QName -> Type -> Defn -> Definition
defaultDefn ArgInfo
info QName
x Type
t Defn
def = Defn
  { defArgInfo :: ArgInfo
defArgInfo           = ArgInfo
info
  , defName :: QName
defName              = QName
x
  , defType :: Type
defType              = Type
t
  , defPolarity :: [Polarity]
defPolarity          = []
  , defArgOccurrences :: [Occurrence]
defArgOccurrences    = []
  , defGeneralizedParams :: [Maybe Name]
defGeneralizedParams = []
  , defDisplay :: [LocalDisplayForm]
defDisplay           = QName -> [LocalDisplayForm]
defaultDisplayForm QName
x
  , defMutual :: MutualId
defMutual            = MutualId
0
  , defCompiledRep :: CompiledRepresentation
defCompiledRep       = CompiledRepresentation
noCompiledRep
  , defInstance :: Maybe InstanceInfo
defInstance          = Maybe InstanceInfo
forall a. Maybe a
Nothing
  , defCopy :: Maybe QName
defCopy              = Maybe QName
forall a. Maybe a
Nothing
  , defNoCompilation :: Bool
defNoCompilation     = Bool
False
  , defInjective :: Bool
defInjective         = Bool
False
  , defCopatternLHS :: Bool
defCopatternLHS      = Bool
False
  , defBlocked :: Blocked_
defBlocked           = NotBlocked' Term -> () -> Blocked_
forall t a. NotBlocked' t -> a -> Blocked' t a
NotBlocked NotBlocked' Term
forall t. NotBlocked' t
ReallyNotBlocked ()
  , defMightContainMetas :: Bool
defMightContainMetas = Bool
True
  , theDef :: Defn
theDef               = Defn
def
  }

instance Pretty Polarity where
  pretty :: Polarity -> Doc
pretty = String -> Doc
forall a. String -> Doc a
text (String -> Doc) -> (Polarity -> String) -> Polarity -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. \case
    Polarity
Covariant     -> String
"+"
    Polarity
Contravariant -> String
"-"
    Polarity
Invariant     -> String
"*"
    Polarity
Nonvariant    -> String
"_"

-- | Information about whether an argument is forced by the type of a function.
data IsForced
  = Forced
  | NotForced
  deriving (Int -> IsForced -> ShowS
[IsForced] -> ShowS
IsForced -> String
(Int -> IsForced -> ShowS)
-> (IsForced -> String) -> ([IsForced] -> ShowS) -> Show IsForced
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> IsForced -> ShowS
showsPrec :: Int -> IsForced -> ShowS
$cshow :: IsForced -> String
show :: IsForced -> String
$cshowList :: [IsForced] -> ShowS
showList :: [IsForced] -> ShowS
Show, IsForced -> IsForced -> Bool
(IsForced -> IsForced -> Bool)
-> (IsForced -> IsForced -> Bool) -> Eq IsForced
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: IsForced -> IsForced -> Bool
== :: IsForced -> IsForced -> Bool
$c/= :: IsForced -> IsForced -> Bool
/= :: IsForced -> IsForced -> Bool
Eq, (forall x. IsForced -> Rep IsForced x)
-> (forall x. Rep IsForced x -> IsForced) -> Generic IsForced
forall x. Rep IsForced x -> IsForced
forall x. IsForced -> Rep IsForced x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. IsForced -> Rep IsForced x
from :: forall x. IsForced -> Rep IsForced x
$cto :: forall x. Rep IsForced x -> IsForced
to :: forall x. Rep IsForced x -> IsForced
Generic)

-- | The backends are responsible for parsing their own pragmas.
data CompilerPragma = CompilerPragma Range String
  deriving (Int -> CompilerPragma -> ShowS
[CompilerPragma] -> ShowS
CompilerPragma -> String
(Int -> CompilerPragma -> ShowS)
-> (CompilerPragma -> String)
-> ([CompilerPragma] -> ShowS)
-> Show CompilerPragma
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CompilerPragma -> ShowS
showsPrec :: Int -> CompilerPragma -> ShowS
$cshow :: CompilerPragma -> String
show :: CompilerPragma -> String
$cshowList :: [CompilerPragma] -> ShowS
showList :: [CompilerPragma] -> ShowS
Show, CompilerPragma -> CompilerPragma -> Bool
(CompilerPragma -> CompilerPragma -> Bool)
-> (CompilerPragma -> CompilerPragma -> Bool) -> Eq CompilerPragma
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CompilerPragma -> CompilerPragma -> Bool
== :: CompilerPragma -> CompilerPragma -> Bool
$c/= :: CompilerPragma -> CompilerPragma -> Bool
/= :: CompilerPragma -> CompilerPragma -> Bool
Eq, (forall x. CompilerPragma -> Rep CompilerPragma x)
-> (forall x. Rep CompilerPragma x -> CompilerPragma)
-> Generic CompilerPragma
forall x. Rep CompilerPragma x -> CompilerPragma
forall x. CompilerPragma -> Rep CompilerPragma x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. CompilerPragma -> Rep CompilerPragma x
from :: forall x. CompilerPragma -> Rep CompilerPragma x
$cto :: forall x. Rep CompilerPragma x -> CompilerPragma
to :: forall x. Rep CompilerPragma x -> CompilerPragma
Generic)

instance HasRange CompilerPragma where
  getRange :: CompilerPragma -> Range
getRange (CompilerPragma Range
r String
_) = Range
r

type CompiledRepresentation = Map BackendName [CompilerPragma]

noCompiledRep :: CompiledRepresentation
noCompiledRep :: CompiledRepresentation
noCompiledRep = CompiledRepresentation
forall k a. Map k a
Map.empty

-- A face represented as a list of equality constraints.
-- (r,False) ↦ (r = i0)
-- (r,True ) ↦ (r = i1)
type Face = [(Term,Bool)]

-- | An alternative representation of partial elements in a telescope:
--   Γ ⊢ λ Δ. [φ₁ u₁, ... , φₙ uₙ] : Δ → PartialP (∨_ᵢ φᵢ) T
--   see cubicaltt paper (however we do not store the type T).
data System = System
  { System -> Telescope
systemTel :: Telescope
    -- ^ the telescope Δ, binding vars for the clauses, Γ ⊢ Δ
  , System -> [(Face, Term)]
systemClauses :: [(Face,Term)]
    -- ^ a system [φ₁ u₁, ... , φₙ uₙ] where Γ, Δ ⊢ φᵢ and Γ, Δ, φᵢ ⊢ uᵢ
  } deriving (Int -> System -> ShowS
[System] -> ShowS
System -> String
(Int -> System -> ShowS)
-> (System -> String) -> ([System] -> ShowS) -> Show System
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> System -> ShowS
showsPrec :: Int -> System -> ShowS
$cshow :: System -> String
show :: System -> String
$cshowList :: [System] -> ShowS
showList :: [System] -> ShowS
Show, (forall x. System -> Rep System x)
-> (forall x. Rep System x -> System) -> Generic System
forall x. Rep System x -> System
forall x. System -> Rep System x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. System -> Rep System x
from :: forall x. System -> Rep System x
$cto :: forall x. Rep System x -> System
to :: forall x. Rep System x -> System
Generic)

-- | Additional information for extended lambdas.
data ExtLamInfo = ExtLamInfo
  { ExtLamInfo -> ModuleName
extLamModule    :: ModuleName
    -- ^ For complicated reasons the scope checker decides the QName of a
    --   pattern lambda, and thus its module. We really need to decide the
    --   module during type checking though, since if the lambda appears in a
    --   refined context the module picked by the scope checker has very much
    --   the wrong parameters.
  , ExtLamInfo -> Bool
extLamAbsurd :: Bool
    -- ^ Was this definition created from an absurd lambda @λ ()@?
  , ExtLamInfo -> Maybe System
extLamSys :: !(Strict.Maybe System)
  } deriving (Int -> ExtLamInfo -> ShowS
[ExtLamInfo] -> ShowS
ExtLamInfo -> String
(Int -> ExtLamInfo -> ShowS)
-> (ExtLamInfo -> String)
-> ([ExtLamInfo] -> ShowS)
-> Show ExtLamInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ExtLamInfo -> ShowS
showsPrec :: Int -> ExtLamInfo -> ShowS
$cshow :: ExtLamInfo -> String
show :: ExtLamInfo -> String
$cshowList :: [ExtLamInfo] -> ShowS
showList :: [ExtLamInfo] -> ShowS
Show, (forall x. ExtLamInfo -> Rep ExtLamInfo x)
-> (forall x. Rep ExtLamInfo x -> ExtLamInfo) -> Generic ExtLamInfo
forall x. Rep ExtLamInfo x -> ExtLamInfo
forall x. ExtLamInfo -> Rep ExtLamInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ExtLamInfo -> Rep ExtLamInfo x
from :: forall x. ExtLamInfo -> Rep ExtLamInfo x
$cto :: forall x. Rep ExtLamInfo x -> ExtLamInfo
to :: forall x. Rep ExtLamInfo x -> ExtLamInfo
Generic)

modifySystem :: (System -> System) -> ExtLamInfo -> ExtLamInfo
modifySystem :: (System -> System) -> ExtLamInfo -> ExtLamInfo
modifySystem System -> System
f ExtLamInfo
e = let !e' :: ExtLamInfo
e' = ExtLamInfo
e { extLamSys = f <$> extLamSys e } in ExtLamInfo
e'

-- | Additional information for projection 'Function's.
data Projection = Projection
  { Projection -> Maybe QName
projProper    :: Maybe QName
    -- ^ @Nothing@ if only projection-like, @Just r@ if record projection.
    --   The @r@ is the name of the record type projected from.
    --   This field is updated by module application.
  , Projection -> QName
projOrig      :: QName
    -- ^ The original projection name
    --   (current name could be from module application).
  , Projection -> Arg QName
projFromType  :: Arg QName
    -- ^ Type projected from. Original record type if @projProper = Just{}@.
    --   Also stores @ArgInfo@ of the principal argument.
    --   This field is unchanged by module application.
  , Projection -> Int
projIndex     :: Int
    -- ^ Index of the record argument.
    --   Start counting with 1, because 0 means that
    --   it is already applied to the record value.
    --   This can happen in module instantiation, but
    --   then either the record value is @var 0@, or @funProjection == Left _@.
  , Projection -> ProjLams
projLams :: ProjLams
    -- ^ Term @t@ to be be applied to record parameters and record value.
    --   The parameters will be dropped.
    --   In case of a proper projection, a postfix projection application
    --   will be created: @t = \ pars r -> r .p@
    --   (Invariant: the number of abstractions equals 'projIndex'.)
    --   In case of a projection-like function, just the function symbol
    --   is returned as 'Def':  @t = \ pars -> f@.
  } deriving (Int -> Projection -> ShowS
[Projection] -> ShowS
Projection -> String
(Int -> Projection -> ShowS)
-> (Projection -> String)
-> ([Projection] -> ShowS)
-> Show Projection
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Projection -> ShowS
showsPrec :: Int -> Projection -> ShowS
$cshow :: Projection -> String
show :: Projection -> String
$cshowList :: [Projection] -> ShowS
showList :: [Projection] -> ShowS
Show, (forall x. Projection -> Rep Projection x)
-> (forall x. Rep Projection x -> Projection) -> Generic Projection
forall x. Rep Projection x -> Projection
forall x. Projection -> Rep Projection x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Projection -> Rep Projection x
from :: forall x. Projection -> Rep Projection x
$cto :: forall x. Rep Projection x -> Projection
to :: forall x. Rep Projection x -> Projection
Generic)

-- | Abstractions to build projection function (dropping parameters).
newtype ProjLams = ProjLams { ProjLams -> [Arg ShortText]
getProjLams :: [Arg ArgName] }
  deriving (Int -> ProjLams -> ShowS
[ProjLams] -> ShowS
ProjLams -> String
(Int -> ProjLams -> ShowS)
-> (ProjLams -> String) -> ([ProjLams] -> ShowS) -> Show ProjLams
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ProjLams -> ShowS
showsPrec :: Int -> ProjLams -> ShowS
$cshow :: ProjLams -> String
show :: ProjLams -> String
$cshowList :: [ProjLams] -> ShowS
showList :: [ProjLams] -> ShowS
Show, ProjLams
ProjLams -> Bool
ProjLams -> (ProjLams -> Bool) -> Null ProjLams
forall a. a -> (a -> Bool) -> Null a
$cempty :: ProjLams
empty :: ProjLams
$cnull :: ProjLams -> Bool
null :: ProjLams -> Bool
Null, (forall x. ProjLams -> Rep ProjLams x)
-> (forall x. Rep ProjLams x -> ProjLams) -> Generic ProjLams
forall x. Rep ProjLams x -> ProjLams
forall x. ProjLams -> Rep ProjLams x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ProjLams -> Rep ProjLams x
from :: forall x. ProjLams -> Rep ProjLams x
$cto :: forall x. Rep ProjLams x -> ProjLams
to :: forall x. Rep ProjLams x -> ProjLams
Generic)

-- | Building the projection function (which drops the parameters).
projDropPars :: Projection -> ProjOrigin -> Term
-- Proper projections:
projDropPars :: Projection -> ProjOrigin -> Term
projDropPars (Projection Just{} QName
d Arg QName
_ Int
_ ProjLams
lams) ProjOrigin
o =
  case [Arg ShortText] -> Maybe ([Arg ShortText], Arg ShortText)
forall a. [a] -> Maybe ([a], a)
initLast ([Arg ShortText] -> Maybe ([Arg ShortText], Arg ShortText))
-> [Arg ShortText] -> Maybe ([Arg ShortText], Arg ShortText)
forall a b. (a -> b) -> a -> b
$ ProjLams -> [Arg ShortText]
getProjLams ProjLams
lams of
    Maybe ([Arg ShortText], Arg ShortText)
Nothing -> QName -> [Elim] -> Term
Def QName
d []
    Just ([Arg ShortText]
pars, Arg ArgInfo
i ShortText
y) ->
      let core :: Term
core = ArgInfo -> Abs Term -> Term
Lam ArgInfo
i (Abs Term -> Term) -> Abs Term -> Term
forall a b. (a -> b) -> a -> b
$ ShortText -> Term -> Abs Term
forall a. ShortText -> a -> Abs a
Abs ShortText
y (Term -> Abs Term) -> Term -> Abs Term
forall a b. (a -> b) -> a -> b
$ Int -> [Elim] -> Term
Var Int
0 [ProjOrigin -> QName -> Elim
forall a. ProjOrigin -> QName -> Elim' a
Proj ProjOrigin
o QName
d] in
      (Arg ShortText -> Term -> Term) -> Term -> [Arg ShortText] -> Term
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
List.foldr (\ (Arg ArgInfo
ai ShortText
x) -> ArgInfo -> Abs Term -> Term
Lam ArgInfo
ai (Abs Term -> Term) -> (Term -> Abs Term) -> Term -> Term
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ShortText -> Term -> Abs Term
forall a. ShortText -> a -> Abs a
NoAbs ShortText
x) Term
core [Arg ShortText]
pars
-- Projection-like functions:
projDropPars (Projection Maybe QName
Nothing QName
d Arg QName
_ Int
_ ProjLams
lams) ProjOrigin
o =
  (Arg ShortText -> Term -> Term) -> Term -> [Arg ShortText] -> Term
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
List.foldr (\ (Arg ArgInfo
ai ShortText
x) -> ArgInfo -> Abs Term -> Term
Lam ArgInfo
ai (Abs Term -> Term) -> (Term -> Abs Term) -> Term -> Term
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ShortText -> Term -> Abs Term
forall a. ShortText -> a -> Abs a
NoAbs ShortText
x) (QName -> [Elim] -> Term
Def QName
d []) ([Arg ShortText] -> Term) -> [Arg ShortText] -> Term
forall a b. (a -> b) -> a -> b
$
    [Arg ShortText] -> [Arg ShortText] -> [Arg ShortText]
forall a. [a] -> [a] -> [a]
initWithDefault [Arg ShortText]
forall a. HasCallStack => a
__IMPOSSIBLE__ ([Arg ShortText] -> [Arg ShortText])
-> [Arg ShortText] -> [Arg ShortText]
forall a b. (a -> b) -> a -> b
$ ProjLams -> [Arg ShortText]
getProjLams ProjLams
lams

-- | The info of the principal (record) argument.
projArgInfo :: Projection -> ArgInfo
projArgInfo :: Projection -> ArgInfo
projArgInfo (Projection Maybe QName
_ QName
_ Arg QName
_ Int
_ ProjLams
lams) =
  ArgInfo
-> (Arg ShortText -> ArgInfo) -> Maybe (Arg ShortText) -> ArgInfo
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ArgInfo
forall a. HasCallStack => a
__IMPOSSIBLE__ Arg ShortText -> ArgInfo
forall a. LensArgInfo a => a -> ArgInfo
getArgInfo (Maybe (Arg ShortText) -> ArgInfo)
-> Maybe (Arg ShortText) -> ArgInfo
forall a b. (a -> b) -> a -> b
$ [Arg ShortText] -> Maybe (Arg ShortText)
forall a. [a] -> Maybe a
lastMaybe ([Arg ShortText] -> Maybe (Arg ShortText))
-> [Arg ShortText] -> Maybe (Arg ShortText)
forall a b. (a -> b) -> a -> b
$ ProjLams -> [Arg ShortText]
getProjLams ProjLams
lams

-- | Should a record type admit eta-equality?
data EtaEquality
  = Specified { EtaEquality -> HasEta
theEtaEquality :: !HasEta }  -- ^ User specified 'eta-equality' or 'no-eta-equality'.
  | Inferred  { theEtaEquality :: !HasEta }  -- ^ Positivity checker inferred whether eta is safe.
  deriving (Int -> EtaEquality -> ShowS
[EtaEquality] -> ShowS
EtaEquality -> String
(Int -> EtaEquality -> ShowS)
-> (EtaEquality -> String)
-> ([EtaEquality] -> ShowS)
-> Show EtaEquality
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EtaEquality -> ShowS
showsPrec :: Int -> EtaEquality -> ShowS
$cshow :: EtaEquality -> String
show :: EtaEquality -> String
$cshowList :: [EtaEquality] -> ShowS
showList :: [EtaEquality] -> ShowS
Show, EtaEquality -> EtaEquality -> Bool
(EtaEquality -> EtaEquality -> Bool)
-> (EtaEquality -> EtaEquality -> Bool) -> Eq EtaEquality
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: EtaEquality -> EtaEquality -> Bool
== :: EtaEquality -> EtaEquality -> Bool
$c/= :: EtaEquality -> EtaEquality -> Bool
/= :: EtaEquality -> EtaEquality -> Bool
Eq, (forall x. EtaEquality -> Rep EtaEquality x)
-> (forall x. Rep EtaEquality x -> EtaEquality)
-> Generic EtaEquality
forall x. Rep EtaEquality x -> EtaEquality
forall x. EtaEquality -> Rep EtaEquality x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. EtaEquality -> Rep EtaEquality x
from :: forall x. EtaEquality -> Rep EtaEquality x
$cto :: forall x. Rep EtaEquality x -> EtaEquality
to :: forall x. Rep EtaEquality x -> EtaEquality
Generic)

instance PatternMatchingAllowed EtaEquality where
  patternMatchingAllowed :: EtaEquality -> Bool
patternMatchingAllowed = HasEta -> Bool
forall a. PatternMatchingAllowed a => a -> Bool
patternMatchingAllowed (HasEta -> Bool) -> (EtaEquality -> HasEta) -> EtaEquality -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EtaEquality -> HasEta
theEtaEquality

instance CopatternMatchingAllowed EtaEquality where
  copatternMatchingAllowed :: EtaEquality -> Bool
copatternMatchingAllowed = HasEta -> Bool
forall a. CopatternMatchingAllowed a => a -> Bool
copatternMatchingAllowed (HasEta -> Bool) -> (EtaEquality -> HasEta) -> EtaEquality -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EtaEquality -> HasEta
theEtaEquality

-- | Make sure we do not overwrite a user specification.
setEtaEquality :: EtaEquality -> HasEta -> EtaEquality
setEtaEquality :: EtaEquality -> HasEta -> EtaEquality
setEtaEquality e :: EtaEquality
e@Specified{} HasEta
_ = EtaEquality
e
setEtaEquality EtaEquality
_ HasEta
b = HasEta -> EtaEquality
Inferred HasEta
b

data FunctionFlag
  = FunInline  -- ^ Should calls to this function be inlined by the compiler?
  | FunMacro   -- ^ Is this function a macro?
  | FunFirstOrder
      -- ^ Is this function @INJECTIVE_FOR_INFERENCE@?
      -- Indicates whether the first-order shortcut should be applied to the definition.
  | FunAbstract
      -- ^ Is the function abstract?
  | FunProj
      -- ^ Is this function a descendant of a field (typically, a projection)?
  deriving (FunctionFlag -> FunctionFlag -> Bool
(FunctionFlag -> FunctionFlag -> Bool)
-> (FunctionFlag -> FunctionFlag -> Bool) -> Eq FunctionFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FunctionFlag -> FunctionFlag -> Bool
== :: FunctionFlag -> FunctionFlag -> Bool
$c/= :: FunctionFlag -> FunctionFlag -> Bool
/= :: FunctionFlag -> FunctionFlag -> Bool
Eq, Eq FunctionFlag
Eq FunctionFlag =>
(FunctionFlag -> FunctionFlag -> Ordering)
-> (FunctionFlag -> FunctionFlag -> Bool)
-> (FunctionFlag -> FunctionFlag -> Bool)
-> (FunctionFlag -> FunctionFlag -> Bool)
-> (FunctionFlag -> FunctionFlag -> Bool)
-> (FunctionFlag -> FunctionFlag -> FunctionFlag)
-> (FunctionFlag -> FunctionFlag -> FunctionFlag)
-> Ord FunctionFlag
FunctionFlag -> FunctionFlag -> Bool
FunctionFlag -> FunctionFlag -> Ordering
FunctionFlag -> FunctionFlag -> FunctionFlag
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: FunctionFlag -> FunctionFlag -> Ordering
compare :: FunctionFlag -> FunctionFlag -> Ordering
$c< :: FunctionFlag -> FunctionFlag -> Bool
< :: FunctionFlag -> FunctionFlag -> Bool
$c<= :: FunctionFlag -> FunctionFlag -> Bool
<= :: FunctionFlag -> FunctionFlag -> Bool
$c> :: FunctionFlag -> FunctionFlag -> Bool
> :: FunctionFlag -> FunctionFlag -> Bool
$c>= :: FunctionFlag -> FunctionFlag -> Bool
>= :: FunctionFlag -> FunctionFlag -> Bool
$cmax :: FunctionFlag -> FunctionFlag -> FunctionFlag
max :: FunctionFlag -> FunctionFlag -> FunctionFlag
$cmin :: FunctionFlag -> FunctionFlag -> FunctionFlag
min :: FunctionFlag -> FunctionFlag -> FunctionFlag
Ord, Int -> FunctionFlag
FunctionFlag -> Int
FunctionFlag -> [FunctionFlag]
FunctionFlag -> FunctionFlag
FunctionFlag -> FunctionFlag -> [FunctionFlag]
FunctionFlag -> FunctionFlag -> FunctionFlag -> [FunctionFlag]
(FunctionFlag -> FunctionFlag)
-> (FunctionFlag -> FunctionFlag)
-> (Int -> FunctionFlag)
-> (FunctionFlag -> Int)
-> (FunctionFlag -> [FunctionFlag])
-> (FunctionFlag -> FunctionFlag -> [FunctionFlag])
-> (FunctionFlag -> FunctionFlag -> [FunctionFlag])
-> (FunctionFlag -> FunctionFlag -> FunctionFlag -> [FunctionFlag])
-> Enum FunctionFlag
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: FunctionFlag -> FunctionFlag
succ :: FunctionFlag -> FunctionFlag
$cpred :: FunctionFlag -> FunctionFlag
pred :: FunctionFlag -> FunctionFlag
$ctoEnum :: Int -> FunctionFlag
toEnum :: Int -> FunctionFlag
$cfromEnum :: FunctionFlag -> Int
fromEnum :: FunctionFlag -> Int
$cenumFrom :: FunctionFlag -> [FunctionFlag]
enumFrom :: FunctionFlag -> [FunctionFlag]
$cenumFromThen :: FunctionFlag -> FunctionFlag -> [FunctionFlag]
enumFromThen :: FunctionFlag -> FunctionFlag -> [FunctionFlag]
$cenumFromTo :: FunctionFlag -> FunctionFlag -> [FunctionFlag]
enumFromTo :: FunctionFlag -> FunctionFlag -> [FunctionFlag]
$cenumFromThenTo :: FunctionFlag -> FunctionFlag -> FunctionFlag -> [FunctionFlag]
enumFromThenTo :: FunctionFlag -> FunctionFlag -> FunctionFlag -> [FunctionFlag]
Enum, Int -> FunctionFlag -> ShowS
[FunctionFlag] -> ShowS
FunctionFlag -> String
(Int -> FunctionFlag -> ShowS)
-> (FunctionFlag -> String)
-> ([FunctionFlag] -> ShowS)
-> Show FunctionFlag
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FunctionFlag -> ShowS
showsPrec :: Int -> FunctionFlag -> ShowS
$cshow :: FunctionFlag -> String
show :: FunctionFlag -> String
$cshowList :: [FunctionFlag] -> ShowS
showList :: [FunctionFlag] -> ShowS
Show, (forall x. FunctionFlag -> Rep FunctionFlag x)
-> (forall x. Rep FunctionFlag x -> FunctionFlag)
-> Generic FunctionFlag
forall x. Rep FunctionFlag x -> FunctionFlag
forall x. FunctionFlag -> Rep FunctionFlag x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. FunctionFlag -> Rep FunctionFlag x
from :: forall x. FunctionFlag -> Rep FunctionFlag x
$cto :: forall x. Rep FunctionFlag x -> FunctionFlag
to :: forall x. Rep FunctionFlag x -> FunctionFlag
Generic, Ord FunctionFlag
Ord FunctionFlag =>
((FunctionFlag, FunctionFlag) -> [FunctionFlag])
-> ((FunctionFlag, FunctionFlag) -> FunctionFlag -> Int)
-> ((FunctionFlag, FunctionFlag) -> FunctionFlag -> Int)
-> ((FunctionFlag, FunctionFlag) -> FunctionFlag -> Bool)
-> ((FunctionFlag, FunctionFlag) -> Int)
-> ((FunctionFlag, FunctionFlag) -> Int)
-> Ix FunctionFlag
(FunctionFlag, FunctionFlag) -> Int
(FunctionFlag, FunctionFlag) -> [FunctionFlag]
(FunctionFlag, FunctionFlag) -> FunctionFlag -> Bool
(FunctionFlag, FunctionFlag) -> FunctionFlag -> Int
forall a.
Ord a =>
((a, a) -> [a])
-> ((a, a) -> a -> Int)
-> ((a, a) -> a -> Int)
-> ((a, a) -> a -> Bool)
-> ((a, a) -> Int)
-> ((a, a) -> Int)
-> Ix a
$crange :: (FunctionFlag, FunctionFlag) -> [FunctionFlag]
range :: (FunctionFlag, FunctionFlag) -> [FunctionFlag]
$cindex :: (FunctionFlag, FunctionFlag) -> FunctionFlag -> Int
index :: (FunctionFlag, FunctionFlag) -> FunctionFlag -> Int
$cunsafeIndex :: (FunctionFlag, FunctionFlag) -> FunctionFlag -> Int
unsafeIndex :: (FunctionFlag, FunctionFlag) -> FunctionFlag -> Int
$cinRange :: (FunctionFlag, FunctionFlag) -> FunctionFlag -> Bool
inRange :: (FunctionFlag, FunctionFlag) -> FunctionFlag -> Bool
$crangeSize :: (FunctionFlag, FunctionFlag) -> Int
rangeSize :: (FunctionFlag, FunctionFlag) -> Int
$cunsafeRangeSize :: (FunctionFlag, FunctionFlag) -> Int
unsafeRangeSize :: (FunctionFlag, FunctionFlag) -> Int
Ix, FunctionFlag
FunctionFlag -> FunctionFlag -> Bounded FunctionFlag
forall a. a -> a -> Bounded a
$cminBound :: FunctionFlag
minBound :: FunctionFlag
$cmaxBound :: FunctionFlag
maxBound :: FunctionFlag
Bounded)

instance SmallSetElement FunctionFlag
instance KillRange (SmallSet FunctionFlag) where killRange :: KillRangeT (SmallSet FunctionFlag)
killRange = KillRangeT (SmallSet FunctionFlag)
forall a. a -> a
id

data CompKit = CompKit
  { CompKit -> Maybe QName
nameOfHComp :: Maybe QName
  , CompKit -> Maybe QName
nameOfTransp :: Maybe QName
  }
  deriving (CompKit -> CompKit -> Bool
(CompKit -> CompKit -> Bool)
-> (CompKit -> CompKit -> Bool) -> Eq CompKit
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CompKit -> CompKit -> Bool
== :: CompKit -> CompKit -> Bool
$c/= :: CompKit -> CompKit -> Bool
/= :: CompKit -> CompKit -> Bool
Eq, Eq CompKit
Eq CompKit =>
(CompKit -> CompKit -> Ordering)
-> (CompKit -> CompKit -> Bool)
-> (CompKit -> CompKit -> Bool)
-> (CompKit -> CompKit -> Bool)
-> (CompKit -> CompKit -> Bool)
-> (CompKit -> CompKit -> CompKit)
-> (CompKit -> CompKit -> CompKit)
-> Ord CompKit
CompKit -> CompKit -> Bool
CompKit -> CompKit -> Ordering
CompKit -> CompKit -> CompKit
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: CompKit -> CompKit -> Ordering
compare :: CompKit -> CompKit -> Ordering
$c< :: CompKit -> CompKit -> Bool
< :: CompKit -> CompKit -> Bool
$c<= :: CompKit -> CompKit -> Bool
<= :: CompKit -> CompKit -> Bool
$c> :: CompKit -> CompKit -> Bool
> :: CompKit -> CompKit -> Bool
$c>= :: CompKit -> CompKit -> Bool
>= :: CompKit -> CompKit -> Bool
$cmax :: CompKit -> CompKit -> CompKit
max :: CompKit -> CompKit -> CompKit
$cmin :: CompKit -> CompKit -> CompKit
min :: CompKit -> CompKit -> CompKit
Ord, Int -> CompKit -> ShowS
[CompKit] -> ShowS
CompKit -> String
(Int -> CompKit -> ShowS)
-> (CompKit -> String) -> ([CompKit] -> ShowS) -> Show CompKit
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CompKit -> ShowS
showsPrec :: Int -> CompKit -> ShowS
$cshow :: CompKit -> String
show :: CompKit -> String
$cshowList :: [CompKit] -> ShowS
showList :: [CompKit] -> ShowS
Show, (forall x. CompKit -> Rep CompKit x)
-> (forall x. Rep CompKit x -> CompKit) -> Generic CompKit
forall x. Rep CompKit x -> CompKit
forall x. CompKit -> Rep CompKit x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. CompKit -> Rep CompKit x
from :: forall x. CompKit -> Rep CompKit x
$cto :: forall x. Rep CompKit x -> CompKit
to :: forall x. Rep CompKit x -> CompKit
Generic)

emptyCompKit :: CompKit
emptyCompKit :: CompKit
emptyCompKit = Maybe QName -> Maybe QName -> CompKit
CompKit Maybe QName
forall a. Maybe a
Nothing Maybe QName
forall a. Maybe a
Nothing

defaultAxiom :: Defn
defaultAxiom :: Defn
defaultAxiom = Bool -> Defn
Axiom Bool
False

constTranspAxiom :: Defn
constTranspAxiom :: Defn
constTranspAxiom = Bool -> Defn
Axiom Bool
True

data Defn
  = AxiomDefn AxiomData
      -- ^ Postulate.
  | DataOrRecSigDefn DataOrRecSigData
      -- ^ Data or record type signature that doesn't yet have a definition.
  | GeneralizableVar
      -- ^ Generalizable variable (introduced in @variable@ block).
      NumGeneralizableArgs
        -- ^ For a generalized variable, shows how many arguments should be generalised.
  | AbstractDefn Defn
      -- ^ Returned by 'getConstInfo' if definition is abstract.
  | FunctionDefn FunctionData
  | DatatypeDefn DatatypeData
  | RecordDefn RecordData
  | ConstructorDefn ConstructorData
  | PrimitiveDefn PrimitiveData
      -- ^ Primitive or builtin functions.
  | PrimitiveSortDefn PrimitiveSortData
    deriving (Int -> Defn -> ShowS
[Defn] -> ShowS
Defn -> String
(Int -> Defn -> ShowS)
-> (Defn -> String) -> ([Defn] -> ShowS) -> Show Defn
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Defn -> ShowS
showsPrec :: Int -> Defn -> ShowS
$cshow :: Defn -> String
show :: Defn -> String
$cshowList :: [Defn] -> ShowS
showList :: [Defn] -> ShowS
Show, (forall x. Defn -> Rep Defn x)
-> (forall x. Rep Defn x -> Defn) -> Generic Defn
forall x. Rep Defn x -> Defn
forall x. Defn -> Rep Defn x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Defn -> Rep Defn x
from :: forall x. Defn -> Rep Defn x
$cto :: forall x. Rep Defn x -> Defn
to :: forall x. Rep Defn x -> Defn
Generic)

{-# COMPLETE
  Axiom, DataOrRecSig, GeneralizableVar, AbstractDefn,
  Function, Datatype, Record, Constructor, Primitive, PrimitiveSort #-}

data AxiomData = AxiomData
  { AxiomData -> Bool
_axiomConstTransp :: Bool
    -- ^ Can transp for this postulate be constant?
    --   Set to @True@ for builtins like String.
  } deriving (Int -> AxiomData -> ShowS
[AxiomData] -> ShowS
AxiomData -> String
(Int -> AxiomData -> ShowS)
-> (AxiomData -> String)
-> ([AxiomData] -> ShowS)
-> Show AxiomData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AxiomData -> ShowS
showsPrec :: Int -> AxiomData -> ShowS
$cshow :: AxiomData -> String
show :: AxiomData -> String
$cshowList :: [AxiomData] -> ShowS
showList :: [AxiomData] -> ShowS
Show, (forall x. AxiomData -> Rep AxiomData x)
-> (forall x. Rep AxiomData x -> AxiomData) -> Generic AxiomData
forall x. Rep AxiomData x -> AxiomData
forall x. AxiomData -> Rep AxiomData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. AxiomData -> Rep AxiomData x
from :: forall x. AxiomData -> Rep AxiomData x
$cto :: forall x. Rep AxiomData x -> AxiomData
to :: forall x. Rep AxiomData x -> AxiomData
Generic)

pattern Axiom :: Bool -> Defn
pattern $bAxiom :: Bool -> Defn
$mAxiom :: forall {r}. Defn -> (Bool -> r) -> ((# #) -> r) -> r
Axiom{ Defn -> Bool
axiomConstTransp } = AxiomDefn (AxiomData axiomConstTransp)

data DataOrRecSigData = DataOrRecSigData
  { DataOrRecSigData -> Int
_datarecPars :: Int
  } deriving (Int -> DataOrRecSigData -> ShowS
[DataOrRecSigData] -> ShowS
DataOrRecSigData -> String
(Int -> DataOrRecSigData -> ShowS)
-> (DataOrRecSigData -> String)
-> ([DataOrRecSigData] -> ShowS)
-> Show DataOrRecSigData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DataOrRecSigData -> ShowS
showsPrec :: Int -> DataOrRecSigData -> ShowS
$cshow :: DataOrRecSigData -> String
show :: DataOrRecSigData -> String
$cshowList :: [DataOrRecSigData] -> ShowS
showList :: [DataOrRecSigData] -> ShowS
Show, (forall x. DataOrRecSigData -> Rep DataOrRecSigData x)
-> (forall x. Rep DataOrRecSigData x -> DataOrRecSigData)
-> Generic DataOrRecSigData
forall x. Rep DataOrRecSigData x -> DataOrRecSigData
forall x. DataOrRecSigData -> Rep DataOrRecSigData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. DataOrRecSigData -> Rep DataOrRecSigData x
from :: forall x. DataOrRecSigData -> Rep DataOrRecSigData x
$cto :: forall x. Rep DataOrRecSigData x -> DataOrRecSigData
to :: forall x. Rep DataOrRecSigData x -> DataOrRecSigData
Generic)

pattern DataOrRecSig :: Int -> Defn
pattern $bDataOrRecSig :: Int -> Defn
$mDataOrRecSig :: forall {r}. Defn -> (Int -> r) -> ((# #) -> r) -> r
DataOrRecSig{ Defn -> Int
datarecPars } = DataOrRecSigDefn (DataOrRecSigData datarecPars)

-- | Indicates the reason behind a function having not been marked
-- projection-like.
data ProjectionLikenessMissing
  = MaybeProjection
    -- ^ Projection-likeness analysis has not run on this function yet.
    -- It may do so in the future.
  | NeverProjection
    -- ^ The user has requested that this function be not be marked
    -- projection-like. The analysis may already have run on this
    -- function, but the results have been discarded, and it will not be
    -- run again.
  deriving (Int -> ProjectionLikenessMissing -> ShowS
[ProjectionLikenessMissing] -> ShowS
ProjectionLikenessMissing -> String
(Int -> ProjectionLikenessMissing -> ShowS)
-> (ProjectionLikenessMissing -> String)
-> ([ProjectionLikenessMissing] -> ShowS)
-> Show ProjectionLikenessMissing
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ProjectionLikenessMissing -> ShowS
showsPrec :: Int -> ProjectionLikenessMissing -> ShowS
$cshow :: ProjectionLikenessMissing -> String
show :: ProjectionLikenessMissing -> String
$cshowList :: [ProjectionLikenessMissing] -> ShowS
showList :: [ProjectionLikenessMissing] -> ShowS
Show, (forall x.
 ProjectionLikenessMissing -> Rep ProjectionLikenessMissing x)
-> (forall x.
    Rep ProjectionLikenessMissing x -> ProjectionLikenessMissing)
-> Generic ProjectionLikenessMissing
forall x.
Rep ProjectionLikenessMissing x -> ProjectionLikenessMissing
forall x.
ProjectionLikenessMissing -> Rep ProjectionLikenessMissing x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x.
ProjectionLikenessMissing -> Rep ProjectionLikenessMissing x
from :: forall x.
ProjectionLikenessMissing -> Rep ProjectionLikenessMissing x
$cto :: forall x.
Rep ProjectionLikenessMissing x -> ProjectionLikenessMissing
to :: forall x.
Rep ProjectionLikenessMissing x -> ProjectionLikenessMissing
Generic, Int -> ProjectionLikenessMissing
ProjectionLikenessMissing -> Int
ProjectionLikenessMissing -> [ProjectionLikenessMissing]
ProjectionLikenessMissing -> ProjectionLikenessMissing
ProjectionLikenessMissing
-> ProjectionLikenessMissing -> [ProjectionLikenessMissing]
ProjectionLikenessMissing
-> ProjectionLikenessMissing
-> ProjectionLikenessMissing
-> [ProjectionLikenessMissing]
(ProjectionLikenessMissing -> ProjectionLikenessMissing)
-> (ProjectionLikenessMissing -> ProjectionLikenessMissing)
-> (Int -> ProjectionLikenessMissing)
-> (ProjectionLikenessMissing -> Int)
-> (ProjectionLikenessMissing -> [ProjectionLikenessMissing])
-> (ProjectionLikenessMissing
    -> ProjectionLikenessMissing -> [ProjectionLikenessMissing])
-> (ProjectionLikenessMissing
    -> ProjectionLikenessMissing -> [ProjectionLikenessMissing])
-> (ProjectionLikenessMissing
    -> ProjectionLikenessMissing
    -> ProjectionLikenessMissing
    -> [ProjectionLikenessMissing])
-> Enum ProjectionLikenessMissing
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: ProjectionLikenessMissing -> ProjectionLikenessMissing
succ :: ProjectionLikenessMissing -> ProjectionLikenessMissing
$cpred :: ProjectionLikenessMissing -> ProjectionLikenessMissing
pred :: ProjectionLikenessMissing -> ProjectionLikenessMissing
$ctoEnum :: Int -> ProjectionLikenessMissing
toEnum :: Int -> ProjectionLikenessMissing
$cfromEnum :: ProjectionLikenessMissing -> Int
fromEnum :: ProjectionLikenessMissing -> Int
$cenumFrom :: ProjectionLikenessMissing -> [ProjectionLikenessMissing]
enumFrom :: ProjectionLikenessMissing -> [ProjectionLikenessMissing]
$cenumFromThen :: ProjectionLikenessMissing
-> ProjectionLikenessMissing -> [ProjectionLikenessMissing]
enumFromThen :: ProjectionLikenessMissing
-> ProjectionLikenessMissing -> [ProjectionLikenessMissing]
$cenumFromTo :: ProjectionLikenessMissing
-> ProjectionLikenessMissing -> [ProjectionLikenessMissing]
enumFromTo :: ProjectionLikenessMissing
-> ProjectionLikenessMissing -> [ProjectionLikenessMissing]
$cenumFromThenTo :: ProjectionLikenessMissing
-> ProjectionLikenessMissing
-> ProjectionLikenessMissing
-> [ProjectionLikenessMissing]
enumFromThenTo :: ProjectionLikenessMissing
-> ProjectionLikenessMissing
-> ProjectionLikenessMissing
-> [ProjectionLikenessMissing]
Enum, ProjectionLikenessMissing
ProjectionLikenessMissing
-> ProjectionLikenessMissing -> Bounded ProjectionLikenessMissing
forall a. a -> a -> Bounded a
$cminBound :: ProjectionLikenessMissing
minBound :: ProjectionLikenessMissing
$cmaxBound :: ProjectionLikenessMissing
maxBound :: ProjectionLikenessMissing
Bounded)

-- | Data associated with a generated @with@-function required for
-- checking its applications.
data WithFunInfo
  = NotWithFunction -- ^ This is not a @with@ function.
  | WithFunInfo
    { WithFunInfo -> QName
wfParent   :: !QName
      -- ^ Points to the /immediate/ parent of this @with@ function.
      -- This parent can be another generated function, if the user
      -- wrote nested (rather than parallel) with-abstractions.
    , WithFunInfo -> Telescope
wfDelta1   :: !Telescope
      -- ^ The part of the parent clause context required for checking
      -- the @with@-expressions.
      -- This is a prefix of the @with@-function type.
    , WithFunInfo -> Int
wfWithArgs :: !Nat1
      -- ^ The number of arguments introduced for the @with@ expressions
      -- in the generated function.
      -- This is basically the number of pipes in the LHS, but e.g.
      -- @with ... in ...@ and @rewrite@ both introduce two arguments
      -- each.
    }
  deriving (Int -> WithFunInfo -> ShowS
[WithFunInfo] -> ShowS
WithFunInfo -> String
(Int -> WithFunInfo -> ShowS)
-> (WithFunInfo -> String)
-> ([WithFunInfo] -> ShowS)
-> Show WithFunInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> WithFunInfo -> ShowS
showsPrec :: Int -> WithFunInfo -> ShowS
$cshow :: WithFunInfo -> String
show :: WithFunInfo -> String
$cshowList :: [WithFunInfo] -> ShowS
showList :: [WithFunInfo] -> ShowS
Show, (forall x. WithFunInfo -> Rep WithFunInfo x)
-> (forall x. Rep WithFunInfo x -> WithFunInfo)
-> Generic WithFunInfo
forall x. Rep WithFunInfo x -> WithFunInfo
forall x. WithFunInfo -> Rep WithFunInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. WithFunInfo -> Rep WithFunInfo x
from :: forall x. WithFunInfo -> Rep WithFunInfo x
$cto :: forall x. Rep WithFunInfo x -> WithFunInfo
to :: forall x. Rep WithFunInfo x -> WithFunInfo
Generic)

data FunctionData = FunctionData
  { FunctionData -> [Clause]
_funClauses        :: [Clause]
  , FunctionData -> Maybe CompiledClauses
_funCompiled       :: Maybe CompiledClauses
      -- ^ 'Nothing' while function is still type-checked.
      --   @Just cc@ after type and coverage checking and
      --   translation to case trees.
  , FunctionData -> Maybe SplitTree
_funSplitTree      :: Maybe SplitTree
      -- ^ The split tree constructed by the coverage
      --   checker. Needed to re-compile the clauses after
      --   forcing translation.
  , FunctionData -> [Clause]
_funCovering       :: [Clause]
      -- ^ Covering clauses computed by coverage checking.
      --   Erased by (IApply) confluence checking(?)
  , FunctionData -> FunctionInverse
_funInv            :: FunctionInverse
  , FunctionData -> Maybe [QName]
_funMutual         :: Maybe [QName]
      -- ^ Mutually recursive functions, @data@s and @record@s.
      --   Does include this function.
      --   Empty list if not recursive.
      --   @Nothing@ if not yet computed (by positivity checker).
  , FunctionData -> Either ProjectionLikenessMissing Projection
_funProjection     :: Either ProjectionLikenessMissing Projection
      -- ^ Is it a record projection?
      --   If yes, then return the name of the record type and index of
      --   the record argument.  Start counting with 1, because 0 means that
      --   it is already applied to the record. (Can happen in module
      --   instantiation.) This information is used in the termination
      --   checker.
  , FunctionData -> SmallSet FunctionFlag
_funFlags          :: SmallSet FunctionFlag
      -- ^ Various boolean flags pertaining to the function definition, see 'FunctionFlag'.
  , FunctionData -> Maybe Bool
_funTerminates     :: Maybe Bool
      -- ^ Has this function been termination checked?  Did it pass?
  , FunctionData -> Maybe ExtLamInfo
_funExtLam         :: Maybe ExtLamInfo
      -- ^ Is this function generated from an extended lambda?
      --   If yes, then return the number of hidden and non-hidden lambda-lifted arguments.
  , FunctionData -> WithFunInfo
_funWith           :: WithFunInfo
      -- ^ Is this a generated with-function?
      --   If yes, then what's the name of the parent function?
  , FunctionData -> Maybe QName
_funIsKanOp        :: Maybe QName
      -- ^ Is this a helper for one of the Kan operations (transp,
      -- hcomp) on data types/records? If so, for which data type?
  , FunctionData -> IsOpaque
_funOpaque         :: IsOpaque
      -- ^ Is this function opaque? If so, and we're not in an opaque
      -- block that includes this function('s name), it will be treated
      -- abstractly.
  } deriving (Int -> FunctionData -> ShowS
[FunctionData] -> ShowS
FunctionData -> String
(Int -> FunctionData -> ShowS)
-> (FunctionData -> String)
-> ([FunctionData] -> ShowS)
-> Show FunctionData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FunctionData -> ShowS
showsPrec :: Int -> FunctionData -> ShowS
$cshow :: FunctionData -> String
show :: FunctionData -> String
$cshowList :: [FunctionData] -> ShowS
showList :: [FunctionData] -> ShowS
Show, (forall x. FunctionData -> Rep FunctionData x)
-> (forall x. Rep FunctionData x -> FunctionData)
-> Generic FunctionData
forall x. Rep FunctionData x -> FunctionData
forall x. FunctionData -> Rep FunctionData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. FunctionData -> Rep FunctionData x
from :: forall x. FunctionData -> Rep FunctionData x
$cto :: forall x. Rep FunctionData x -> FunctionData
to :: forall x. Rep FunctionData x -> FunctionData
Generic)

pattern Function
  :: [Clause]
  -> Maybe CompiledClauses
  -> Maybe SplitTree
  -> [Clause]
  -> FunctionInverse
  -> Maybe [QName]
  -> Either ProjectionLikenessMissing Projection
  -> SmallSet FunctionFlag
  -> Maybe Bool
  -> Maybe ExtLamInfo
  -> WithFunInfo
  -> Maybe QName
  -> IsOpaque
  -> Defn
pattern $bFunction :: [Clause]
-> Maybe CompiledClauses
-> Maybe SplitTree
-> [Clause]
-> FunctionInverse
-> Maybe [QName]
-> Either ProjectionLikenessMissing Projection
-> SmallSet FunctionFlag
-> Maybe Bool
-> Maybe ExtLamInfo
-> WithFunInfo
-> Maybe QName
-> IsOpaque
-> Defn
$mFunction :: forall {r}.
Defn
-> ([Clause]
    -> Maybe CompiledClauses
    -> Maybe SplitTree
    -> [Clause]
    -> FunctionInverse
    -> Maybe [QName]
    -> Either ProjectionLikenessMissing Projection
    -> SmallSet FunctionFlag
    -> Maybe Bool
    -> Maybe ExtLamInfo
    -> WithFunInfo
    -> Maybe QName
    -> IsOpaque
    -> r)
-> ((# #) -> r)
-> r
Function
  { Defn -> [Clause]
funClauses
  , Defn -> Maybe CompiledClauses
funCompiled
  , Defn -> Maybe SplitTree
funSplitTree
  , Defn -> [Clause]
funCovering
  , Defn -> FunctionInverse
funInv
  , Defn -> Maybe [QName]
funMutual
  , Defn -> Either ProjectionLikenessMissing Projection
funProjection
  , Defn -> SmallSet FunctionFlag
funFlags
  , Defn -> Maybe Bool
funTerminates
  , Defn -> Maybe ExtLamInfo
funExtLam
  , Defn -> WithFunInfo
funWith
  , Defn -> Maybe QName
funIsKanOp
  , Defn -> IsOpaque
funOpaque
  } = FunctionDefn (FunctionData
    funClauses
    funCompiled
    funSplitTree
    funCovering
    funInv
    funMutual
    funProjection
    funFlags
    funTerminates
    funExtLam
    funWith
    funIsKanOp
    funOpaque
  )

data DatatypeData = DatatypeData
  { DatatypeData -> Int
_dataPars           :: Nat
      -- ^ Number of parameters.
  , DatatypeData -> Int
_dataIxs            :: Nat
      -- ^ Number of indices.
  , DatatypeData -> Maybe Clause
_dataClause         :: Maybe Clause
      -- ^ This might be in an instantiated module.
  , DatatypeData -> [QName]
_dataCons           :: [QName]
      -- ^ Constructor names, ordered according to the order of their definition.
  , DatatypeData -> Sort
_dataSort           :: Sort
  , DatatypeData -> Maybe [QName]
_dataMutual         :: Maybe [QName]
      -- ^ Mutually recursive functions, @data@s and @record@s.
      --   Does include this data type.
      --   Empty if not recursive.
      --   @Nothing@ if not yet computed (by positivity checker).
  , DatatypeData -> PositivityCheck
_dataPositivityCheck:: PositivityCheck
      -- ^ Should positivity errors be reported for this data type?
  , DatatypeData -> IsAbstract
_dataAbstr          :: IsAbstract
  , DatatypeData -> [QName]
_dataPathCons       :: [QName]
      -- ^ Path constructor names (subset of @dataCons@).
  , DatatypeData -> Maybe QName
_dataTranspIx       :: Maybe QName
      -- ^ If indexed datatype, name of the "index transport" function.
  , DatatypeData -> Maybe QName
_dataTransp         :: Maybe QName
      -- ^ Transport function, should be available for all datatypes in supported sorts.
  } deriving (Int -> DatatypeData -> ShowS
[DatatypeData] -> ShowS
DatatypeData -> String
(Int -> DatatypeData -> ShowS)
-> (DatatypeData -> String)
-> ([DatatypeData] -> ShowS)
-> Show DatatypeData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DatatypeData -> ShowS
showsPrec :: Int -> DatatypeData -> ShowS
$cshow :: DatatypeData -> String
show :: DatatypeData -> String
$cshowList :: [DatatypeData] -> ShowS
showList :: [DatatypeData] -> ShowS
Show, (forall x. DatatypeData -> Rep DatatypeData x)
-> (forall x. Rep DatatypeData x -> DatatypeData)
-> Generic DatatypeData
forall x. Rep DatatypeData x -> DatatypeData
forall x. DatatypeData -> Rep DatatypeData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. DatatypeData -> Rep DatatypeData x
from :: forall x. DatatypeData -> Rep DatatypeData x
$cto :: forall x. Rep DatatypeData x -> DatatypeData
to :: forall x. Rep DatatypeData x -> DatatypeData
Generic)

pattern Datatype
  :: Nat
  -> Nat
  -> (Maybe Clause)
  -> [QName]
  -> Sort
  -> Maybe [QName]
  -> PositivityCheck
  -> IsAbstract
  -> [QName]
  -> Maybe QName
  -> Maybe QName
  -> Defn

pattern $bDatatype :: Int
-> Int
-> Maybe Clause
-> [QName]
-> Sort
-> Maybe [QName]
-> PositivityCheck
-> IsAbstract
-> [QName]
-> Maybe QName
-> Maybe QName
-> Defn
$mDatatype :: forall {r}.
Defn
-> (Int
    -> Int
    -> Maybe Clause
    -> [QName]
    -> Sort
    -> Maybe [QName]
    -> PositivityCheck
    -> IsAbstract
    -> [QName]
    -> Maybe QName
    -> Maybe QName
    -> r)
-> ((# #) -> r)
-> r
Datatype
  { Defn -> Int
dataPars
  , Defn -> Int
dataIxs
  , Defn -> Maybe Clause
dataClause
  , Defn -> [QName]
dataCons
  , Defn -> Sort
dataSort
  , Defn -> Maybe [QName]
dataMutual
  , Defn -> PositivityCheck
dataPositivityCheck
  , Defn -> IsAbstract
dataAbstr
  , Defn -> [QName]
dataPathCons
  , Defn -> Maybe QName
dataTranspIx
  , Defn -> Maybe QName
dataTransp
  } = DatatypeDefn (DatatypeData
    dataPars
    dataIxs
    dataClause
    dataCons
    dataSort
    dataMutual
    dataPositivityCheck
    dataAbstr
    dataPathCons
    dataTranspIx
    dataTransp
  )

data RecordData = RecordData
  { RecordData -> Int
_recPars           :: Nat
      -- ^ Number of parameters.
  , RecordData -> Maybe Clause
_recClause         :: Maybe Clause
      -- ^ Was this record type created by a module application?
      --   If yes, the clause is its definition (linking back to the original record type).
  , RecordData -> ConHead
_recConHead        :: ConHead
      -- ^ Constructor name and fields.
  , RecordData -> Bool
_recNamedCon       :: Bool
      -- ^ Does this record have a @constructor@?
  , RecordData -> [Dom QName]
_recFields         :: [Dom QName]
      -- ^ The record field names.
  , RecordData -> Telescope
_recTel            :: Telescope
      -- ^ The record field telescope. (Includes record parameters.)
      --   Note: @TelV recTel _ == telView' recConType@.
      --   Thus, @recTel@ is redundant.
      --
      -- == __Warning__
      --
      -- The parameter visibilities on @_recTel@ do not match
      -- the visibilities of the record's 'defType'!
  , RecordData -> Maybe [QName]
_recMutual         :: Maybe [QName]
      -- ^ Mutually recursive functions, @data@s and @record@s.
      --   Does include this record.
      --   Empty if not recursive.
      --   @Nothing@ if not yet computed (by positivity checker).
  , RecordData -> PositivityCheck
_recPositivityCheck :: PositivityCheck
      -- ^ Should positivity errors be reported for this record type?
  , RecordData -> EtaEquality
_recEtaEquality'    :: EtaEquality
      -- ^ Eta-expand at this record type?
      --   @False@ for unguarded recursive records and coinductive records
      --   unless the user specifies otherwise.
  , RecordData -> PatternOrCopattern
_recPatternMatching :: PatternOrCopattern
      -- ^ In case eta-equality is off, do we allow pattern matching on the
      --   constructor or construction by copattern matching?
      --   Having both loses subject reduction, see issue #4560.
      --   After positivity checking, this field is obsolete, part of 'EtaEquality'.
  , RecordData -> Maybe Induction
_recInduction      :: Maybe Induction
      -- ^ 'Inductive' or 'CoInductive'?  Matters only for recursive records.
      --   'Nothing' means that the user did not specify it, which is an error
      --   for recursive records.
  , RecordData -> Maybe Bool
_recTerminates     :: Maybe Bool
      -- ^ 'Just True' means that unfolding of the recursive record terminates,
      --   'Just False' means that we have no evidence for termination,
      --   and 'Nothing' means we have not run the termination checker yet.
  , RecordData -> IsAbstract
_recAbstr          :: IsAbstract
  , RecordData -> CompKit
_recComp           :: CompKit
  } deriving (Int -> RecordData -> ShowS
[RecordData] -> ShowS
RecordData -> String
(Int -> RecordData -> ShowS)
-> (RecordData -> String)
-> ([RecordData] -> ShowS)
-> Show RecordData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RecordData -> ShowS
showsPrec :: Int -> RecordData -> ShowS
$cshow :: RecordData -> String
show :: RecordData -> String
$cshowList :: [RecordData] -> ShowS
showList :: [RecordData] -> ShowS
Show, (forall x. RecordData -> Rep RecordData x)
-> (forall x. Rep RecordData x -> RecordData) -> Generic RecordData
forall x. Rep RecordData x -> RecordData
forall x. RecordData -> Rep RecordData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. RecordData -> Rep RecordData x
from :: forall x. RecordData -> Rep RecordData x
$cto :: forall x. Rep RecordData x -> RecordData
to :: forall x. Rep RecordData x -> RecordData
Generic)

pattern Record
  :: Nat
  -> Maybe Clause
  -> ConHead
  -> Bool
  -> [Dom QName]
  -> Telescope
  -> Maybe [QName]
  -> PositivityCheck
  -> EtaEquality
  -> PatternOrCopattern
  -> Maybe Induction
  -> Maybe Bool
  -> IsAbstract
  -> CompKit
  -> Defn

pattern $bRecord :: Int
-> Maybe Clause
-> ConHead
-> Bool
-> [Dom QName]
-> Telescope
-> Maybe [QName]
-> PositivityCheck
-> EtaEquality
-> PatternOrCopattern
-> Maybe Induction
-> Maybe Bool
-> IsAbstract
-> CompKit
-> Defn
$mRecord :: forall {r}.
Defn
-> (Int
    -> Maybe Clause
    -> ConHead
    -> Bool
    -> [Dom QName]
    -> Telescope
    -> Maybe [QName]
    -> PositivityCheck
    -> EtaEquality
    -> PatternOrCopattern
    -> Maybe Induction
    -> Maybe Bool
    -> IsAbstract
    -> CompKit
    -> r)
-> ((# #) -> r)
-> r
Record
  { Defn -> Int
recPars
  , Defn -> Maybe Clause
recClause
  , Defn -> ConHead
recConHead
  , Defn -> Bool
recNamedCon
  , Defn -> [Dom QName]
recFields
  , Defn -> Telescope
recTel
  , Defn -> Maybe [QName]
recMutual
  , Defn -> PositivityCheck
recPositivityCheck
  , Defn -> EtaEquality
recEtaEquality'
  , Defn -> PatternOrCopattern
recPatternMatching
  , Defn -> Maybe Induction
recInduction
  , Defn -> Maybe Bool
recTerminates
  , Defn -> IsAbstract
recAbstr
  , Defn -> CompKit
recComp
  } = RecordDefn (RecordData
    recPars
    recClause
    recConHead
    recNamedCon
    recFields
    recTel
    recMutual
    recPositivityCheck
    recEtaEquality'
    recPatternMatching
    recInduction
    recTerminates
    recAbstr
    recComp
  )

data ConstructorData = ConstructorData
  { ConstructorData -> Int
_conPars   :: Int
      -- ^ Number of parameters.
  , ConstructorData -> Int
_conArity  :: Int
      -- ^ Number of arguments (excluding parameters).
  , ConstructorData -> ConHead
_conSrcCon :: ConHead
      -- ^ Name of (original) constructor and fields. (This might be in a module instance.)
  , ConstructorData -> QName
_conData   :: QName
      -- ^ Name of datatype or record type.
  , ConstructorData -> IsAbstract
_conAbstr  :: IsAbstract
  , ConstructorData -> CompKit
_conComp   :: CompKit
      -- ^ Cubical composition.
  , ConstructorData -> Maybe [QName]
_conProj   :: Maybe [QName]
      -- ^ Projections. 'Nothing' if not yet computed.
  , ConstructorData -> [IsForced]
_conForced :: [IsForced]
      -- ^ Which arguments are forced (i.e. determined by the type of the constructor)?
      --   Either this list is empty (if the forcing analysis isn't run), or its length is @conArity@.
  , ConstructorData -> Bool
_conInline :: !Bool
      -- ^ Shall we translate the constructor on the root of the rhs into copattern matching on the lhs?
      --   Activated by INLINE pragma.
  } deriving (Int -> ConstructorData -> ShowS
[ConstructorData] -> ShowS
ConstructorData -> String
(Int -> ConstructorData -> ShowS)
-> (ConstructorData -> String)
-> ([ConstructorData] -> ShowS)
-> Show ConstructorData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ConstructorData -> ShowS
showsPrec :: Int -> ConstructorData -> ShowS
$cshow :: ConstructorData -> String
show :: ConstructorData -> String
$cshowList :: [ConstructorData] -> ShowS
showList :: [ConstructorData] -> ShowS
Show, (forall x. ConstructorData -> Rep ConstructorData x)
-> (forall x. Rep ConstructorData x -> ConstructorData)
-> Generic ConstructorData
forall x. Rep ConstructorData x -> ConstructorData
forall x. ConstructorData -> Rep ConstructorData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ConstructorData -> Rep ConstructorData x
from :: forall x. ConstructorData -> Rep ConstructorData x
$cto :: forall x. Rep ConstructorData x -> ConstructorData
to :: forall x. Rep ConstructorData x -> ConstructorData
Generic)

pattern Constructor
  :: Int
  -> Int
  -> ConHead
  -> QName
  -> IsAbstract
  -> CompKit
  -> Maybe [QName]
  -> [IsForced]
  -> Bool
  -> Defn
pattern $bConstructor :: Int
-> Int
-> ConHead
-> QName
-> IsAbstract
-> CompKit
-> Maybe [QName]
-> [IsForced]
-> Bool
-> Defn
$mConstructor :: forall {r}.
Defn
-> (Int
    -> Int
    -> ConHead
    -> QName
    -> IsAbstract
    -> CompKit
    -> Maybe [QName]
    -> [IsForced]
    -> Bool
    -> r)
-> ((# #) -> r)
-> r
Constructor
  { Defn -> Int
conPars
  , Defn -> Int
conArity
  , Defn -> ConHead
conSrcCon
  , Defn -> QName
conData
  , Defn -> IsAbstract
conAbstr
  , Defn -> CompKit
conComp
  , Defn -> Maybe [QName]
conProj
  , Defn -> [IsForced]
conForced
  , Defn -> Bool
conInline
  } = ConstructorDefn (ConstructorData
    conPars
    conArity
    conSrcCon
    conData
    conAbstr
    conComp
    conProj
    conForced
    conInline
  )

data PrimitiveData = PrimitiveData
  { PrimitiveData -> IsAbstract
_primAbstr    :: IsAbstract
  , PrimitiveData -> PrimitiveId
_primName     :: PrimitiveId
  , PrimitiveData -> [Clause]
_primClauses  :: [Clause]
      -- ^ 'null' for primitive functions, @not null@ for builtin functions.
  , PrimitiveData -> FunctionInverse
_primInv      :: FunctionInverse
      -- ^ Builtin functions can have inverses. For instance, natural number addition.
  , PrimitiveData -> Maybe CompiledClauses
_primCompiled :: Maybe CompiledClauses
      -- ^ 'Nothing' for primitive functions,
      --   @'Just' something@ for builtin functions.
  , PrimitiveData -> IsOpaque
_primOpaque   :: IsOpaque
      -- ^ Primitives can also live in opaque blocks.
  } deriving (Int -> PrimitiveData -> ShowS
[PrimitiveData] -> ShowS
PrimitiveData -> String
(Int -> PrimitiveData -> ShowS)
-> (PrimitiveData -> String)
-> ([PrimitiveData] -> ShowS)
-> Show PrimitiveData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PrimitiveData -> ShowS
showsPrec :: Int -> PrimitiveData -> ShowS
$cshow :: PrimitiveData -> String
show :: PrimitiveData -> String
$cshowList :: [PrimitiveData] -> ShowS
showList :: [PrimitiveData] -> ShowS
Show, (forall x. PrimitiveData -> Rep PrimitiveData x)
-> (forall x. Rep PrimitiveData x -> PrimitiveData)
-> Generic PrimitiveData
forall x. Rep PrimitiveData x -> PrimitiveData
forall x. PrimitiveData -> Rep PrimitiveData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PrimitiveData -> Rep PrimitiveData x
from :: forall x. PrimitiveData -> Rep PrimitiveData x
$cto :: forall x. Rep PrimitiveData x -> PrimitiveData
to :: forall x. Rep PrimitiveData x -> PrimitiveData
Generic)

pattern Primitive
  :: IsAbstract
  -> PrimitiveId
  -> [Clause]
  -> FunctionInverse
  -> Maybe CompiledClauses
  -> IsOpaque
  -> Defn
pattern $bPrimitive :: IsAbstract
-> PrimitiveId
-> [Clause]
-> FunctionInverse
-> Maybe CompiledClauses
-> IsOpaque
-> Defn
$mPrimitive :: forall {r}.
Defn
-> (IsAbstract
    -> PrimitiveId
    -> [Clause]
    -> FunctionInverse
    -> Maybe CompiledClauses
    -> IsOpaque
    -> r)
-> ((# #) -> r)
-> r
Primitive
  { Defn -> IsAbstract
primAbstr
  , Defn -> PrimitiveId
primName
  , Defn -> [Clause]
primClauses
  , Defn -> FunctionInverse
primInv
  , Defn -> Maybe CompiledClauses
primCompiled
  , Defn -> IsOpaque
primOpaque
  } = PrimitiveDefn (PrimitiveData
    primAbstr
    primName
    primClauses
    primInv
    primCompiled
    primOpaque
  )

data PrimitiveSortData = PrimitiveSortData
  { PrimitiveSortData -> BuiltinSort
_primSortName :: BuiltinSort
  , PrimitiveSortData -> Sort
_primSortSort :: Sort
  } deriving (Int -> PrimitiveSortData -> ShowS
[PrimitiveSortData] -> ShowS
PrimitiveSortData -> String
(Int -> PrimitiveSortData -> ShowS)
-> (PrimitiveSortData -> String)
-> ([PrimitiveSortData] -> ShowS)
-> Show PrimitiveSortData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PrimitiveSortData -> ShowS
showsPrec :: Int -> PrimitiveSortData -> ShowS
$cshow :: PrimitiveSortData -> String
show :: PrimitiveSortData -> String
$cshowList :: [PrimitiveSortData] -> ShowS
showList :: [PrimitiveSortData] -> ShowS
Show, (forall x. PrimitiveSortData -> Rep PrimitiveSortData x)
-> (forall x. Rep PrimitiveSortData x -> PrimitiveSortData)
-> Generic PrimitiveSortData
forall x. Rep PrimitiveSortData x -> PrimitiveSortData
forall x. PrimitiveSortData -> Rep PrimitiveSortData x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PrimitiveSortData -> Rep PrimitiveSortData x
from :: forall x. PrimitiveSortData -> Rep PrimitiveSortData x
$cto :: forall x. Rep PrimitiveSortData x -> PrimitiveSortData
to :: forall x. Rep PrimitiveSortData x -> PrimitiveSortData
Generic)

pattern PrimitiveSort
  :: BuiltinSort
  -> Sort
  -> Defn
pattern $bPrimitiveSort :: BuiltinSort -> Sort -> Defn
$mPrimitiveSort :: forall {r}. Defn -> (BuiltinSort -> Sort -> r) -> ((# #) -> r) -> r
PrimitiveSort
  { Defn -> BuiltinSort
primSortName
  , Defn -> Sort
primSortSort
  } = PrimitiveSortDefn (PrimitiveSortData
    primSortName
    primSortSort
  )

-- TODO: lenses for all Defn variants

lensFunction :: Lens' Defn FunctionData
lensFunction :: Lens' Defn FunctionData
lensFunction FunctionData -> f FunctionData
f = \case
  FunctionDefn FunctionData
d -> FunctionData -> Defn
FunctionDefn (FunctionData -> Defn) -> f FunctionData -> f Defn
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FunctionData -> f FunctionData
f FunctionData
d
  Defn
_ -> f Defn
forall a. HasCallStack => a
__IMPOSSIBLE__

lensConstructor :: Lens' Defn ConstructorData
lensConstructor :: Lens' Defn ConstructorData
lensConstructor ConstructorData -> f ConstructorData
f = \case
  ConstructorDefn ConstructorData
d -> ConstructorData -> Defn
ConstructorDefn (ConstructorData -> Defn) -> f ConstructorData -> f Defn
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ConstructorData -> f ConstructorData
f ConstructorData
d
  Defn
_ -> f Defn
forall a. HasCallStack => a
__IMPOSSIBLE__

lensRecord :: Lens' Defn RecordData
lensRecord :: Lens' Defn RecordData
lensRecord RecordData -> f RecordData
f = \case
  RecordDefn RecordData
d -> RecordData -> Defn
RecordDefn (RecordData -> Defn) -> f RecordData -> f Defn
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RecordData -> f RecordData
f RecordData
d
  Defn
_ -> f Defn
forall a. HasCallStack => a
__IMPOSSIBLE__

-- Lenses for Record

lensRecTel :: Lens' RecordData Telescope
lensRecTel :: Lens' RecordData Telescope
lensRecTel Telescope -> f Telescope
f RecordData
r =
  Telescope -> f Telescope
f (RecordData -> Telescope
_recTel RecordData
r) f Telescope -> (Telescope -> RecordData) -> f RecordData
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Telescope
tel -> RecordData
r { _recTel = tel }

lensRecEta :: Lens' RecordData EtaEquality
lensRecEta :: Lens' RecordData EtaEquality
lensRecEta EtaEquality -> f EtaEquality
f RecordData
r =
  EtaEquality -> f EtaEquality
f (RecordData -> EtaEquality
_recEtaEquality' RecordData
r) f EtaEquality -> (EtaEquality -> RecordData) -> f RecordData
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ EtaEquality
eta -> RecordData
r { _recEtaEquality' = eta }

-- Pretty printing definitions

instance Pretty Definition where
  pretty :: Definition -> Doc
pretty Defn{Bool
[Maybe Name]
[Occurrence]
[Polarity]
[LocalDisplayForm]
Maybe QName
Maybe InstanceInfo
CompiledRepresentation
ArgInfo
QName
Blocked_
Type
Defn
MutualId
defArgInfo :: Definition -> ArgInfo
defName :: Definition -> QName
defType :: Definition -> Type
defPolarity :: Definition -> [Polarity]
defArgOccurrences :: Definition -> [Occurrence]
defGeneralizedParams :: Definition -> [Maybe Name]
defDisplay :: Definition -> [LocalDisplayForm]
defMutual :: Definition -> MutualId
defCompiledRep :: Definition -> CompiledRepresentation
defInstance :: Definition -> Maybe InstanceInfo
defCopy :: Definition -> Maybe QName
defNoCompilation :: Definition -> Bool
defInjective :: Definition -> Bool
defCopatternLHS :: Definition -> Bool
defBlocked :: Definition -> Blocked_
defMightContainMetas :: Definition -> Bool
theDef :: Definition -> Defn
defArgInfo :: ArgInfo
defName :: QName
defType :: Type
defPolarity :: [Polarity]
defArgOccurrences :: [Occurrence]
defGeneralizedParams :: [Maybe Name]
defDisplay :: [LocalDisplayForm]
defMutual :: MutualId
defCompiledRep :: CompiledRepresentation
defInstance :: Maybe InstanceInfo
defCopy :: Maybe QName
defNoCompilation :: Bool
defInjective :: Bool
defCopatternLHS :: Bool
defBlocked :: Blocked_
defMightContainMetas :: Bool
theDef :: Defn
..} =
    Doc
"Defn {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"defArgInfo        =" Doc -> Doc -> Doc
<?> ArgInfo -> Doc
forall a. Show a => a -> Doc
pshow ArgInfo
defArgInfo
      , Doc
"defName           =" Doc -> Doc -> Doc
<?> QName -> Doc
forall a. Pretty a => a -> Doc
pretty QName
defName
      , Doc
"defType           =" Doc -> Doc -> Doc
<?> Type -> Doc
forall a. Pretty a => a -> Doc
pretty Type
defType
      , Doc
"defPolarity       =" Doc -> Doc -> Doc
<?> [Polarity] -> Doc
forall a. Show a => a -> Doc
pshow [Polarity]
defPolarity
      , Doc
"defArgOccurrences =" Doc -> Doc -> Doc
<?> [Occurrence] -> Doc
forall a. Show a => a -> Doc
pshow [Occurrence]
defArgOccurrences
      , Doc
"defGeneralizedParams =" Doc -> Doc -> Doc
<?> [Maybe Name] -> Doc
forall a. Show a => a -> Doc
pshow [Maybe Name]
defGeneralizedParams
      , Doc
"defDisplay        =" Doc -> Doc -> Doc
<?> [LocalDisplayForm] -> Doc
forall a. Pretty a => a -> Doc
pretty [LocalDisplayForm]
defDisplay
      , Doc
"defMutual         =" Doc -> Doc -> Doc
<?> MutualId -> Doc
forall a. Show a => a -> Doc
pshow MutualId
defMutual
      , Doc
"defCompiledRep    =" Doc -> Doc -> Doc
<?> CompiledRepresentation -> Doc
forall a. Show a => a -> Doc
pshow CompiledRepresentation
defCompiledRep
      , Doc
"defInstance       =" Doc -> Doc -> Doc
<?> Maybe InstanceInfo -> Doc
forall a. Show a => a -> Doc
pshow Maybe InstanceInfo
defInstance
      , Doc
"defCopy           =" Doc -> Doc -> Doc
<?> Maybe QName -> Doc
forall a. Show a => a -> Doc
pshow Maybe QName
defCopy
      , Doc
"defInjective      =" Doc -> Doc -> Doc
<?> Bool -> Doc
forall a. Show a => a -> Doc
pshow Bool
defInjective
      , Doc
"defCopatternLHS   =" Doc -> Doc -> Doc
<?> Bool -> Doc
forall a. Show a => a -> Doc
pshow Bool
defCopatternLHS
      , Doc
"theDef            =" Doc -> Doc -> Doc
<?> Defn -> Doc
forall a. Pretty a => a -> Doc
pretty Defn
theDef ] Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Doc
"}"

instance Pretty Defn where
  pretty :: Defn -> Doc
pretty = \case
    AxiomDefn AxiomData
_         -> Doc
"Axiom"
    DataOrRecSigDefn DataOrRecSigData
d  -> DataOrRecSigData -> Doc
forall a. Pretty a => a -> Doc
pretty DataOrRecSigData
d
    GeneralizableVar NumGeneralizableArgs
_  -> Doc
"GeneralizableVar"
    AbstractDefn Defn
def    -> Doc
"AbstractDefn" Doc -> Doc -> Doc
<?> Doc -> Doc
parens (Defn -> Doc
forall a. Pretty a => a -> Doc
pretty Defn
def)
    FunctionDefn FunctionData
d      -> FunctionData -> Doc
forall a. Pretty a => a -> Doc
pretty FunctionData
d
    DatatypeDefn DatatypeData
d      -> DatatypeData -> Doc
forall a. Pretty a => a -> Doc
pretty DatatypeData
d
    RecordDefn RecordData
d        -> RecordData -> Doc
forall a. Pretty a => a -> Doc
pretty RecordData
d
    ConstructorDefn ConstructorData
d   -> ConstructorData -> Doc
forall a. Pretty a => a -> Doc
pretty ConstructorData
d
    PrimitiveDefn PrimitiveData
d     -> PrimitiveData -> Doc
forall a. Pretty a => a -> Doc
pretty PrimitiveData
d
    PrimitiveSortDefn PrimitiveSortData
d -> PrimitiveSortData -> Doc
forall a. Pretty a => a -> Doc
pretty PrimitiveSortData
d

instance Pretty DataOrRecSigData where
  pretty :: DataOrRecSigData -> Doc
pretty (DataOrRecSigData Int
n) = Doc
"DataOrRecSig" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Int -> Doc
forall a. Pretty a => a -> Doc
pretty Int
n

instance Pretty ProjectionLikenessMissing where
  pretty :: ProjectionLikenessMissing -> Doc
pretty ProjectionLikenessMissing
MaybeProjection = Doc
"MaybeProjection"
  pretty ProjectionLikenessMissing
NeverProjection = Doc
"NeverProjection"

instance Pretty WithFunInfo where
  pretty :: WithFunInfo -> Doc
pretty WithFunInfo
NotWithFunction = Doc
"NotWithFunction"
  pretty (WithFunInfo QName
parent Telescope
delta1 Int
withargs) =
    Doc
"WithFunction {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"wfParent     =" Doc -> Doc -> Doc
<?> QName -> Doc
forall a. Pretty a => a -> Doc
pretty QName
parent
      , Doc
"wfDelta1     =" Doc -> Doc -> Doc
<?> Telescope -> Doc
forall a. Pretty a => a -> Doc
pretty Telescope
delta1
      , Doc
"wfWithArgs   =" Doc -> Doc -> Doc
<?> Int -> Doc
forall a. Pretty a => a -> Doc
pretty Int
withargs
      ] Doc -> Doc -> Doc
<?> Doc
"}"

instance Pretty FunctionData where
  pretty :: FunctionData -> Doc
pretty (FunctionData
      [Clause]
funClauses
      Maybe CompiledClauses
funCompiled
      Maybe SplitTree
funSplitTree
      [Clause]
_funCovering
      FunctionInverse
funInv
      Maybe [QName]
funMutual
      Either ProjectionLikenessMissing Projection
funProjection
      SmallSet FunctionFlag
funFlags
      Maybe Bool
funTerminates
      Maybe ExtLamInfo
_funExtLam
      WithFunInfo
funWith
      Maybe QName
funIsKanOp
      IsOpaque
funOpaque
    ) =
    Doc
"Function {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"funClauses      =" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat ((Clause -> Doc) -> [Clause] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map Clause -> Doc
forall a. Pretty a => a -> Doc
pretty [Clause]
funClauses)
      , Doc
"funCompiled     =" Doc -> Doc -> Doc
<?> Maybe CompiledClauses -> Doc
forall a. Pretty a => a -> Doc
pretty Maybe CompiledClauses
funCompiled
      , Doc
"funSplitTree    =" Doc -> Doc -> Doc
<?> Maybe SplitTree -> Doc
forall a. Pretty a => a -> Doc
pretty Maybe SplitTree
funSplitTree
      , Doc
"funInv          =" Doc -> Doc -> Doc
<?> FunctionInverse -> Doc
forall a. Pretty a => a -> Doc
pretty FunctionInverse
funInv
      , Doc
"funMutual       =" Doc -> Doc -> Doc
<?> Maybe [QName] -> Doc
forall a. Show a => a -> Doc
pshow Maybe [QName]
funMutual
      , Doc
"funProjection   =" Doc -> Doc -> Doc
<?> Either ProjectionLikenessMissing Projection -> Doc
forall a. Pretty a => a -> Doc
pretty Either ProjectionLikenessMissing Projection
funProjection
      , Doc
"funFlags        =" Doc -> Doc -> Doc
<?> SmallSet FunctionFlag -> Doc
forall a. Show a => a -> Doc
pshow SmallSet FunctionFlag
funFlags
      , Doc
"funTerminates   =" Doc -> Doc -> Doc
<?> Maybe Bool -> Doc
forall a. Show a => a -> Doc
pshow Maybe Bool
funTerminates
      , Doc
"funWith         =" Doc -> Doc -> Doc
<?> WithFunInfo -> Doc
forall a. Pretty a => a -> Doc
pretty WithFunInfo
funWith
      , Doc
"funIsKanOp      =" Doc -> Doc -> Doc
<?> Maybe QName -> Doc
forall a. Pretty a => a -> Doc
pretty Maybe QName
funIsKanOp
      , Doc
"funOpaque       =" Doc -> Doc -> Doc
<?> IsOpaque -> Doc
forall a. Show a => a -> Doc
pshow IsOpaque
funOpaque
      ] Doc -> Doc -> Doc
<?> Doc
"}"

instance Pretty DatatypeData where
  pretty :: DatatypeData -> Doc
pretty (DatatypeData
      Int
dataPars
      Int
dataIxs
      Maybe Clause
dataClause
      [QName]
dataCons
      Sort
dataSort
      Maybe [QName]
dataMutual
      PositivityCheck
_dataPositivityCheck
      IsAbstract
_dataAbstr
      [QName]
_dataPathCons
      Maybe QName
_dataTranspIx
      Maybe QName
_dataTransp
    ) =
    Doc
"Datatype {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"dataPars       =" Doc -> Doc -> Doc
<?> Int -> Doc
forall a. Show a => a -> Doc
pshow Int
dataPars
      , Doc
"dataIxs        =" Doc -> Doc -> Doc
<?> Int -> Doc
forall a. Show a => a -> Doc
pshow Int
dataIxs
      , Doc
"dataClause     =" Doc -> Doc -> Doc
<?> Maybe Clause -> Doc
forall a. Pretty a => a -> Doc
pretty Maybe Clause
dataClause
      , Doc
"dataCons       =" Doc -> Doc -> Doc
<?> [QName] -> Doc
forall a. Show a => a -> Doc
pshow [QName]
dataCons
      , Doc
"dataSort       =" Doc -> Doc -> Doc
<?> Sort -> Doc
forall a. Pretty a => a -> Doc
pretty Sort
dataSort
      , Doc
"dataMutual     =" Doc -> Doc -> Doc
<?> Maybe [QName] -> Doc
forall a. Show a => a -> Doc
pshow Maybe [QName]
dataMutual
      , Doc
"dataAbstr      =" Doc -> Doc -> Doc
<?> (Defn -> IsAbstract) -> Doc
forall a. Show a => a -> Doc
pshow Defn -> IsAbstract
dataAbstr
      ] Doc -> Doc -> Doc
<?> Doc
"}"

instance Pretty RecordData where
  pretty :: RecordData -> Doc
pretty (RecordData
      Int
recPars
      Maybe Clause
recClause
      ConHead
recConHead
      Bool
recNamedCon
      [Dom QName]
recFields
      Telescope
recTel
      Maybe [QName]
recMutual
      PositivityCheck
_recPositivityCheck
      EtaEquality
recEtaEquality'
      PatternOrCopattern
_recPatternMatching
      Maybe Induction
recInduction
      Maybe Bool
_recTerminates
      IsAbstract
recAbstr
      CompKit
_recComp
    ) =
    Doc
"Record {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"recPars         =" Doc -> Doc -> Doc
<?> Int -> Doc
forall a. Show a => a -> Doc
pshow Int
recPars
      , Doc
"recClause       =" Doc -> Doc -> Doc
<?> Maybe Clause -> Doc
forall a. Pretty a => a -> Doc
pretty Maybe Clause
recClause
      , Doc
"recConHead      =" Doc -> Doc -> Doc
<?> ConHead -> Doc
forall a. Pretty a => a -> Doc
pretty ConHead
recConHead
      , Doc
"recNamedCon     =" Doc -> Doc -> Doc
<?> Bool -> Doc
forall a. Pretty a => a -> Doc
pretty Bool
recNamedCon
      , Doc
"recFields       =" Doc -> Doc -> Doc
<?> [Dom QName] -> Doc
forall a. Pretty a => a -> Doc
pretty [Dom QName]
recFields
      , Doc
"recTel          =" Doc -> Doc -> Doc
<?> Telescope -> Doc
forall a. Pretty a => a -> Doc
pretty Telescope
recTel
      , Doc
"recMutual       =" Doc -> Doc -> Doc
<?> Maybe [QName] -> Doc
forall a. Show a => a -> Doc
pshow Maybe [QName]
recMutual
      , Doc
"recEtaEquality' =" Doc -> Doc -> Doc
<?> EtaEquality -> Doc
forall a. Show a => a -> Doc
pshow EtaEquality
recEtaEquality'
      , Doc
"recInduction    =" Doc -> Doc -> Doc
<?> Maybe Induction -> Doc
forall a. Show a => a -> Doc
pshow Maybe Induction
recInduction
      , Doc
"recAbstr        =" Doc -> Doc -> Doc
<?> IsAbstract -> Doc
forall a. Show a => a -> Doc
pshow IsAbstract
recAbstr
      ] Doc -> Doc -> Doc
<?> Doc
"}"

instance Pretty ConstructorData where
  pretty :: ConstructorData -> Doc
pretty (ConstructorData
      Int
conPars
      Int
conArity
      ConHead
conSrcCon
      QName
conData
      IsAbstract
conAbstr
      CompKit
_conComp
      Maybe [QName]
_conProj
      [IsForced]
_conForced
      Bool
conInline
    ) =
    Doc
"Constructor {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"conPars    =" Doc -> Doc -> Doc
<?> Int -> Doc
forall a. Show a => a -> Doc
pshow Int
conPars
      , Doc
"conArity   =" Doc -> Doc -> Doc
<?> Int -> Doc
forall a. Show a => a -> Doc
pshow Int
conArity
      , Doc
"conSrcCon  =" Doc -> Doc -> Doc
<?> ConHead -> Doc
forall a. Pretty a => a -> Doc
pretty ConHead
conSrcCon
      , Doc
"conData    =" Doc -> Doc -> Doc
<?> QName -> Doc
forall a. Pretty a => a -> Doc
pretty QName
conData
      , Doc
"conAbstr   =" Doc -> Doc -> Doc
<?> IsAbstract -> Doc
forall a. Show a => a -> Doc
pshow IsAbstract
conAbstr
      , Doc
"conInline  =" Doc -> Doc -> Doc
<?> Bool -> Doc
forall a. Show a => a -> Doc
pshow Bool
conInline
      ] Doc -> Doc -> Doc
<?> Doc
"}"

instance Pretty PrimitiveData where
  pretty :: PrimitiveData -> Doc
pretty (PrimitiveData
      IsAbstract
primAbstr
      PrimitiveId
primName
      [Clause]
primClauses
      FunctionInverse
_primInv
      Maybe CompiledClauses
primCompiled
      IsOpaque
primOpaque
      ) =
    Doc
"Primitive {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"primAbstr    =" Doc -> Doc -> Doc
<?> IsAbstract -> Doc
forall a. Show a => a -> Doc
pshow IsAbstract
primAbstr
      , Doc
"primName     =" Doc -> Doc -> Doc
<?> PrimitiveId -> Doc
forall a. Show a => a -> Doc
pshow PrimitiveId
primName
      , Doc
"primClauses  =" Doc -> Doc -> Doc
<?> [Clause] -> Doc
forall a. Show a => a -> Doc
pshow [Clause]
primClauses
      , Doc
"primCompiled =" Doc -> Doc -> Doc
<?> Maybe CompiledClauses -> Doc
forall a. Show a => a -> Doc
pshow Maybe CompiledClauses
primCompiled
      , Doc
"primOpaque   =" Doc -> Doc -> Doc
<?> IsOpaque -> Doc
forall a. Show a => a -> Doc
pshow IsOpaque
primOpaque
      ] Doc -> Doc -> Doc
<?> Doc
"}"

instance Pretty PrimitiveSortData where
  pretty :: PrimitiveSortData -> Doc
pretty (PrimitiveSortData BuiltinSort
primSortName Sort
primSortSort) =
    Doc
"PrimitiveSort {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"primSortName =" Doc -> Doc -> Doc
<?> BuiltinSort -> Doc
forall a. Show a => a -> Doc
pshow BuiltinSort
primSortName
      , Doc
"primSortSort =" Doc -> Doc -> Doc
<?> Sort -> Doc
forall a. Show a => a -> Doc
pshow Sort
primSortSort
      ] Doc -> Doc -> Doc
<?> Doc
"}"

instance Pretty Projection where
  pretty :: Projection -> Doc
pretty Projection{Int
Maybe QName
Arg QName
QName
ProjLams
projProper :: Projection -> Maybe QName
projOrig :: Projection -> QName
projFromType :: Projection -> Arg QName
projIndex :: Projection -> Int
projLams :: Projection -> ProjLams
projProper :: Maybe QName
projOrig :: QName
projFromType :: Arg QName
projIndex :: Int
projLams :: ProjLams
..} =
    Doc
"Projection {" Doc -> Doc -> Doc
<?> [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
      [ Doc
"projProper   =" Doc -> Doc -> Doc
<?> Maybe QName -> Doc
forall a. Pretty a => a -> Doc
pretty Maybe QName
projProper
      , Doc
"projOrig     =" Doc -> Doc -> Doc
<?> QName -> Doc
forall a. Pretty a => a -> Doc
pretty QName
projOrig
      , Doc
"projFromType =" Doc -> Doc -> Doc
<?> Arg QName -> Doc
forall a. Pretty a => a -> Doc
pretty Arg QName
projFromType
      , Doc
"projIndex    =" Doc -> Doc -> Doc
<?> Int -> Doc
forall a. Show a => a -> Doc
pshow Int
projIndex
      , Doc
"projLams     =" Doc -> Doc -> Doc
<?> ProjLams -> Doc
forall a. Pretty a => a -> Doc
pretty ProjLams
projLams
      ]

instance Pretty c => Pretty (FunctionInverse' c) where
  pretty :: FunctionInverse' c -> Doc
pretty FunctionInverse' c
NotInjective = Doc
"NotInjective"
  pretty (Inverse InversionMap c
inv) = Doc
"Inverse" Doc -> Doc -> Doc
<?>
    [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat [ TermHead -> Doc
forall a. Pretty a => a -> Doc
pretty TermHead
h Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Doc
"->" Doc -> Doc -> Doc
<?> [c] -> Doc
forall a. Pretty a => a -> Doc
pretty [c]
cs
         | (TermHead
h, [c]
cs) <- InversionMap c -> [(TermHead, [c])]
forall k a. Map k a -> [(k, a)]
Map.toList InversionMap c
inv ]

instance Pretty ProjLams where
  pretty :: ProjLams -> Doc
pretty (ProjLams [Arg ShortText]
args) = [Arg ShortText] -> Doc
forall a. Pretty a => a -> Doc
pretty [Arg ShortText]
args

-- | Is the record type recursive?
recRecursive :: Defn -> Bool
recRecursive :: Defn -> Bool
recRecursive (RecordDefn RecordData
d) = RecordData -> Bool
recRecursive_ RecordData
d
recRecursive Defn
_ = Bool
forall a. HasCallStack => a
__IMPOSSIBLE__

recRecursive_ :: RecordData -> Bool
recRecursive_ :: RecordData -> Bool
recRecursive_ RecordData{ _recMutual :: RecordData -> Maybe [QName]
_recMutual = Just [QName]
qs } = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ [QName] -> Bool
forall a. Null a => a -> Bool
null [QName]
qs
recRecursive_ RecordData
_ = Bool
forall a. HasCallStack => a
__IMPOSSIBLE__

recEtaEquality :: Defn -> HasEta
recEtaEquality :: Defn -> HasEta
recEtaEquality = EtaEquality -> HasEta
theEtaEquality (EtaEquality -> HasEta) -> (Defn -> EtaEquality) -> Defn -> HasEta
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Defn -> EtaEquality
recEtaEquality'

_recEtaEquality :: RecordData -> HasEta
_recEtaEquality :: RecordData -> HasEta
_recEtaEquality = EtaEquality -> HasEta
theEtaEquality (EtaEquality -> HasEta)
-> (RecordData -> EtaEquality) -> RecordData -> HasEta
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RecordData -> EtaEquality
_recEtaEquality'

-- | A template for creating 'Function' definitions, with sensible
-- defaults.
emptyFunctionData :: FunctionData
emptyFunctionData :: FunctionData
emptyFunctionData = FunctionData
    { _funClauses :: [Clause]
_funClauses     = []
    , _funCompiled :: Maybe CompiledClauses
_funCompiled    = Maybe CompiledClauses
forall a. Maybe a
Nothing
    , _funSplitTree :: Maybe SplitTree
_funSplitTree   = Maybe SplitTree
forall a. Maybe a
Nothing
    , _funInv :: FunctionInverse
_funInv         = FunctionInverse
forall c. FunctionInverse' c
NotInjective
    , _funMutual :: Maybe [QName]
_funMutual      = Maybe [QName]
forall a. Maybe a
Nothing
    , _funProjection :: Either ProjectionLikenessMissing Projection
_funProjection  = ProjectionLikenessMissing
-> Either ProjectionLikenessMissing Projection
forall a b. a -> Either a b
Left ProjectionLikenessMissing
MaybeProjection
    , _funFlags :: SmallSet FunctionFlag
_funFlags       = SmallSet FunctionFlag
forall a. SmallSet a
SmallSet.empty
    , _funTerminates :: Maybe Bool
_funTerminates  = Maybe Bool
forall a. Maybe a
Nothing
    , _funExtLam :: Maybe ExtLamInfo
_funExtLam      = Maybe ExtLamInfo
forall a. Maybe a
Nothing
    , _funWith :: WithFunInfo
_funWith        = WithFunInfo
NotWithFunction
    , _funCovering :: [Clause]
_funCovering    = []
    , _funIsKanOp :: Maybe QName
_funIsKanOp     = Maybe QName
forall a. Maybe a
Nothing
    , _funOpaque :: IsOpaque
_funOpaque      = IsOpaque
TransparentDef
    }

emptyFunction :: Defn
emptyFunction :: Defn
emptyFunction = FunctionData -> Defn
FunctionDefn FunctionData
emptyFunctionData

funFlag_ :: FunctionFlag -> Lens' FunctionData Bool
funFlag_ :: FunctionFlag -> Lens' FunctionData Bool
funFlag_ FunctionFlag
flag Bool -> f Bool
f def :: FunctionData
def@FunctionData{ _funFlags :: FunctionData -> SmallSet FunctionFlag
_funFlags = SmallSet FunctionFlag
flags } =
  Bool -> f Bool
f (FunctionFlag -> SmallSet FunctionFlag -> Bool
forall a. SmallSetElement a => a -> SmallSet a -> Bool
SmallSet.member FunctionFlag
flag SmallSet FunctionFlag
flags) f Bool -> (Bool -> FunctionData) -> f FunctionData
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&>
  \ Bool
b -> FunctionData
def{ _funFlags = (if b then SmallSet.insert else SmallSet.delete) flag flags }

funFlag :: FunctionFlag -> Lens' Defn Bool
funFlag :: FunctionFlag -> Lens' Defn Bool
funFlag FunctionFlag
flag Bool -> f Bool
f = \case
  FunctionDefn FunctionData
d -> FunctionData -> Defn
FunctionDefn (FunctionData -> Defn) -> f FunctionData -> f Defn
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FunctionFlag -> Lens' FunctionData Bool
funFlag_ FunctionFlag
flag Bool -> f Bool
f FunctionData
d
  Defn
def            -> Bool -> f Bool
f Bool
False f Bool -> Defn -> f Defn
forall (f :: * -> *) a b. Functor f => f a -> b -> f b
$> Defn
def

funInline, funMacro :: Lens' Defn Bool
funInline :: Lens' Defn Bool
funInline       = FunctionFlag -> Lens' Defn Bool
funFlag FunctionFlag
FunInline
funMacro :: Lens' Defn Bool
funMacro        = FunctionFlag -> Lens' Defn Bool
funFlag FunctionFlag
FunMacro

funMacro_ :: Lens' FunctionData Bool
funMacro_ :: Lens' FunctionData Bool
funMacro_ = FunctionFlag -> Lens' FunctionData Bool
funFlag_ FunctionFlag
FunMacro

-- | Toggle the 'FunFirstOrder' flag.
funFirstOrder :: Lens' Defn Bool
funFirstOrder :: Lens' Defn Bool
funFirstOrder = FunctionFlag -> Lens' Defn Bool
funFlag FunctionFlag
FunFirstOrder

-- | Toggle the 'FunAbstract' flag.
funAbstract :: Lens' Defn Bool
funAbstract :: Lens' Defn Bool
funAbstract = FunctionFlag -> Lens' Defn Bool
funFlag FunctionFlag
FunAbstract

-- | Toggle the 'FunAbstract' flag.
funAbstr :: Lens' Defn IsAbstract
funAbstr :: Lens' Defn IsAbstract
funAbstr = (Bool -> f Bool) -> Defn -> f Defn
Lens' Defn Bool
funAbstract ((Bool -> f Bool) -> Defn -> f Defn)
-> ((IsAbstract -> f IsAbstract) -> Bool -> f Bool)
-> (IsAbstract -> f IsAbstract)
-> Defn
-> f Defn
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> IsAbstract)
-> (IsAbstract -> Bool) -> Iso Bool Bool IsAbstract IsAbstract
forall s a b t. (s -> a) -> (b -> t) -> Iso s t a b
iso Bool -> IsAbstract
forall a. Boolean a => Bool -> a
fromBool IsAbstract -> Bool
forall a. IsBool a => a -> Bool
toBool

-- | Toggle the 'FunAbstract' flag.
funAbstract_ :: Lens' FunctionData Bool
funAbstract_ :: Lens' FunctionData Bool
funAbstract_ = FunctionFlag -> Lens' FunctionData Bool
funFlag_ FunctionFlag
FunAbstract

-- | Toggle the 'FunAbstract' flag.
funAbstr_ :: Lens' FunctionData IsAbstract
funAbstr_ :: Lens' FunctionData IsAbstract
funAbstr_ = (Bool -> f Bool) -> FunctionData -> f FunctionData
Lens' FunctionData Bool
funAbstract_ ((Bool -> f Bool) -> FunctionData -> f FunctionData)
-> ((IsAbstract -> f IsAbstract) -> Bool -> f Bool)
-> (IsAbstract -> f IsAbstract)
-> FunctionData
-> f FunctionData
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> IsAbstract)
-> (IsAbstract -> Bool) -> Iso Bool Bool IsAbstract IsAbstract
forall s a b t. (s -> a) -> (b -> t) -> Iso s t a b
iso Bool -> IsAbstract
forall a. Boolean a => Bool -> a
fromBool IsAbstract -> Bool
forall a. IsBool a => a -> Bool
toBool

-- | Toggle the 'FunProj' flag.
funProj :: Lens' Defn Bool
funProj :: Lens' Defn Bool
funProj = FunctionFlag -> Lens' Defn Bool
funFlag FunctionFlag
FunProj

-- | Toggle the 'FunProj' flag.
funProj_ :: Lens' FunctionData Bool
funProj_ :: Lens' FunctionData Bool
funProj_ = FunctionFlag -> Lens' FunctionData Bool
funFlag_ FunctionFlag
FunProj

isMacro :: Defn -> Bool
isMacro :: Defn -> Bool
isMacro = (Defn -> Getting Bool Defn Bool -> Bool
forall s a. s -> Getting a s a -> a
^. Getting Bool Defn Bool
Lens' Defn Bool
funMacro)

-- | Checking whether we are dealing with a function yet to be defined.
isEmptyFunction :: Defn -> Bool
isEmptyFunction :: Defn -> Bool
isEmptyFunction Defn
def =
  case Defn
def of
    Function { funClauses :: Defn -> [Clause]
funClauses = [] } -> Bool
True
    Defn
_ -> Bool
False

isExtendedLambda :: Defn -> Bool
isExtendedLambda :: Defn -> Bool
isExtendedLambda Defn
def =
  case Defn
def of
    Function { funExtLam :: Defn -> Maybe ExtLamInfo
funExtLam = Just{} } -> Bool
True
    Defn
_ -> Bool
False

isWithFunction :: Defn -> Bool
isWithFunction :: Defn -> Bool
isWithFunction Defn
def =
  case Defn
def of
    Function { funWith :: Defn -> WithFunInfo
funWith = WithFunInfo{} } -> Bool
True
    Defn
_ -> Bool
False

isCopatternLHS :: Foldable f => f Clause -> Bool
isCopatternLHS :: forall (f :: * -> *). Foldable f => f Clause -> Bool
isCopatternLHS = (Clause -> Bool) -> f Clause -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((NamedArg DeBruijnPattern -> Bool)
-> [NamedArg DeBruijnPattern] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe (ProjOrigin, AmbiguousQName) -> Bool
forall a. Maybe a -> Bool
isJust (Maybe (ProjOrigin, AmbiguousQName) -> Bool)
-> (NamedArg DeBruijnPattern -> Maybe (ProjOrigin, AmbiguousQName))
-> NamedArg DeBruijnPattern
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NamedArg DeBruijnPattern -> Maybe (ProjOrigin, AmbiguousQName)
forall a. IsProjP a => a -> Maybe (ProjOrigin, AmbiguousQName)
A.isProjP) ([NamedArg DeBruijnPattern] -> Bool)
-> (Clause -> [NamedArg DeBruijnPattern]) -> Clause -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Clause -> [NamedArg DeBruijnPattern]
namedClausePats)

recCon :: Defn -> QName
recCon :: Defn -> QName
recCon Record{ ConHead
recConHead :: Defn -> ConHead
recConHead :: ConHead
recConHead } = ConHead -> QName
conName ConHead
recConHead
recCon Defn
_ = QName
forall a. HasCallStack => a
__IMPOSSIBLE__

defIsRecord :: Defn -> Bool
defIsRecord :: Defn -> Bool
defIsRecord Record{} = Bool
True
defIsRecord Defn
_        = Bool
False

defIsDataOrRecord :: Defn -> Bool
defIsDataOrRecord :: Defn -> Bool
defIsDataOrRecord Record{}   = Bool
True
defIsDataOrRecord Datatype{} = Bool
True
defIsDataOrRecord Defn
_          = Bool
False

defConstructors :: Defn -> [QName]
defConstructors :: Defn -> [QName]
defConstructors Datatype{dataCons :: Defn -> [QName]
dataCons = [QName]
cs} = [QName]
cs
defConstructors Record{recConHead :: Defn -> ConHead
recConHead = ConHead
c} = [ConHead -> QName
conName ConHead
c]
defConstructors Defn
_ = [QName]
forall a. HasCallStack => a
__IMPOSSIBLE__

newtype Fields = Fields [(C.Name, Type)]
  deriving Fields
Fields -> Bool
Fields -> (Fields -> Bool) -> Null Fields
forall a. a -> (a -> Bool) -> Null a
$cempty :: Fields
empty :: Fields
$cnull :: Fields -> Bool
null :: Fields -> Bool
Null

-- | Did we encounter a simplifying reduction?
--   In terms of CIC, that would be a iota-reduction.
--   In terms of Agda, this is a constructor or literal
--   pattern that matched.
--   Just beta-reduction (substitution) or delta-reduction
--   (unfolding of definitions) does not count as simplifying?

data Simplification = YesSimplification | NoSimplification
  deriving (Simplification -> Simplification -> Bool
(Simplification -> Simplification -> Bool)
-> (Simplification -> Simplification -> Bool) -> Eq Simplification
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Simplification -> Simplification -> Bool
== :: Simplification -> Simplification -> Bool
$c/= :: Simplification -> Simplification -> Bool
/= :: Simplification -> Simplification -> Bool
Eq, Int -> Simplification -> ShowS
[Simplification] -> ShowS
Simplification -> String
(Int -> Simplification -> ShowS)
-> (Simplification -> String)
-> ([Simplification] -> ShowS)
-> Show Simplification
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Simplification -> ShowS
showsPrec :: Int -> Simplification -> ShowS
$cshow :: Simplification -> String
show :: Simplification -> String
$cshowList :: [Simplification] -> ShowS
showList :: [Simplification] -> ShowS
Show, (forall x. Simplification -> Rep Simplification x)
-> (forall x. Rep Simplification x -> Simplification)
-> Generic Simplification
forall x. Rep Simplification x -> Simplification
forall x. Simplification -> Rep Simplification x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Simplification -> Rep Simplification x
from :: forall x. Simplification -> Rep Simplification x
$cto :: forall x. Rep Simplification x -> Simplification
to :: forall x. Rep Simplification x -> Simplification
Generic)

instance Null Simplification where
  empty :: Simplification
empty = Simplification
NoSimplification
  null :: Simplification -> Bool
null  = (Simplification -> Simplification -> Bool
forall a. Eq a => a -> a -> Bool
== Simplification
NoSimplification)

instance Semigroup Simplification where
  Simplification
YesSimplification <> :: Simplification -> Simplification -> Simplification
<> Simplification
_ = Simplification
YesSimplification
  Simplification
NoSimplification  <> Simplification
s = Simplification
s

instance Monoid Simplification where
  mempty :: Simplification
mempty = Simplification
NoSimplification
  mappend :: Simplification -> Simplification -> Simplification
mappend = Simplification -> Simplification -> Simplification
forall a. Semigroup a => a -> a -> a
(<>)

data Reduced no yes
  = NoReduction no
  | YesReduction Simplification yes
  deriving (forall a b. (a -> b) -> Reduced no a -> Reduced no b)
-> (forall a b. a -> Reduced no b -> Reduced no a)
-> Functor (Reduced no)
forall a b. a -> Reduced no b -> Reduced no a
forall a b. (a -> b) -> Reduced no a -> Reduced no b
forall no a b. a -> Reduced no b -> Reduced no a
forall no a b. (a -> b) -> Reduced no a -> Reduced no b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall no a b. (a -> b) -> Reduced no a -> Reduced no b
fmap :: forall a b. (a -> b) -> Reduced no a -> Reduced no b
$c<$ :: forall no a b. a -> Reduced no b -> Reduced no a
<$ :: forall a b. a -> Reduced no b -> Reduced no a
Functor

redReturn :: a -> ReduceM (Reduced a' a)
redReturn :: forall a a'. a -> ReduceM (Reduced a' a)
redReturn = Reduced a' a -> ReduceM (Reduced a' a)
forall a. a -> ReduceM a
forall (m :: * -> *) a. Monad m => a -> m a
return (Reduced a' a -> ReduceM (Reduced a' a))
-> (a -> Reduced a' a) -> a -> ReduceM (Reduced a' a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Simplification -> a -> Reduced a' a
forall no yes. Simplification -> yes -> Reduced no yes
YesReduction Simplification
YesSimplification

-- | Conceptually: @redBind m f k = either (return . Left . f) k =<< m@

redBind :: ReduceM (Reduced a a') -> (a -> ReduceM b) ->
           (a' -> ReduceM (Reduced b b')) -> ReduceM (Reduced b b')
redBind :: forall a a' b b'.
ReduceM (Reduced a a')
-> (a -> ReduceM b)
-> (a' -> ReduceM (Reduced b b'))
-> ReduceM (Reduced b b')
redBind ReduceM (Reduced a a')
ma a -> ReduceM b
f a' -> ReduceM (Reduced b b')
k = do
  r <- ReduceM (Reduced a a')
ma
  case r of
    NoReduction a
x    -> b -> Reduced b b'
forall no yes. no -> Reduced no yes
NoReduction (b -> Reduced b b') -> ReduceM b -> ReduceM (Reduced b b')
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> a -> ReduceM b
f a
x
    YesReduction Simplification
_ a'
y -> a' -> ReduceM (Reduced b b')
k a'
y

-- | Three cases: 1. not reduced, 2. reduced, but blocked, 3. reduced, not blocked.
data IsReduced
  = NotReduced
  | Reduced    (Blocked ())

data MaybeReduced a = MaybeRed
  { forall a. MaybeReduced a -> IsReduced
isReduced     :: IsReduced
  , forall a. MaybeReduced a -> a
ignoreReduced :: a
  }
  deriving ((forall a b. (a -> b) -> MaybeReduced a -> MaybeReduced b)
-> (forall a b. a -> MaybeReduced b -> MaybeReduced a)
-> Functor MaybeReduced
forall a b. a -> MaybeReduced b -> MaybeReduced a
forall a b. (a -> b) -> MaybeReduced a -> MaybeReduced b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall a b. (a -> b) -> MaybeReduced a -> MaybeReduced b
fmap :: forall a b. (a -> b) -> MaybeReduced a -> MaybeReduced b
$c<$ :: forall a b. a -> MaybeReduced b -> MaybeReduced a
<$ :: forall a b. a -> MaybeReduced b -> MaybeReduced a
Functor)

instance IsProjElim e => IsProjElim (MaybeReduced e) where
  isProjElim :: MaybeReduced e -> Maybe (ProjOrigin, QName)
isProjElim = e -> Maybe (ProjOrigin, QName)
forall e. IsProjElim e => e -> Maybe (ProjOrigin, QName)
isProjElim (e -> Maybe (ProjOrigin, QName))
-> (MaybeReduced e -> e)
-> MaybeReduced e
-> Maybe (ProjOrigin, QName)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MaybeReduced e -> e
forall a. MaybeReduced a -> a
ignoreReduced

type MaybeReducedArgs = [MaybeReduced (Arg Term)]
type MaybeReducedElims = [MaybeReduced Elim]

notReduced :: a -> MaybeReduced a
notReduced :: forall a. a -> MaybeReduced a
notReduced a
x = IsReduced -> a -> MaybeReduced a
forall a. IsReduced -> a -> MaybeReduced a
MaybeRed IsReduced
NotReduced a
x

reduced :: Blocked (Arg Term) -> MaybeReduced (Arg Term)
reduced :: Blocked (Arg Term) -> MaybeReduced (Arg Term)
reduced Blocked (Arg Term)
b = IsReduced -> Arg Term -> MaybeReduced (Arg Term)
forall a. IsReduced -> a -> MaybeReduced a
MaybeRed (Blocked_ -> IsReduced
Reduced (Blocked_ -> IsReduced) -> Blocked_ -> IsReduced
forall a b. (a -> b) -> a -> b
$ () () -> Blocked (Arg Term) -> Blocked_
forall a b. a -> Blocked' Term b -> Blocked' Term a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Blocked (Arg Term)
b) (Arg Term -> MaybeReduced (Arg Term))
-> Arg Term -> MaybeReduced (Arg Term)
forall a b. (a -> b) -> a -> b
$ Blocked (Arg Term) -> Arg Term
forall t a. Blocked' t a -> a
ignoreBlocking Blocked (Arg Term)
b

-- | Controlling 'reduce'.
data AllowedReduction
  = ProjectionReductions     -- ^ (Projection and) projection-like functions may be reduced.
  | InlineReductions         -- ^ Functions marked INLINE may be reduced.
  | CopatternReductions      -- ^ Copattern definitions may be reduced.
  | FunctionReductions       -- ^ Non-recursive functions and primitives may be reduced.
  | RecursiveReductions      -- ^ Even recursive functions may be reduced.
  | LevelReductions          -- ^ Reduce @'Level'@ terms.
  | TypeLevelReductions      -- ^ Allow @allReductions@ in types, even
                             --   if not allowed at term level (used
                             --   by confluence checker)
  | UnconfirmedReductions    -- ^ Functions whose termination has not (yet) been confirmed.
  | NonTerminatingReductions -- ^ Functions that have failed termination checking.
  deriving (Int -> AllowedReduction -> ShowS
[AllowedReduction] -> ShowS
AllowedReduction -> String
(Int -> AllowedReduction -> ShowS)
-> (AllowedReduction -> String)
-> ([AllowedReduction] -> ShowS)
-> Show AllowedReduction
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AllowedReduction -> ShowS
showsPrec :: Int -> AllowedReduction -> ShowS
$cshow :: AllowedReduction -> String
show :: AllowedReduction -> String
$cshowList :: [AllowedReduction] -> ShowS
showList :: [AllowedReduction] -> ShowS
Show, AllowedReduction -> AllowedReduction -> Bool
(AllowedReduction -> AllowedReduction -> Bool)
-> (AllowedReduction -> AllowedReduction -> Bool)
-> Eq AllowedReduction
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AllowedReduction -> AllowedReduction -> Bool
== :: AllowedReduction -> AllowedReduction -> Bool
$c/= :: AllowedReduction -> AllowedReduction -> Bool
/= :: AllowedReduction -> AllowedReduction -> Bool
Eq, Eq AllowedReduction
Eq AllowedReduction =>
(AllowedReduction -> AllowedReduction -> Ordering)
-> (AllowedReduction -> AllowedReduction -> Bool)
-> (AllowedReduction -> AllowedReduction -> Bool)
-> (AllowedReduction -> AllowedReduction -> Bool)
-> (AllowedReduction -> AllowedReduction -> Bool)
-> (AllowedReduction -> AllowedReduction -> AllowedReduction)
-> (AllowedReduction -> AllowedReduction -> AllowedReduction)
-> Ord AllowedReduction
AllowedReduction -> AllowedReduction -> Bool
AllowedReduction -> AllowedReduction -> Ordering
AllowedReduction -> AllowedReduction -> AllowedReduction
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: AllowedReduction -> AllowedReduction -> Ordering
compare :: AllowedReduction -> AllowedReduction -> Ordering
$c< :: AllowedReduction -> AllowedReduction -> Bool
< :: AllowedReduction -> AllowedReduction -> Bool
$c<= :: AllowedReduction -> AllowedReduction -> Bool
<= :: AllowedReduction -> AllowedReduction -> Bool
$c> :: AllowedReduction -> AllowedReduction -> Bool
> :: AllowedReduction -> AllowedReduction -> Bool
$c>= :: AllowedReduction -> AllowedReduction -> Bool
>= :: AllowedReduction -> AllowedReduction -> Bool
$cmax :: AllowedReduction -> AllowedReduction -> AllowedReduction
max :: AllowedReduction -> AllowedReduction -> AllowedReduction
$cmin :: AllowedReduction -> AllowedReduction -> AllowedReduction
min :: AllowedReduction -> AllowedReduction -> AllowedReduction
Ord, Int -> AllowedReduction
AllowedReduction -> Int
AllowedReduction -> [AllowedReduction]
AllowedReduction -> AllowedReduction
AllowedReduction -> AllowedReduction -> [AllowedReduction]
AllowedReduction
-> AllowedReduction -> AllowedReduction -> [AllowedReduction]
(AllowedReduction -> AllowedReduction)
-> (AllowedReduction -> AllowedReduction)
-> (Int -> AllowedReduction)
-> (AllowedReduction -> Int)
-> (AllowedReduction -> [AllowedReduction])
-> (AllowedReduction -> AllowedReduction -> [AllowedReduction])
-> (AllowedReduction -> AllowedReduction -> [AllowedReduction])
-> (AllowedReduction
    -> AllowedReduction -> AllowedReduction -> [AllowedReduction])
-> Enum AllowedReduction
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: AllowedReduction -> AllowedReduction
succ :: AllowedReduction -> AllowedReduction
$cpred :: AllowedReduction -> AllowedReduction
pred :: AllowedReduction -> AllowedReduction
$ctoEnum :: Int -> AllowedReduction
toEnum :: Int -> AllowedReduction
$cfromEnum :: AllowedReduction -> Int
fromEnum :: AllowedReduction -> Int
$cenumFrom :: AllowedReduction -> [AllowedReduction]
enumFrom :: AllowedReduction -> [AllowedReduction]
$cenumFromThen :: AllowedReduction -> AllowedReduction -> [AllowedReduction]
enumFromThen :: AllowedReduction -> AllowedReduction -> [AllowedReduction]
$cenumFromTo :: AllowedReduction -> AllowedReduction -> [AllowedReduction]
enumFromTo :: AllowedReduction -> AllowedReduction -> [AllowedReduction]
$cenumFromThenTo :: AllowedReduction
-> AllowedReduction -> AllowedReduction -> [AllowedReduction]
enumFromThenTo :: AllowedReduction
-> AllowedReduction -> AllowedReduction -> [AllowedReduction]
Enum, AllowedReduction
AllowedReduction -> AllowedReduction -> Bounded AllowedReduction
forall a. a -> a -> Bounded a
$cminBound :: AllowedReduction
minBound :: AllowedReduction
$cmaxBound :: AllowedReduction
maxBound :: AllowedReduction
Bounded, Ord AllowedReduction
Ord AllowedReduction =>
((AllowedReduction, AllowedReduction) -> [AllowedReduction])
-> ((AllowedReduction, AllowedReduction)
    -> AllowedReduction -> Int)
-> ((AllowedReduction, AllowedReduction)
    -> AllowedReduction -> Int)
-> ((AllowedReduction, AllowedReduction)
    -> AllowedReduction -> Bool)
-> ((AllowedReduction, AllowedReduction) -> Int)
-> ((AllowedReduction, AllowedReduction) -> Int)
-> Ix AllowedReduction
(AllowedReduction, AllowedReduction) -> Int
(AllowedReduction, AllowedReduction) -> [AllowedReduction]
(AllowedReduction, AllowedReduction) -> AllowedReduction -> Bool
(AllowedReduction, AllowedReduction) -> AllowedReduction -> Int
forall a.
Ord a =>
((a, a) -> [a])
-> ((a, a) -> a -> Int)
-> ((a, a) -> a -> Int)
-> ((a, a) -> a -> Bool)
-> ((a, a) -> Int)
-> ((a, a) -> Int)
-> Ix a
$crange :: (AllowedReduction, AllowedReduction) -> [AllowedReduction]
range :: (AllowedReduction, AllowedReduction) -> [AllowedReduction]
$cindex :: (AllowedReduction, AllowedReduction) -> AllowedReduction -> Int
index :: (AllowedReduction, AllowedReduction) -> AllowedReduction -> Int
$cunsafeIndex :: (AllowedReduction, AllowedReduction) -> AllowedReduction -> Int
unsafeIndex :: (AllowedReduction, AllowedReduction) -> AllowedReduction -> Int
$cinRange :: (AllowedReduction, AllowedReduction) -> AllowedReduction -> Bool
inRange :: (AllowedReduction, AllowedReduction) -> AllowedReduction -> Bool
$crangeSize :: (AllowedReduction, AllowedReduction) -> Int
rangeSize :: (AllowedReduction, AllowedReduction) -> Int
$cunsafeRangeSize :: (AllowedReduction, AllowedReduction) -> Int
unsafeRangeSize :: (AllowedReduction, AllowedReduction) -> Int
Ix, (forall x. AllowedReduction -> Rep AllowedReduction x)
-> (forall x. Rep AllowedReduction x -> AllowedReduction)
-> Generic AllowedReduction
forall x. Rep AllowedReduction x -> AllowedReduction
forall x. AllowedReduction -> Rep AllowedReduction x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. AllowedReduction -> Rep AllowedReduction x
from :: forall x. AllowedReduction -> Rep AllowedReduction x
$cto :: forall x. Rep AllowedReduction x -> AllowedReduction
to :: forall x. Rep AllowedReduction x -> AllowedReduction
Generic)

instance SmallSet.SmallSetElement AllowedReduction

type AllowedReductions = SmallSet AllowedReduction

-- | Not quite all reductions (skip non-terminating reductions)
allReductions :: AllowedReductions
allReductions :: AllowedReductions
allReductions = AllowedReduction -> AllowedReductions -> AllowedReductions
forall a. SmallSetElement a => a -> SmallSet a -> SmallSet a
SmallSet.delete AllowedReduction
NonTerminatingReductions AllowedReductions
reallyAllReductions

reallyAllReductions :: AllowedReductions
reallyAllReductions :: AllowedReductions
reallyAllReductions = AllowedReductions
forall a. SmallSet a
SmallSet.total

data ReduceDefs
  = OnlyReduceDefs (Set QName)
  | DontReduceDefs (Set QName)
  deriving (forall x. ReduceDefs -> Rep ReduceDefs x)
-> (forall x. Rep ReduceDefs x -> ReduceDefs) -> Generic ReduceDefs
forall x. Rep ReduceDefs x -> ReduceDefs
forall x. ReduceDefs -> Rep ReduceDefs x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ReduceDefs -> Rep ReduceDefs x
from :: forall x. ReduceDefs -> Rep ReduceDefs x
$cto :: forall x. Rep ReduceDefs x -> ReduceDefs
to :: forall x. Rep ReduceDefs x -> ReduceDefs
Generic

reduceAllDefs :: ReduceDefs
reduceAllDefs :: ReduceDefs
reduceAllDefs = Set QName -> ReduceDefs
DontReduceDefs Set QName
forall a. Null a => a
empty

locallyReduceDefs :: MonadTCEnv m => ReduceDefs -> m a -> m a
locallyReduceDefs :: forall (m :: * -> *) a. MonadTCEnv m => ReduceDefs -> m a -> m a
locallyReduceDefs = Lens' TCEnv ReduceDefs -> (ReduceDefs -> ReduceDefs) -> m a -> m a
forall (m :: * -> *) a b.
MonadTCEnv m =>
Lens' TCEnv a -> (a -> a) -> m b -> m b
locallyTC (ReduceDefs -> f ReduceDefs) -> TCEnv -> f TCEnv
Lens' TCEnv ReduceDefs
eReduceDefs ((ReduceDefs -> ReduceDefs) -> m a -> m a)
-> (ReduceDefs -> ReduceDefs -> ReduceDefs)
-> ReduceDefs
-> m a
-> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ReduceDefs -> ReduceDefs -> ReduceDefs
forall a b. a -> b -> a
const

locallyReduceAllDefs :: MonadTCEnv m => m a -> m a
locallyReduceAllDefs :: forall (m :: * -> *) a. MonadTCEnv m => m a -> m a
locallyReduceAllDefs = ReduceDefs -> m a -> m a
forall (m :: * -> *) a. MonadTCEnv m => ReduceDefs -> m a -> m a
locallyReduceDefs ReduceDefs
reduceAllDefs

{-# INLINE shouldReduceDef #-}
shouldReduceDef :: (MonadTCEnv m) => QName -> m Bool
shouldReduceDef :: forall (m :: * -> *). MonadTCEnv m => QName -> m Bool
shouldReduceDef QName
f = Lens' TCEnv ReduceDefs -> m ReduceDefs
forall (m :: * -> *) a. MonadTCEnv m => Lens' TCEnv a -> m a
viewTC (ReduceDefs -> f ReduceDefs) -> TCEnv -> f TCEnv
Lens' TCEnv ReduceDefs
eReduceDefs m ReduceDefs -> (ReduceDefs -> Bool) -> m Bool
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \case
  OnlyReduceDefs Set QName
defs -> QName
f QName -> Set QName -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set QName
defs
  DontReduceDefs Set QName
defs -> Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ QName
f QName -> Set QName -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set QName
defs

toReduceDefs :: (Bool, [QName]) -> ReduceDefs
toReduceDefs :: (Bool, [QName]) -> ReduceDefs
toReduceDefs (Bool
True,  [QName]
ns) = Set QName -> ReduceDefs
OnlyReduceDefs ([QName] -> Set QName
forall a. Ord a => [a] -> Set a
Data.Set.fromList [QName]
ns)
toReduceDefs (Bool
False, [QName]
ns) = Set QName -> ReduceDefs
DontReduceDefs ([QName] -> Set QName
forall a. Ord a => [a] -> Set a
Data.Set.fromList [QName]
ns)

fromReduceDefs :: ReduceDefs -> (Bool, [QName])
fromReduceDefs :: ReduceDefs -> (Bool, [QName])
fromReduceDefs (OnlyReduceDefs Set QName
ns) = (Bool
True,  Set QName -> [QName]
forall a. Set a -> [a]
toList Set QName
ns)
fromReduceDefs (DontReduceDefs Set QName
ns) = (Bool
False, Set QName -> [QName]
forall a. Set a -> [a]
toList Set QName
ns)

locallyReconstructed :: MonadTCEnv m => m a -> m a
locallyReconstructed :: forall (m :: * -> *) a. MonadTCEnv m => m a -> m a
locallyReconstructed = Lens' TCEnv Bool -> (Bool -> Bool) -> m a -> m a
forall (m :: * -> *) a b.
MonadTCEnv m =>
Lens' TCEnv a -> (a -> a) -> m b -> m b
locallyTC (Bool -> f Bool) -> TCEnv -> f TCEnv
Lens' TCEnv Bool
eReconstructed ((Bool -> Bool) -> m a -> m a)
-> (Bool -> Bool -> Bool) -> Bool -> m a -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> Bool -> Bool
forall a b. a -> b -> a
const (Bool -> m a -> m a) -> Bool -> m a -> m a
forall a b. (a -> b) -> a -> b
$ Bool
True

isReconstructed :: (MonadTCEnv m) => m Bool
isReconstructed :: forall (m :: * -> *). MonadTCEnv m => m Bool
isReconstructed = Lens' TCEnv Bool -> m Bool
forall (m :: * -> *) a. MonadTCEnv m => Lens' TCEnv a -> m a
viewTC (Bool -> f Bool) -> TCEnv -> f TCEnv
Lens' TCEnv Bool
eReconstructed

-- | Primitives

data PrimitiveImpl = PrimImpl Type PrimFun

data PrimFun = PrimFun
  { PrimFun -> QName
primFunName           :: QName
  , PrimFun -> Int
primFunArity          :: Arity
  , PrimFun -> [Occurrence]
primFunArgOccurrences :: [Occurrence]
    -- ^ See 'defArgOccurrences'.
  , PrimFun -> Args -> Int -> ReduceM (Reduced MaybeReducedArgs Term)
primFunImplementation :: [Arg Term] -> Int -> ReduceM (Reduced MaybeReducedArgs Term)
  }
  deriving (forall x. PrimFun -> Rep PrimFun x)
-> (forall x. Rep PrimFun x -> PrimFun) -> Generic PrimFun
forall x. Rep PrimFun x -> PrimFun
forall x. PrimFun -> Rep PrimFun x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. PrimFun -> Rep PrimFun x
from :: forall x. PrimFun -> Rep PrimFun x
$cto :: forall x. Rep PrimFun x -> PrimFun
to :: forall x. Rep PrimFun x -> PrimFun
Generic

primFun :: QName -> Arity -> ([Arg Term] -> ReduceM (Reduced MaybeReducedArgs Term)) -> PrimFun
primFun :: QName
-> Int
-> (Args -> ReduceM (Reduced MaybeReducedArgs Term))
-> PrimFun
primFun QName
q Int
ar Args -> ReduceM (Reduced MaybeReducedArgs Term)
imp = QName
-> Int
-> [Occurrence]
-> (Args -> Int -> ReduceM (Reduced MaybeReducedArgs Term))
-> PrimFun
PrimFun QName
q Int
ar [] (\Args
args Int
_ -> Args -> ReduceM (Reduced MaybeReducedArgs Term)
imp Args
args)

defClauses :: Definition -> [Clause]
defClauses :: Definition -> [Clause]
defClauses Defn{theDef :: Definition -> Defn
theDef = Function{funClauses :: Defn -> [Clause]
funClauses = [Clause]
cs}}        = [Clause]
cs
defClauses Defn{theDef :: Definition -> Defn
theDef = Primitive{primClauses :: Defn -> [Clause]
primClauses = [Clause]
cs}}      = [Clause]
cs
defClauses Defn{theDef :: Definition -> Defn
theDef = Datatype{dataClause :: Defn -> Maybe Clause
dataClause = Just Clause
c}}    = [Clause
c]
defClauses Defn{theDef :: Definition -> Defn
theDef = Record{recClause :: Defn -> Maybe Clause
recClause = Just Clause
c}}       = [Clause
c]
defClauses Definition
_                                               = []

defCompiled :: Definition -> Maybe CompiledClauses
defCompiled :: Definition -> Maybe CompiledClauses
defCompiled Defn{theDef :: Definition -> Defn
theDef = Function {funCompiled :: Defn -> Maybe CompiledClauses
funCompiled  = Maybe CompiledClauses
mcc}} = Maybe CompiledClauses
mcc
defCompiled Defn{theDef :: Definition -> Defn
theDef = Primitive{primCompiled :: Defn -> Maybe CompiledClauses
primCompiled = Maybe CompiledClauses
mcc}} = Maybe CompiledClauses
mcc
defCompiled Definition
_ = Maybe CompiledClauses
forall a. Maybe a
Nothing

defParameters :: Definition -> Maybe Nat
defParameters :: Definition -> Maybe Int
defParameters Defn{theDef :: Definition -> Defn
theDef = Datatype{dataPars :: Defn -> Int
dataPars = Int
n}} = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
n
defParameters Defn{theDef :: Definition -> Defn
theDef = Record  {recPars :: Defn -> Int
recPars  = Int
n}} = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
n
defParameters Definition
_                                     = Maybe Int
forall a. Maybe a
Nothing

defInverse :: Definition -> FunctionInverse
defInverse :: Definition -> FunctionInverse
defInverse Defn{theDef :: Definition -> Defn
theDef = Function { funInv :: Defn -> FunctionInverse
funInv  = FunctionInverse
inv }} = FunctionInverse
inv
defInverse Defn{theDef :: Definition -> Defn
theDef = Primitive{ primInv :: Defn -> FunctionInverse
primInv = FunctionInverse
inv }} = FunctionInverse
inv
defInverse Definition
_                                         = FunctionInverse
forall c. FunctionInverse' c
NotInjective

defCompilerPragmas :: BackendName -> Definition -> [CompilerPragma]
defCompilerPragmas :: ShortText -> Definition -> [CompilerPragma]
defCompilerPragmas ShortText
b = [CompilerPragma] -> [CompilerPragma]
forall a. [a] -> [a]
reverse ([CompilerPragma] -> [CompilerPragma])
-> (Definition -> [CompilerPragma])
-> Definition
-> [CompilerPragma]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [CompilerPragma] -> Maybe [CompilerPragma] -> [CompilerPragma]
forall a. a -> Maybe a -> a
fromMaybe [] (Maybe [CompilerPragma] -> [CompilerPragma])
-> (Definition -> Maybe [CompilerPragma])
-> Definition
-> [CompilerPragma]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ShortText -> CompiledRepresentation -> Maybe [CompilerPragma]
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ShortText
b (CompiledRepresentation -> Maybe [CompilerPragma])
-> (Definition -> CompiledRepresentation)
-> Definition
-> Maybe [CompilerPragma]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Definition -> CompiledRepresentation
defCompiledRep
  -- reversed because we add new pragmas to the front of the list

-- | Has the definition failed the termination checker?
defNonterminating :: Definition -> Bool
defNonterminating :: Definition -> Bool
defNonterminating Defn{theDef :: Definition -> Defn
theDef = Function{funTerminates :: Defn -> Maybe Bool
funTerminates = Just Bool
False}} = Bool
True
defNonterminating Definition
_                                                   = Bool
False

-- | Has the definition not termination checked or did the check fail?
defTerminationUnconfirmed :: Definition -> Bool
defTerminationUnconfirmed :: Definition -> Bool
defTerminationUnconfirmed Defn{theDef :: Definition -> Defn
theDef = Function{funTerminates :: Defn -> Maybe Bool
funTerminates = Just Bool
True}} = Bool
False
defTerminationUnconfirmed Defn{theDef :: Definition -> Defn
theDef = Function{funTerminates :: Defn -> Maybe Bool
funTerminates = Maybe Bool
_        }} = Bool
True
defTerminationUnconfirmed Definition
_ = Bool
False

defAbstract :: Definition -> IsAbstract
defAbstract :: Definition -> IsAbstract
defAbstract Definition
def = case Definition -> Defn
theDef Definition
def of
    AxiomDefn AxiomData
_         -> IsAbstract
ConcreteDef
    DataOrRecSigDefn DataOrRecSigData
_  -> IsAbstract
ConcreteDef
    GeneralizableVar NumGeneralizableArgs
_  -> IsAbstract
ConcreteDef
    AbstractDefn Defn
_      -> IsAbstract
AbstractDef
    FunctionDefn FunctionData
d      -> FunctionData
d FunctionData
-> Getting IsAbstract FunctionData IsAbstract -> IsAbstract
forall s a. s -> Getting a s a -> a
^. Getting IsAbstract FunctionData IsAbstract
Lens' FunctionData IsAbstract
funAbstr_
    DatatypeDefn DatatypeData
d      -> DatatypeData -> IsAbstract
_dataAbstr DatatypeData
d
    RecordDefn RecordData
d        -> RecordData -> IsAbstract
_recAbstr RecordData
d
    ConstructorDefn ConstructorData
d   -> ConstructorData -> IsAbstract
_conAbstr ConstructorData
d
    PrimitiveDefn PrimitiveData
d     -> PrimitiveData -> IsAbstract
_primAbstr PrimitiveData
d
    PrimitiveSortDefn PrimitiveSortData
_ -> IsAbstract
ConcreteDef

defOpaque :: Definition -> IsOpaque
defOpaque :: Definition -> IsOpaque
defOpaque Definition
d = case Definition -> Defn
theDef Definition
d of
    -- These two can be opaque:
    Function{funOpaque :: Defn -> IsOpaque
funOpaque=IsOpaque
o}     -> IsOpaque
o
    Primitive{primOpaque :: Defn -> IsOpaque
primOpaque=IsOpaque
o}   -> IsOpaque
o

    -- Doesn't matter whether or not it's opaque:
    Axiom{}                   -> IsOpaque
TransparentDef
    -- Concreteness is orthogonal to opacity:
    AbstractDefn{}            -> IsOpaque
TransparentDef

    -- None of these are supported in opaque blocks:
    DataOrRecSig{}            -> IsOpaque
TransparentDef
    GeneralizableVar{}        -> IsOpaque
TransparentDef
    Datatype{}                -> IsOpaque
TransparentDef
    Record{}                  -> IsOpaque
TransparentDef
    Constructor{}             -> IsOpaque
TransparentDef
    PrimitiveSort{}           -> IsOpaque
TransparentDef

defForced :: Definition -> [IsForced]
defForced :: Definition -> [IsForced]
defForced Definition
d = case Definition -> Defn
theDef Definition
d of
    Constructor{conForced :: Defn -> [IsForced]
conForced = [IsForced]
fs} -> [IsForced]
fs
    Axiom{}                     -> []
    DataOrRecSig{}              -> []
    GeneralizableVar{}          -> []
    AbstractDefn{}              -> []
    Function{}                  -> []
    Datatype{}                  -> []
    Record{}                    -> []
    Primitive{}                 -> []
    PrimitiveSort{}             -> []

----------------------------------------------------------------------------------------------------
-- ** Injectivity
----------------------------------------------------------------------------------------------------

type FunctionInverse = FunctionInverse' Clause
type InversionMap c = Map TermHead [c]

data FunctionInverse' c
  = NotInjective
  | Inverse (InversionMap c)
  deriving (Int -> FunctionInverse' c -> ShowS
[FunctionInverse' c] -> ShowS
FunctionInverse' c -> String
(Int -> FunctionInverse' c -> ShowS)
-> (FunctionInverse' c -> String)
-> ([FunctionInverse' c] -> ShowS)
-> Show (FunctionInverse' c)
forall c. Show c => Int -> FunctionInverse' c -> ShowS
forall c. Show c => [FunctionInverse' c] -> ShowS
forall c. Show c => FunctionInverse' c -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall c. Show c => Int -> FunctionInverse' c -> ShowS
showsPrec :: Int -> FunctionInverse' c -> ShowS
$cshow :: forall c. Show c => FunctionInverse' c -> String
show :: FunctionInverse' c -> String
$cshowList :: forall c. Show c => [FunctionInverse' c] -> ShowS
showList :: [FunctionInverse' c] -> ShowS
Show, (forall a b. (a -> b) -> FunctionInverse' a -> FunctionInverse' b)
-> (forall a b. a -> FunctionInverse' b -> FunctionInverse' a)
-> Functor FunctionInverse'
forall a b. a -> FunctionInverse' b -> FunctionInverse' a
forall a b. (a -> b) -> FunctionInverse' a -> FunctionInverse' b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall a b. (a -> b) -> FunctionInverse' a -> FunctionInverse' b
fmap :: forall a b. (a -> b) -> FunctionInverse' a -> FunctionInverse' b
$c<$ :: forall a b. a -> FunctionInverse' b -> FunctionInverse' a
<$ :: forall a b. a -> FunctionInverse' b -> FunctionInverse' a
Functor, (forall x. FunctionInverse' c -> Rep (FunctionInverse' c) x)
-> (forall x. Rep (FunctionInverse' c) x -> FunctionInverse' c)
-> Generic (FunctionInverse' c)
forall x. Rep (FunctionInverse' c) x -> FunctionInverse' c
forall x. FunctionInverse' c -> Rep (FunctionInverse' c) x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
forall c x. Rep (FunctionInverse' c) x -> FunctionInverse' c
forall c x. FunctionInverse' c -> Rep (FunctionInverse' c) x
$cfrom :: forall c x. FunctionInverse' c -> Rep (FunctionInverse' c) x
from :: forall x. FunctionInverse' c -> Rep (FunctionInverse' c) x
$cto :: forall c x. Rep (FunctionInverse' c) x -> FunctionInverse' c
to :: forall x. Rep (FunctionInverse' c) x -> FunctionInverse' c
Generic)

data TermHead = SortHead
              | PiHead
              | ConsHead QName
              | VarHead Nat
              | UnknownHead
  deriving (TermHead -> TermHead -> Bool
(TermHead -> TermHead -> Bool)
-> (TermHead -> TermHead -> Bool) -> Eq TermHead
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: TermHead -> TermHead -> Bool
== :: TermHead -> TermHead -> Bool
$c/= :: TermHead -> TermHead -> Bool
/= :: TermHead -> TermHead -> Bool
Eq, Eq TermHead
Eq TermHead =>
(TermHead -> TermHead -> Ordering)
-> (TermHead -> TermHead -> Bool)
-> (TermHead -> TermHead -> Bool)
-> (TermHead -> TermHead -> Bool)
-> (TermHead -> TermHead -> Bool)
-> (TermHead -> TermHead -> TermHead)
-> (TermHead -> TermHead -> TermHead)
-> Ord TermHead
TermHead -> TermHead -> Bool
TermHead -> TermHead -> Ordering
TermHead -> TermHead -> TermHead
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: TermHead -> TermHead -> Ordering
compare :: TermHead -> TermHead -> Ordering
$c< :: TermHead -> TermHead -> Bool
< :: TermHead -> TermHead -> Bool
$c<= :: TermHead -> TermHead -> Bool
<= :: TermHead -> TermHead -> Bool
$c> :: TermHead -> TermHead -> Bool
> :: TermHead -> TermHead -> Bool
$c>= :: TermHead -> TermHead -> Bool
>= :: TermHead -> TermHead -> Bool
$cmax :: TermHead -> TermHead -> TermHead
max :: TermHead -> TermHead -> TermHead
$cmin :: TermHead -> TermHead -> TermHead
min :: TermHead -> TermHead -> TermHead
Ord, Int -> TermHead -> ShowS
[TermHead] -> ShowS
TermHead -> String
(Int -> TermHead -> ShowS)
-> (TermHead -> String) -> ([TermHead] -> ShowS) -> Show TermHead
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TermHead -> ShowS
showsPrec :: Int -> TermHead -> ShowS
$cshow :: TermHead -> String
show :: TermHead -> String
$cshowList :: [TermHead] -> ShowS
showList :: [TermHead] -> ShowS
Show, (forall x. TermHead -> Rep TermHead x)
-> (forall x. Rep TermHead x -> TermHead) -> Generic TermHead
forall x. Rep TermHead x -> TermHead
forall x. TermHead -> Rep TermHead x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TermHead -> Rep TermHead x
from :: forall x. TermHead -> Rep TermHead x
$cto :: forall x. Rep TermHead x -> TermHead
to :: forall x. Rep TermHead x -> TermHead
Generic)

instance Pretty TermHead where
  pretty :: TermHead -> Doc
pretty = \ case
    TermHead
SortHead    -> Doc
"SortHead"
    TermHead
PiHead      -> Doc
"PiHead"
    ConsHead QName
q  -> Doc
"ConsHead" Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> QName -> Doc
forall a. Pretty a => a -> Doc
pretty QName
q
    VarHead Int
i   -> String -> Doc
forall a. String -> Doc a
text (String
"VarHead " String -> ShowS
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
i)
    TermHead
UnknownHead -> Doc
"UnknownHead"

----------------------------------------------------------------------------------------------------
-- ** Mutual blocks
----------------------------------------------------------------------------------------------------

newtype MutualId = MutualId Word32
  deriving (MutualId -> MutualId -> Bool
(MutualId -> MutualId -> Bool)
-> (MutualId -> MutualId -> Bool) -> Eq MutualId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: MutualId -> MutualId -> Bool
== :: MutualId -> MutualId -> Bool
$c/= :: MutualId -> MutualId -> Bool
/= :: MutualId -> MutualId -> Bool
Eq, Eq MutualId
Eq MutualId =>
(MutualId -> MutualId -> Ordering)
-> (MutualId -> MutualId -> Bool)
-> (MutualId -> MutualId -> Bool)
-> (MutualId -> MutualId -> Bool)
-> (MutualId -> MutualId -> Bool)
-> (MutualId -> MutualId -> MutualId)
-> (MutualId -> MutualId -> MutualId)
-> Ord MutualId
MutualId -> MutualId -> Bool
MutualId -> MutualId -> Ordering
MutualId -> MutualId -> MutualId
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: MutualId -> MutualId -> Ordering
compare :: MutualId -> MutualId -> Ordering
$c< :: MutualId -> MutualId -> Bool
< :: MutualId -> MutualId -> Bool
$c<= :: MutualId -> MutualId -> Bool
<= :: MutualId -> MutualId -> Bool
$c> :: MutualId -> MutualId -> Bool
> :: MutualId -> MutualId -> Bool
$c>= :: MutualId -> MutualId -> Bool
>= :: MutualId -> MutualId -> Bool
$cmax :: MutualId -> MutualId -> MutualId
max :: MutualId -> MutualId -> MutualId
$cmin :: MutualId -> MutualId -> MutualId
min :: MutualId -> MutualId -> MutualId
Ord, Int -> MutualId -> ShowS
[MutualId] -> ShowS
MutualId -> String
(Int -> MutualId -> ShowS)
-> (MutualId -> String) -> ([MutualId] -> ShowS) -> Show MutualId
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MutualId -> ShowS
showsPrec :: Int -> MutualId -> ShowS
$cshow :: MutualId -> String
show :: MutualId -> String
$cshowList :: [MutualId] -> ShowS
showList :: [MutualId] -> ShowS
Show, Integer -> MutualId
MutualId -> MutualId
MutualId -> MutualId -> MutualId
(MutualId -> MutualId -> MutualId)
-> (MutualId -> MutualId -> MutualId)
-> (MutualId -> MutualId -> MutualId)
-> (MutualId -> MutualId)
-> (MutualId -> MutualId)
-> (MutualId -> MutualId)
-> (Integer -> MutualId)
-> Num MutualId
forall a.
(a -> a -> a)
-> (a -> a -> a)
-> (a -> a -> a)
-> (a -> a)
-> (a -> a)
-> (a -> a)
-> (Integer -> a)
-> Num a
$c+ :: MutualId -> MutualId -> MutualId
+ :: MutualId -> MutualId -> MutualId
$c- :: MutualId -> MutualId -> MutualId
- :: MutualId -> MutualId -> MutualId
$c* :: MutualId -> MutualId -> MutualId
* :: MutualId -> MutualId -> MutualId
$cnegate :: MutualId -> MutualId
negate :: MutualId -> MutualId
$cabs :: MutualId -> MutualId
abs :: MutualId -> MutualId
$csignum :: MutualId -> MutualId
signum :: MutualId -> MutualId
$cfromInteger :: Integer -> MutualId
fromInteger :: Integer -> MutualId
Num, Int -> MutualId
MutualId -> Int
MutualId -> [MutualId]
MutualId -> MutualId
MutualId -> MutualId -> [MutualId]
MutualId -> MutualId -> MutualId -> [MutualId]
(MutualId -> MutualId)
-> (MutualId -> MutualId)
-> (Int -> MutualId)
-> (MutualId -> Int)
-> (MutualId -> [MutualId])
-> (MutualId -> MutualId -> [MutualId])
-> (MutualId -> MutualId -> [MutualId])
-> (MutualId -> MutualId -> MutualId -> [MutualId])
-> Enum MutualId
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: MutualId -> MutualId
succ :: MutualId -> MutualId
$cpred :: MutualId -> MutualId
pred :: MutualId -> MutualId
$ctoEnum :: Int -> MutualId
toEnum :: Int -> MutualId
$cfromEnum :: MutualId -> Int
fromEnum :: MutualId -> Int
$cenumFrom :: MutualId -> [MutualId]
enumFrom :: MutualId -> [MutualId]
$cenumFromThen :: MutualId -> MutualId -> [MutualId]
enumFromThen :: MutualId -> MutualId -> [MutualId]
$cenumFromTo :: MutualId -> MutualId -> [MutualId]
enumFromTo :: MutualId -> MutualId -> [MutualId]
$cenumFromThenTo :: MutualId -> MutualId -> MutualId -> [MutualId]
enumFromThenTo :: MutualId -> MutualId -> MutualId -> [MutualId]
Enum, MutualId -> ()
(MutualId -> ()) -> NFData MutualId
forall a. (a -> ()) -> NFData a
$crnf :: MutualId -> ()
rnf :: MutualId -> ()
NFData)

instance Pretty MutualId where
  pretty :: MutualId -> Doc
pretty (MutualId Word32
i) = Word32 -> Doc
forall a. Pretty a => a -> Doc
pretty Word32
i

-- | Map 'MutualId' to 'MutualBlock'.
type MutualBlocks = IntMap MutualBlock

-- | A mutual block of names in the signature.
data MutualBlock = MutualBlock
  { MutualBlock -> MutualInfo
mutualInfo  :: MutualInfo
    -- ^ The original info of the mutual block.
  , MutualBlock -> Set QName
mutualNames :: Set QName
  } deriving (Int -> MutualBlock -> ShowS
[MutualBlock] -> ShowS
MutualBlock -> String
(Int -> MutualBlock -> ShowS)
-> (MutualBlock -> String)
-> ([MutualBlock] -> ShowS)
-> Show MutualBlock
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MutualBlock -> ShowS
showsPrec :: Int -> MutualBlock -> ShowS
$cshow :: MutualBlock -> String
show :: MutualBlock -> String
$cshowList :: [MutualBlock] -> ShowS
showList :: [MutualBlock] -> ShowS
Show, MutualBlock -> MutualBlock -> Bool
(MutualBlock -> MutualBlock -> Bool)
-> (MutualBlock -> MutualBlock -> Bool) -> Eq MutualBlock
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: MutualBlock -> MutualBlock -> Bool
== :: MutualBlock -> MutualBlock -> Bool
$c/= :: MutualBlock -> MutualBlock -> Bool
/= :: MutualBlock -> MutualBlock -> Bool
Eq, (forall x. MutualBlock -> Rep MutualBlock x)
-> (forall x. Rep MutualBlock x -> MutualBlock)
-> Generic MutualBlock
forall x. Rep MutualBlock x -> MutualBlock
forall x. MutualBlock -> Rep MutualBlock x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. MutualBlock -> Rep MutualBlock x
from :: forall x. MutualBlock -> Rep MutualBlock x
$cto :: forall x. Rep MutualBlock x -> MutualBlock
to :: forall x. Rep MutualBlock x -> MutualBlock
Generic)

instance Null MutualBlock where
  empty :: MutualBlock
empty = MutualInfo -> Set QName -> MutualBlock
MutualBlock MutualInfo
forall a. Null a => a
empty Set QName
forall a. Null a => a
empty

----------------------------------------------------------------------------------------------------
-- ** Statistics
----------------------------------------------------------------------------------------------------

-- | 'Statistics' is a collection of arbitrary string counters. The keys
-- that can be found in the map depend on what profiling options were
-- given.
data Statistics = Statistics
  { Statistics -> HashMap String (Sum Word64)
statTicks :: !(HashMap String (Sum Word64))
    -- ^ Tally counters, which should be added when merging.
  , Statistics -> HashMap String (Max Word64)
statMaxes :: !(HashMap String (Max Word64))
    -- ^ Record counters, which
  }
  deriving (Int -> Statistics -> ShowS
[Statistics] -> ShowS
Statistics -> String
(Int -> Statistics -> ShowS)
-> (Statistics -> String)
-> ([Statistics] -> ShowS)
-> Show Statistics
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Statistics -> ShowS
showsPrec :: Int -> Statistics -> ShowS
$cshow :: Statistics -> String
show :: Statistics -> String
$cshowList :: [Statistics] -> ShowS
showList :: [Statistics] -> ShowS
Show, Statistics -> Statistics -> Bool
(Statistics -> Statistics -> Bool)
-> (Statistics -> Statistics -> Bool) -> Eq Statistics
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Statistics -> Statistics -> Bool
== :: Statistics -> Statistics -> Bool
$c/= :: Statistics -> Statistics -> Bool
/= :: Statistics -> Statistics -> Bool
Eq, (forall x. Statistics -> Rep Statistics x)
-> (forall x. Rep Statistics x -> Statistics) -> Generic Statistics
forall x. Rep Statistics x -> Statistics
forall x. Statistics -> Rep Statistics x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Statistics -> Rep Statistics x
from :: forall x. Statistics -> Rep Statistics x
$cto :: forall x. Rep Statistics x -> Statistics
to :: forall x. Rep Statistics x -> Statistics
Generic)

instance Semigroup Statistics where
  Statistics HashMap String (Sum Word64)
a HashMap String (Max Word64)
b <> :: Statistics -> Statistics -> Statistics
<> Statistics HashMap String (Sum Word64)
a' HashMap String (Max Word64)
b' = HashMap String (Sum Word64)
-> HashMap String (Max Word64) -> Statistics
Statistics
    ((Sum Word64 -> Sum Word64 -> Sum Word64)
-> HashMap String (Sum Word64)
-> HashMap String (Sum Word64)
-> HashMap String (Sum Word64)
forall k v.
Eq k =>
(v -> v -> v) -> HashMap k v -> HashMap k v -> HashMap k v
HMap.unionWith Sum Word64 -> Sum Word64 -> Sum Word64
forall a. Semigroup a => a -> a -> a
(<>) HashMap String (Sum Word64)
a HashMap String (Sum Word64)
a')
    ((Max Word64 -> Max Word64 -> Max Word64)
-> HashMap String (Max Word64)
-> HashMap String (Max Word64)
-> HashMap String (Max Word64)
forall k v.
Eq k =>
(v -> v -> v) -> HashMap k v -> HashMap k v -> HashMap k v
HMap.unionWith Max Word64 -> Max Word64 -> Max Word64
forall a. Semigroup a => a -> a -> a
(<>) HashMap String (Max Word64)
b HashMap String (Max Word64)
b')

instance Null Statistics where
  empty :: Statistics
empty = HashMap String (Sum Word64)
-> HashMap String (Max Word64) -> Statistics
Statistics HashMap String (Sum Word64)
forall a. Null a => a
empty HashMap String (Max Word64)
forall a. Null a => a
empty

  null :: Statistics -> Bool
null (Statistics HashMap String (Sum Word64)
a HashMap String (Max Word64)
b) = HashMap String (Sum Word64) -> Bool
forall k v. HashMap k v -> Bool
HMap.null HashMap String (Sum Word64)
a Bool -> Bool -> Bool
&& HashMap String (Max Word64) -> Bool
forall k v. HashMap k v -> Bool
HMap.null HashMap String (Max Word64)
b

instance Monoid Statistics where
  mempty :: Statistics
mempty = Statistics
forall a. Null a => a
empty

----------------------------------------------------------------------------------------------------
-- ** Trace
----------------------------------------------------------------------------------------------------

data Call
  = CheckClause Type A.SpineClause
  | CheckLHS A.SpineLHS
  | CheckPattern A.Pattern Telescope Type
  | CheckPatternLinearityType C.Name
  | CheckPatternLinearityValue C.Name
  | CheckLetBinding A.LetBinding
  | InferExpr A.Expr
  | CheckExprCall Comparison A.Expr Type
  | CheckDotPattern A.Expr Term
  | CheckProjection Range QName Type
  | IsTypeCall Comparison A.Expr Sort
  | IsType_ A.Expr
  | InferVar Name
  | InferDef QName
  | CheckArguments A.Expr [NamedArg A.Expr] Type (Maybe Type)
  | CheckMetaSolution Range MetaId Type Term
  | CheckTargetType Range Type Type
  | CheckDataDef Range QName [A.LamBinding] [A.Constructor]
  | CheckRecDef Range QName [A.LamBinding] [A.Constructor]
  | CheckConstructor QName Telescope Sort A.Constructor
  | CheckIndexSort QName Type Sort
  | CheckConArgFitsIn QName Bool Type Sort
  | CheckFunDefCall Range QName Bool
    -- ^ Highlight (interactively) if and only if the boolean is 'True'.
  | CheckPragma Range A.Pragma
  | CheckPrimitive Range QName A.Expr
  | CheckIsEmpty Range Type
  | CheckModuleParameters ModuleName A.Telescope
  | CheckWithFunctionType Type
  | CheckWithFunctionLet Name LetBinding
  | CheckSectionApplication Range ModuleName A.ModuleApplication
  | CheckNonLocalWhere ModuleName
  -- | Checking a clause for confluence with endpoint reductions. Always
  -- @φ ⊢ f vs = rhs@ for now, but we store the simplifications of
    -- @f vs[φ]@ and @rhs[φ]@.
  | CheckIApplyConfluence
      Range  -- ^ Clause range
      QName  -- ^ Function name
      Term   -- ^ (As-is) Function applied to the patterns in this clause
      Term   -- ^ (Simplified) Function applied to the patterns in this clause
      Term   -- ^ (Simplified) clause RHS
      Type   -- ^ (Simplified) clause type
  | ScopeCheckExpr C.Expr
  | ScopeCheckDeclaration NiceDeclaration
  | ScopeCheckLHS C.QName C.Pattern
  | NoHighlighting
  | ModuleContents  -- ^ Interaction command: show module contents.
  | SetRange Range  -- ^ used by 'setCurrentRange'
  deriving ((forall x. Call -> Rep Call x)
-> (forall x. Rep Call x -> Call) -> Generic Call
forall x. Rep Call x -> Call
forall x. Call -> Rep Call x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Call -> Rep Call x
from :: forall x. Call -> Rep Call x
$cto :: forall x. Rep Call x -> Call
to :: forall x. Rep Call x -> Call
Generic, Int -> Call -> ShowS
[Call] -> ShowS
Call -> String
(Int -> Call -> ShowS)
-> (Call -> String) -> ([Call] -> ShowS) -> Show Call
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Call -> ShowS
showsPrec :: Int -> Call -> ShowS
$cshow :: Call -> String
show :: Call -> String
$cshowList :: [Call] -> ShowS
showList :: [Call] -> ShowS
Show)

instance Pretty Call where
    pretty :: Call -> Doc
pretty CheckClause{}             = Doc
"CheckClause"
    pretty CheckLHS{}                = Doc
"CheckLHS"
    pretty CheckPattern{}            = Doc
"CheckPattern"
    pretty CheckPatternLinearityType{}  = Doc
"CheckPatternLinearityType"
    pretty CheckPatternLinearityValue{} = Doc
"CheckPatternLinearityValue"
    pretty InferExpr{}               = Doc
"InferExpr"
    pretty CheckExprCall{}           = Doc
"CheckExprCall"
    pretty CheckLetBinding{}         = Doc
"CheckLetBinding"
    pretty CheckProjection{}         = Doc
"CheckProjection"
    pretty IsTypeCall{}              = Doc
"IsTypeCall"
    pretty IsType_{}                 = Doc
"IsType_"
    pretty InferVar{}                = Doc
"InferVar"
    pretty InferDef{}                = Doc
"InferDef"
    pretty CheckArguments{}          = Doc
"CheckArguments"
    pretty CheckMetaSolution{}       = Doc
"CheckMetaSolution"
    pretty CheckTargetType{}         = Doc
"CheckTargetType"
    pretty CheckDataDef{}            = Doc
"CheckDataDef"
    pretty CheckRecDef{}             = Doc
"CheckRecDef"
    pretty CheckConstructor{}        = Doc
"CheckConstructor"
    pretty CheckIndexSort{}          = Doc
"CheckIndexSort"
    pretty CheckConArgFitsIn{}       = Doc
"CheckConArgFitsIn"
    pretty CheckFunDefCall{}         = Doc
"CheckFunDefCall"
    pretty CheckPragma{}             = Doc
"CheckPragma"
    pretty CheckPrimitive{}          = Doc
"CheckPrimitive"
    pretty CheckModuleParameters{}   = Doc
"CheckModuleParameters"
    pretty CheckWithFunctionType{}   = Doc
"CheckWithFunctionType"
    pretty CheckWithFunctionLet{}    = Doc
"CheckWithFunctionLet"
    pretty CheckNonLocalWhere{}      = Doc
"CheckNonLocalWhere"
    pretty ScopeCheckExpr{}          = Doc
"ScopeCheckExpr"
    pretty ScopeCheckDeclaration{}   = Doc
"ScopeCheckDeclaration"
    pretty ScopeCheckLHS{}           = Doc
"ScopeCheckLHS"
    pretty CheckDotPattern{}         = Doc
"CheckDotPattern"
    pretty SetRange{}                = Doc
"SetRange"
    pretty CheckSectionApplication{} = Doc
"CheckSectionApplication"
    pretty CheckIsEmpty{}            = Doc
"CheckIsEmpty"
    pretty NoHighlighting{}          = Doc
"NoHighlighting"
    pretty ModuleContents{}          = Doc
"ModuleContents"
    pretty CheckIApplyConfluence{}   = Doc
"ModuleContents"

instance HasRange Call where
    getRange :: Call -> Range
getRange (CheckClause Type
_ SpineClause
c)                   = SpineClause -> Range
forall a. HasRange a => a -> Range
getRange SpineClause
c
    getRange (CheckLHS SpineLHS
lhs)                      = SpineLHS -> Range
forall a. HasRange a => a -> Range
getRange SpineLHS
lhs
    getRange (CheckPattern Pattern
p Telescope
_ Type
_)                = Pattern -> Range
forall a. HasRange a => a -> Range
getRange Pattern
p
    getRange (CheckPatternLinearityType Name
x)       = Name -> Range
forall a. HasRange a => a -> Range
getRange Name
x
    getRange (CheckPatternLinearityValue Name
x)      = Name -> Range
forall a. HasRange a => a -> Range
getRange Name
x
    getRange (InferExpr Expr
e)                       = Expr -> Range
forall a. HasRange a => a -> Range
getRange Expr
e
    getRange (CheckExprCall Comparison
_ Expr
e Type
_)               = Expr -> Range
forall a. HasRange a => a -> Range
getRange Expr
e
    getRange (CheckLetBinding LetBinding
b)                 = LetBinding -> Range
forall a. HasRange a => a -> Range
getRange LetBinding
b
    getRange (CheckProjection Range
r QName
_ Type
_)             = Range
r
    getRange (IsTypeCall Comparison
cmp Expr
e Sort
s)                = Expr -> Range
forall a. HasRange a => a -> Range
getRange Expr
e
    getRange (IsType_ Expr
e)                         = Expr -> Range
forall a. HasRange a => a -> Range
getRange Expr
e
    getRange (InferVar Name
x)                        = Name -> Range
forall a. HasRange a => a -> Range
getRange Name
x
    getRange (InferDef QName
f)                        = QName -> Range
forall a. HasRange a => a -> Range
getRange QName
f
    getRange (CheckArguments Expr
fun Args
_ Type
_ Maybe Type
_)          = Expr -> Range
forall a. HasRange a => a -> Range
getRange Expr
fun
    getRange (CheckMetaSolution Range
r MetaId
_ Type
_ Term
_)         = Range
r
    getRange (CheckTargetType Range
r Type
_ Type
_)             = Range
r
    getRange (CheckDataDef Range
i QName
_ [LamBinding]
_ [Constructor]
_)              = Range -> Range
forall a. HasRange a => a -> Range
getRange Range
i
    getRange (CheckRecDef Range
i QName
_ [LamBinding]
_ [Constructor]
_)               = Range -> Range
forall a. HasRange a => a -> Range
getRange Range
i
    getRange (CheckConstructor QName
_ Telescope
_ Sort
_ Constructor
c)          = Constructor -> Range
forall a. HasRange a => a -> Range
getRange Constructor
c
    getRange (CheckIndexSort QName
d Type
_ Sort
_)              = QName -> Range
forall a. HasRange a => a -> Range
getRange QName
d
    getRange (CheckConArgFitsIn QName
c Bool
_ Type
_ Sort
_)         = QName -> Range
forall a. HasRange a => a -> Range
getRange QName
c
    getRange (CheckFunDefCall Range
i QName
_ Bool
_)             = Range -> Range
forall a. HasRange a => a -> Range
getRange Range
i
    getRange (CheckPragma Range
r Pragma
_)                   = Range
r
    getRange (CheckPrimitive Range
i QName
_ Expr
_)              = Range -> Range
forall a. HasRange a => a -> Range
getRange Range
i
    getRange (CheckModuleParameters ModuleName
_ Telescope
tel)       = Telescope -> Range
forall a. HasRange a => a -> Range
getRange Telescope
tel
    getRange CheckWithFunctionType{}             = Range
forall a. Range' a
noRange
    getRange (CheckWithFunctionLet Name
x LetBinding
_)          = Name -> Range
forall a. HasRange a => a -> Range
getRange Name
x
    getRange (CheckNonLocalWhere ModuleName
m)              = ModuleName -> Range
forall a. HasRange a => a -> Range
getRange ModuleName
m
    getRange (ScopeCheckExpr Expr
e)                  = Expr -> Range
forall a. HasRange a => a -> Range
getRange Expr
e
    getRange (ScopeCheckDeclaration NiceDeclaration
d)           = NiceDeclaration -> Range
forall a. HasRange a => a -> Range
getRange NiceDeclaration
d
    getRange (ScopeCheckLHS QName
_ Pattern
p)                 = Pattern -> Range
forall a. HasRange a => a -> Range
getRange Pattern
p
    getRange (CheckDotPattern Expr
e Term
_)               = Expr -> Range
forall a. HasRange a => a -> Range
getRange Expr
e
    getRange (SetRange Range
r)                        = Range
r
    getRange (CheckSectionApplication Range
r ModuleName
_ ModuleApplication
_)     = Range
r
    getRange (CheckIsEmpty Range
r Type
_)                  = Range
r
    getRange Call
NoHighlighting                      = Range
forall a. Range' a
noRange
    getRange Call
ModuleContents                      = Range
forall a. Range' a
noRange
    getRange (CheckIApplyConfluence Range
e QName
_ Term
_ Term
_ Term
_ Type
_) = Range -> Range
forall a. HasRange a => a -> Range
getRange Range
e

----------------------------------------------------------------------------------------------------
-- ** Instance table
----------------------------------------------------------------------------------------------------

-- | Records information about the instances in the signature. Does not
-- deal with local instances.
data InstanceTable = InstanceTable
  { InstanceTable -> DiscrimTree QName
_itableTree   :: DiscrimTree QName
    -- ^ The actual discrimination tree for looking up instances with

  , InstanceTable -> Map QName Int
_itableCounts :: Map QName Int
    -- ^ For profiling, we store the number of instances on a per-class
    -- basis. This lets us compare the result from the discrimination
    -- tree with all the instances in scope, thus informing us how many
    -- validity checks were skipped.
  }
  deriving (Int -> InstanceTable -> ShowS
[InstanceTable] -> ShowS
InstanceTable -> String
(Int -> InstanceTable -> ShowS)
-> (InstanceTable -> String)
-> ([InstanceTable] -> ShowS)
-> Show InstanceTable
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> InstanceTable -> ShowS
showsPrec :: Int -> InstanceTable -> ShowS
$cshow :: InstanceTable -> String
show :: InstanceTable -> String
$cshowList :: [InstanceTable] -> ShowS
showList :: [InstanceTable] -> ShowS
Show, (forall x. InstanceTable -> Rep InstanceTable x)
-> (forall x. Rep InstanceTable x -> InstanceTable)
-> Generic InstanceTable
forall x. Rep InstanceTable x -> InstanceTable
forall x. InstanceTable -> Rep InstanceTable x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. InstanceTable -> Rep InstanceTable x
from :: forall x. InstanceTable -> Rep InstanceTable x
$cto :: forall x. Rep InstanceTable x -> InstanceTable
to :: forall x. Rep InstanceTable x -> InstanceTable
Generic)

instance Semigroup InstanceTable where
  InstanceTable DiscrimTree QName
t Map QName Int
i <> :: InstanceTable -> InstanceTable -> InstanceTable
<> InstanceTable DiscrimTree QName
t' Map QName Int
i' = InstanceTable
    { _itableTree :: DiscrimTree QName
_itableTree   = DiscrimTree QName
t DiscrimTree QName -> DiscrimTree QName -> DiscrimTree QName
forall a. Semigroup a => a -> a -> a
<> DiscrimTree QName
t'
    , _itableCounts :: Map QName Int
_itableCounts = (Int -> Int -> Int)
-> Map QName Int -> Map QName Int -> Map QName Int
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
Map.unionWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) Map QName Int
i Map QName Int
i'
    }

instance Monoid InstanceTable where
  mempty :: InstanceTable
mempty = DiscrimTree QName -> Map QName Int -> InstanceTable
InstanceTable DiscrimTree QName
forall a. Monoid a => a
mempty Map QName Int
forall a. Monoid a => a
mempty

instance Null InstanceTable where
  empty :: InstanceTable
empty = InstanceTable
forall a. Monoid a => a
mempty
  null :: InstanceTable -> Bool
null (InstanceTable DiscrimTree QName
a Map QName Int
b) = DiscrimTree QName -> Bool
forall a. Null a => a -> Bool
null DiscrimTree QName
a Bool -> Bool -> Bool
&& Map QName Int -> Bool
forall a. Null a => a -> Bool
null Map QName Int
b

itableTree :: Lens' InstanceTable (DiscrimTree QName)
itableTree :: Lens' InstanceTable (DiscrimTree QName)
itableTree DiscrimTree QName -> f (DiscrimTree QName)
f InstanceTable
s = DiscrimTree QName -> f (DiscrimTree QName)
f (InstanceTable -> DiscrimTree QName
_itableTree InstanceTable
s) f (DiscrimTree QName)
-> (DiscrimTree QName -> InstanceTable) -> f InstanceTable
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \DiscrimTree QName
x -> InstanceTable
s { _itableTree = x }

itableCounts :: Lens' InstanceTable (Map QName Int)
itableCounts :: Lens' InstanceTable (Map QName Int)
itableCounts Map QName Int -> f (Map QName Int)
f InstanceTable
s = Map QName Int -> f (Map QName Int)
f (InstanceTable -> Map QName Int
_itableCounts InstanceTable
s) f (Map QName Int)
-> (Map QName Int -> InstanceTable) -> f InstanceTable
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \Map QName Int
x -> InstanceTable
s { _itableCounts = x }

-- | When typechecking something of the following form:
--
--     instance
--       x : _
--       x = y
--
--   it's not yet known where to add @x@, so we add it to a list of
--   unresolved instances and we'll deal with it later.
type TempInstanceTable = (InstanceTable , Set QName)

----------------------------------------------------------------------------------------------------
-- ** Builtin things
----------------------------------------------------------------------------------------------------

data BuiltinSort
  = SortUniv Univ
  | SortOmega Univ
  | SortIntervalUniv
  | SortLevelUniv
  | SortCofUniv
  deriving (Int -> BuiltinSort -> ShowS
[BuiltinSort] -> ShowS
BuiltinSort -> String
(Int -> BuiltinSort -> ShowS)
-> (BuiltinSort -> String)
-> ([BuiltinSort] -> ShowS)
-> Show BuiltinSort
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> BuiltinSort -> ShowS
showsPrec :: Int -> BuiltinSort -> ShowS
$cshow :: BuiltinSort -> String
show :: BuiltinSort -> String
$cshowList :: [BuiltinSort] -> ShowS
showList :: [BuiltinSort] -> ShowS
Show, BuiltinSort -> BuiltinSort -> Bool
(BuiltinSort -> BuiltinSort -> Bool)
-> (BuiltinSort -> BuiltinSort -> Bool) -> Eq BuiltinSort
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: BuiltinSort -> BuiltinSort -> Bool
== :: BuiltinSort -> BuiltinSort -> Bool
$c/= :: BuiltinSort -> BuiltinSort -> Bool
/= :: BuiltinSort -> BuiltinSort -> Bool
Eq, (forall x. BuiltinSort -> Rep BuiltinSort x)
-> (forall x. Rep BuiltinSort x -> BuiltinSort)
-> Generic BuiltinSort
forall x. Rep BuiltinSort x -> BuiltinSort
forall x. BuiltinSort -> Rep BuiltinSort x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. BuiltinSort -> Rep BuiltinSort x
from :: forall x. BuiltinSort -> Rep BuiltinSort x
$cto :: forall x. Rep BuiltinSort x -> BuiltinSort
to :: forall x. Rep BuiltinSort x -> BuiltinSort
Generic)

pattern SortProp, SortType, SortStrictSet, SortPropOmega, SortTypeOmega, SortStrictSetOmega :: BuiltinSort
pattern $bSortProp :: BuiltinSort
$mSortProp :: forall {r}. BuiltinSort -> ((# #) -> r) -> ((# #) -> r) -> r
SortProp           = SortUniv  UProp
pattern $bSortType :: BuiltinSort
$mSortType :: forall {r}. BuiltinSort -> ((# #) -> r) -> ((# #) -> r) -> r
SortType            = SortUniv  UType
pattern $bSortStrictSet :: BuiltinSort
$mSortStrictSet :: forall {r}. BuiltinSort -> ((# #) -> r) -> ((# #) -> r) -> r
SortStrictSet      = SortUniv  USSet
pattern $bSortPropOmega :: BuiltinSort
$mSortPropOmega :: forall {r}. BuiltinSort -> ((# #) -> r) -> ((# #) -> r) -> r
SortPropOmega      = SortOmega UProp
pattern $bSortTypeOmega :: BuiltinSort
$mSortTypeOmega :: forall {r}. BuiltinSort -> ((# #) -> r) -> ((# #) -> r) -> r
SortTypeOmega       = SortOmega UType
pattern $bSortStrictSetOmega :: BuiltinSort
$mSortStrictSetOmega :: forall {r}. BuiltinSort -> ((# #) -> r) -> ((# #) -> r) -> r
SortStrictSetOmega = SortOmega USSet

{-# COMPLETE
  SortProp, SortType, SortStrictSet,
  SortPropOmega, SortTypeOmega, SortStrictSetOmega,
  SortIntervalUniv, SortLevelUniv, SortCofUniv #-}

data BuiltinDescriptor
  = BuiltinData (TCM Type) [BuiltinId]
  | BuiltinDataCons (TCM Type)
  | BuiltinPrim PrimitiveId (Term -> TCM ())
  | BuiltinSort BuiltinSort
  | BuiltinPostulate (TCM Type)
  | BuiltinUnknown (Maybe (TCM Type)) (Term -> Type -> TCM ())
    -- ^ Builtin of any kind.
    --   Type can be checked (@Just t@) or inferred (@Nothing@).
    --   The second argument is the hook for the verification function.

data BuiltinInfo =
   BuiltinInfo { BuiltinInfo -> BuiltinId
builtinName :: BuiltinId
               , BuiltinInfo -> BuiltinDescriptor
builtinDesc :: BuiltinDescriptor }

type BuiltinThings = BuiltinThings' PrimFun
type BuiltinThings' pf = Map SomeBuiltin (Builtin pf)

data Builtin pf
  = Builtin Term
  | Prim pf
  deriving (Int -> Builtin pf -> ShowS
[Builtin pf] -> ShowS
Builtin pf -> String
(Int -> Builtin pf -> ShowS)
-> (Builtin pf -> String)
-> ([Builtin pf] -> ShowS)
-> Show (Builtin pf)
forall pf. Show pf => Int -> Builtin pf -> ShowS
forall pf. Show pf => [Builtin pf] -> ShowS
forall pf. Show pf => Builtin pf -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall pf. Show pf => Int -> Builtin pf -> ShowS
showsPrec :: Int -> Builtin pf -> ShowS
$cshow :: forall pf. Show pf => Builtin pf -> String
show :: Builtin pf -> String
$cshowList :: forall pf. Show pf => [Builtin pf] -> ShowS
showList :: [Builtin pf] -> ShowS
Show, (forall a b. (a -> b) -> Builtin a -> Builtin b)
-> (forall a b. a -> Builtin b -> Builtin a) -> Functor Builtin
forall a b. a -> Builtin b -> Builtin a
forall a b. (a -> b) -> Builtin a -> Builtin b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall a b. (a -> b) -> Builtin a -> Builtin b
fmap :: forall a b. (a -> b) -> Builtin a -> Builtin b
$c<$ :: forall a b. a -> Builtin b -> Builtin a
<$ :: forall a b. a -> Builtin b -> Builtin a
Functor, (forall m. Monoid m => Builtin m -> m)
-> (forall m a. Monoid m => (a -> m) -> Builtin a -> m)
-> (forall m a. Monoid m => (a -> m) -> Builtin a -> m)
-> (forall a b. (a -> b -> b) -> b -> Builtin a -> b)
-> (forall a b. (a -> b -> b) -> b -> Builtin a -> b)
-> (forall b a. (b -> a -> b) -> b -> Builtin a -> b)
-> (forall b a. (b -> a -> b) -> b -> Builtin a -> b)
-> (forall a. (a -> a -> a) -> Builtin a -> a)
-> (forall a. (a -> a -> a) -> Builtin a -> a)
-> (forall a. Builtin a -> [a])
-> (forall a. Builtin a -> Bool)
-> (forall a. Builtin a -> Int)
-> (forall a. Eq a => a -> Builtin a -> Bool)
-> (forall a. Ord a => Builtin a -> a)
-> (forall a. Ord a => Builtin a -> a)
-> (forall a. Num a => Builtin a -> a)
-> (forall a. Num a => Builtin a -> a)
-> Foldable Builtin
forall a. Eq a => a -> Builtin a -> Bool
forall a. Num a => Builtin a -> a
forall a. Ord a => Builtin a -> a
forall m. Monoid m => Builtin m -> m
forall a. Builtin a -> Bool
forall a. Builtin a -> Int
forall a. Builtin a -> [a]
forall a. (a -> a -> a) -> Builtin a -> a
forall m a. Monoid m => (a -> m) -> Builtin a -> m
forall b a. (b -> a -> b) -> b -> Builtin a -> b
forall a b. (a -> b -> b) -> b -> Builtin a -> b
forall (t :: * -> *).
(forall m. Monoid m => t m -> m)
-> (forall m a. Monoid m => (a -> m) -> t a -> m)
-> (forall m a. Monoid m => (a -> m) -> t a -> m)
-> (forall a b. (a -> b -> b) -> b -> t a -> b)
-> (forall a b. (a -> b -> b) -> b -> t a -> b)
-> (forall b a. (b -> a -> b) -> b -> t a -> b)
-> (forall b a. (b -> a -> b) -> b -> t a -> b)
-> (forall a. (a -> a -> a) -> t a -> a)
-> (forall a. (a -> a -> a) -> t a -> a)
-> (forall a. t a -> [a])
-> (forall a. t a -> Bool)
-> (forall a. t a -> Int)
-> (forall a. Eq a => a -> t a -> Bool)
-> (forall a. Ord a => t a -> a)
-> (forall a. Ord a => t a -> a)
-> (forall a. Num a => t a -> a)
-> (forall a. Num a => t a -> a)
-> Foldable t
$cfold :: forall m. Monoid m => Builtin m -> m
fold :: forall m. Monoid m => Builtin m -> m
$cfoldMap :: forall m a. Monoid m => (a -> m) -> Builtin a -> m
foldMap :: forall m a. Monoid m => (a -> m) -> Builtin a -> m
$cfoldMap' :: forall m a. Monoid m => (a -> m) -> Builtin a -> m
foldMap' :: forall m a. Monoid m => (a -> m) -> Builtin a -> m
$cfoldr :: forall a b. (a -> b -> b) -> b -> Builtin a -> b
foldr :: forall a b. (a -> b -> b) -> b -> Builtin a -> b
$cfoldr' :: forall a b. (a -> b -> b) -> b -> Builtin a -> b
foldr' :: forall a b. (a -> b -> b) -> b -> Builtin a -> b
$cfoldl :: forall b a. (b -> a -> b) -> b -> Builtin a -> b
foldl :: forall b a. (b -> a -> b) -> b -> Builtin a -> b
$cfoldl' :: forall b a. (b -> a -> b) -> b -> Builtin a -> b
foldl' :: forall b a. (b -> a -> b) -> b -> Builtin a -> b
$cfoldr1 :: forall a. (a -> a -> a) -> Builtin a -> a
foldr1 :: forall a. (a -> a -> a) -> Builtin a -> a
$cfoldl1 :: forall a. (a -> a -> a) -> Builtin a -> a
foldl1 :: forall a. (a -> a -> a) -> Builtin a -> a
$ctoList :: forall a. Builtin a -> [a]
toList :: forall a. Builtin a -> [a]
$cnull :: forall a. Builtin a -> Bool
null :: forall a. Builtin a -> Bool
$clength :: forall a. Builtin a -> Int
length :: forall a. Builtin a -> Int
$celem :: forall a. Eq a => a -> Builtin a -> Bool
elem :: forall a. Eq a => a -> Builtin a -> Bool
$cmaximum :: forall a. Ord a => Builtin a -> a
maximum :: forall a. Ord a => Builtin a -> a
$cminimum :: forall a. Ord a => Builtin a -> a
minimum :: forall a. Ord a => Builtin a -> a
$csum :: forall a. Num a => Builtin a -> a
sum :: forall a. Num a => Builtin a -> a
$cproduct :: forall a. Num a => Builtin a -> a
product :: forall a. Num a => Builtin a -> a
Foldable, Functor Builtin
Foldable Builtin
(Functor Builtin, Foldable Builtin) =>
(forall (f :: * -> *) a b.
 Applicative f =>
 (a -> f b) -> Builtin a -> f (Builtin b))
-> (forall (f :: * -> *) a.
    Applicative f =>
    Builtin (f a) -> f (Builtin a))
-> (forall (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> Builtin a -> m (Builtin b))
-> (forall (m :: * -> *) a.
    Monad m =>
    Builtin (m a) -> m (Builtin a))
-> Traversable Builtin
forall (t :: * -> *).
(Functor t, Foldable t) =>
(forall (f :: * -> *) a b.
 Applicative f =>
 (a -> f b) -> t a -> f (t b))
-> (forall (f :: * -> *) a. Applicative f => t (f a) -> f (t a))
-> (forall (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> t a -> m (t b))
-> (forall (m :: * -> *) a. Monad m => t (m a) -> m (t a))
-> Traversable t
forall (m :: * -> *) a. Monad m => Builtin (m a) -> m (Builtin a)
forall (f :: * -> *) a.
Applicative f =>
Builtin (f a) -> f (Builtin a)
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Builtin a -> m (Builtin b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Builtin a -> f (Builtin b)
$ctraverse :: forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Builtin a -> f (Builtin b)
traverse :: forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Builtin a -> f (Builtin b)
$csequenceA :: forall (f :: * -> *) a.
Applicative f =>
Builtin (f a) -> f (Builtin a)
sequenceA :: forall (f :: * -> *) a.
Applicative f =>
Builtin (f a) -> f (Builtin a)
$cmapM :: forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Builtin a -> m (Builtin b)
mapM :: forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Builtin a -> m (Builtin b)
$csequence :: forall (m :: * -> *) a. Monad m => Builtin (m a) -> m (Builtin a)
sequence :: forall (m :: * -> *) a. Monad m => Builtin (m a) -> m (Builtin a)
Traversable, (forall x. Builtin pf -> Rep (Builtin pf) x)
-> (forall x. Rep (Builtin pf) x -> Builtin pf)
-> Generic (Builtin pf)
forall x. Rep (Builtin pf) x -> Builtin pf
forall x. Builtin pf -> Rep (Builtin pf) x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
forall pf x. Rep (Builtin pf) x -> Builtin pf
forall pf x. Builtin pf -> Rep (Builtin pf) x
$cfrom :: forall pf x. Builtin pf -> Rep (Builtin pf) x
from :: forall x. Builtin pf -> Rep (Builtin pf) x
$cto :: forall pf x. Rep (Builtin pf) x -> Builtin pf
to :: forall x. Rep (Builtin pf) x -> Builtin pf
Generic)

----------------------------------------------------------------------------------------------------
-- * Highlighting levels
----------------------------------------------------------------------------------------------------

-- | @ifTopLevelAndHighlightingLevelIs l b m@ runs @m@ when we're
-- type-checking the top-level module (or before we've started doing
-- this) and either the highlighting level is /at least/ @l@ or @b@ is
-- 'True'.

ifTopLevelAndHighlightingLevelIsOr ::
  MonadTCEnv tcm => HighlightingLevel -> Bool -> tcm () -> tcm ()
ifTopLevelAndHighlightingLevelIsOr :: forall (tcm :: * -> *).
MonadTCEnv tcm =>
HighlightingLevel -> Bool -> tcm () -> tcm ()
ifTopLevelAndHighlightingLevelIsOr HighlightingLevel
l Bool
b tcm ()
m = do
  e <- tcm TCEnv
forall (m :: * -> *). MonadTCEnv m => m TCEnv
askTC
  when ((e ^. eHighlightingLevel) >= l || b) $
    case e ^. eImportStack of
      -- Below the main module.
      (TopLevelModuleName
_:TopLevelModuleName
_:[TopLevelModuleName]
_) -> () -> tcm ()
forall a. a -> tcm a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
      -- In or before the top-level module.
      [TopLevelModuleName]
_ -> tcm ()
m

-- | @ifTopLevelAndHighlightingLevelIs l m@ runs @m@ when we're
-- type-checking the top-level module (or before we've started doing
-- this) and the highlighting level is /at least/ @l@.

ifTopLevelAndHighlightingLevelIs ::
  MonadTCEnv tcm => HighlightingLevel -> tcm () -> tcm ()
ifTopLevelAndHighlightingLevelIs :: forall (tcm :: * -> *).
MonadTCEnv tcm =>
HighlightingLevel -> tcm () -> tcm ()
ifTopLevelAndHighlightingLevelIs HighlightingLevel
l =
  HighlightingLevel -> Bool -> tcm () -> tcm ()
forall (tcm :: * -> *).
MonadTCEnv tcm =>
HighlightingLevel -> Bool -> tcm () -> tcm ()
ifTopLevelAndHighlightingLevelIsOr HighlightingLevel
l Bool
False

----------------------------------------------------------------------------------------------------
-- * Boolean flag storage
----------------------------------------------------------------------------------------------------

newtype Flags64 = Flags64 Word64 deriving (Flags64 -> Flags64 -> Bool
(Flags64 -> Flags64 -> Bool)
-> (Flags64 -> Flags64 -> Bool) -> Eq Flags64
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Flags64 -> Flags64 -> Bool
== :: Flags64 -> Flags64 -> Bool
$c/= :: Flags64 -> Flags64 -> Bool
/= :: Flags64 -> Flags64 -> Bool
Eq, (forall x. Flags64 -> Rep Flags64 x)
-> (forall x. Rep Flags64 x -> Flags64) -> Generic Flags64
forall x. Rep Flags64 x -> Flags64
forall x. Flags64 -> Rep Flags64 x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Flags64 -> Rep Flags64 x
from :: forall x. Flags64 -> Rep Flags64 x
$cto :: forall x. Rep Flags64 x -> Flags64
to :: forall x. Rep Flags64 x -> Flags64
Generic, Flags64 -> ()
(Flags64 -> ()) -> NFData Flags64
forall a. (a -> ()) -> NFData a
$crnf :: Flags64 -> ()
rnf :: Flags64 -> ()
NFData)

{-# INLINE mkFlag #-}
mkFlag :: Int -> Lens' Flags64 Bool
mkFlag :: Int -> Lens' Flags64 Bool
mkFlag !Int
i = \Bool -> f Bool
f Flags64
fs -> Bool -> f Bool
f (Int -> Flags64 -> Bool
getFlag Int
i Flags64
fs) f Bool -> (Bool -> Flags64) -> f Flags64
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \Bool
x -> Int -> Bool -> Flags64 -> Flags64
setFlag Int
i Bool
x Flags64
fs

{-# INLINE setFlag #-}
setFlag :: Int -> Bool -> Flags64 -> Flags64
setFlag :: Int -> Bool -> Flags64 -> Flags64
setFlag Int
i Bool
b (Flags64 Word64
fs) =
  if Bool
b then Word64 -> Flags64
Flags64 (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftL Word64
1 Int
i Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. Word64
fs)
       else Word64 -> Flags64
Flags64 (Word64 -> Word64
forall a. Bits a => a -> a
complement (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftL Word64
1 Int
i) Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.&. Word64
fs)

{-# INLINE getFlag #-}
getFlag :: Int -> Flags64 -> Bool
getFlag :: Int -> Flags64 -> Bool
getFlag !Int
i (Flags64 !Word64
fs) = Int -> Bool
forall a. Enum a => Int -> a
toEnum (Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
fs Int
i Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.&. Word64
1))

----------------------------------------------------------------------------------------------------
-- * Type checking environment
----------------------------------------------------------------------------------------------------


data TCEnv = TCEnv {
    TCEnv -> TCContext
envTCContext         :: !TCContext
  , TCEnv -> Set ProblemId
envActiveProblems    :: !(Set ProblemId)
  , TCEnv -> LetBindings
envLetBindings       :: !LetBindings
  , TCEnv -> AllowedReductions
envAllowedReductions :: !AllowedReductions
  , TCEnv -> Flags64
envFlags             :: !Flags64
  , TCEnv -> ColdEnv
envColdEnv           :: !ColdEnv
  } deriving (forall x. TCEnv -> Rep TCEnv x)
-> (forall x. Rep TCEnv x -> TCEnv) -> Generic TCEnv
forall x. Rep TCEnv x -> TCEnv
forall x. TCEnv -> Rep TCEnv x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TCEnv -> Rep TCEnv x
from :: forall x. TCEnv -> Rep TCEnv x
$cto :: forall x. Rep TCEnv x -> TCEnv
to :: forall x. Rep TCEnv x -> TCEnv
Generic

data TCContext = TCContext {
    TCContext -> Context
envContext           :: !Context
  , TCContext -> CheckpointId
envCurrentCheckpoint :: !CheckpointId
    -- ^ Checkpoints track the evolution of the context as we go
    -- under binders or refine it by pattern matching.
  , TCContext -> Map CheckpointId Substitution
envCheckpoints       :: Map CheckpointId Substitution
    -- ^ Keeps the substitution from each previous checkpoint to
    --   the current context.
  , TCContext -> Maybe QName
envAppDef :: !(Maybe QName)
        -- ^ We are reducing an application of this function.
        --  (For tracking of incomplete matches.)
  } deriving (forall x. TCContext -> Rep TCContext x)
-> (forall x. Rep TCContext x -> TCContext) -> Generic TCContext
forall x. Rep TCContext x -> TCContext
forall x. TCContext -> Rep TCContext x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TCContext -> Rep TCContext x
from :: forall x. TCContext -> Rep TCContext x
$cto :: forall x. Rep TCContext x -> TCContext
to :: forall x. Rep TCContext x -> TCContext
Generic


data ColdEnv = ColdEnv {
    ColdEnv -> ModuleName
envCurrentModule         :: ModuleName
  , ColdEnv -> Maybe FileId
envCurrentPath         :: Maybe FileId
    -- ^ The path to the file that is currently being
    -- type-checked.  'Nothing' if we do not have a file
    -- (like in interactive mode see @CommandLine@).
  , ColdEnv -> [(ModuleName, Int)]
envAnonymousModules    :: [(ModuleName, Nat)] -- ^ anonymous modules and their number of free variables
  , ColdEnv -> [TopLevelModuleName]
envImportStack         :: [TopLevelModuleName]
    -- ^ The module stack with the entry being the top-level module as
    --   Agda chases modules. It will be empty if there is no main
    --   module, will have a single entry for the top level module, or
    --   more when descending past the main module. This is used to
    --   detect import cycles and in some cases highlighting behavior.
    --   The level of a given module is not necessarily the same as the
    --   length, in the module dependency graph, of the shortest path
    --   from the top-level module; it depends on in which order Agda
    --   chooses to chase dependencies.
  , ColdEnv -> Maybe MutualId
envMutualBlock         :: !(Maybe MutualId)       -- ^ the current (if any) mutual block
  , ColdEnv -> TerminationCheck
envTerminationCheck    :: !TerminationCheck       -- ^ are we inside the scope of a termination pragma
  , ColdEnv -> CoverageCheck
envCoverageCheck       :: !CoverageCheck          -- ^ are we inside the scope of a coverage pragma
  , ColdEnv -> WhereClause_
envCheckingWhere       :: !C.WhereClause_
        -- ^ Have we stepped into the where-declarations of a clause?
        --   Everything under a @where@ will be checked with this flag on.
  , ColdEnv -> Maybe ProblemId
envUnquoteProblem      :: !(Maybe ProblemId)
    -- ^ If inside a `runUnquoteM` call, stores the top-level problem id assigned to the
    --   invokation. We use this to decide which instance constraints originate from the
    --   current call and which come from the outside, for the purpose of a
    --   `solveInstanceConstraints` inside `noConstraints` only failing for local instance
    --   constraints.
  , ColdEnv -> AbstractMode
envAbstractMode        :: !AbstractMode
        -- ^ When checking the typesignature of a public definition
        --   or the body of a non-abstract definition this is true.
        --   To prevent information about abstract things leaking
        --   outside the module.
  , ColdEnv -> Range
envRange :: Range
  , ColdEnv -> Range
envHighlightingRange :: Range
        -- ^ Interactive highlighting uses this range rather
        --   than 'envRange'.
  , ColdEnv -> IPClause
envClause :: IPClause
        -- ^ What is the current clause we are type-checking?
        --   Will be recorded in interaction points in this clause.
  , ColdEnv -> Maybe (Closure Call)
envCall  :: Maybe (Closure Call)
        -- ^ what we're doing at the moment
  , ColdEnv -> HighlightingLevel
envHighlightingLevel  :: !HighlightingLevel
        -- ^ Set to 'None' when imported modules are
        --   type-checked.
  , ColdEnv -> HighlightingMethod
envHighlightingMethod :: !HighlightingMethod
  , ColdEnv -> ExpandHidden
envExpandLast :: !ExpandHidden
        -- ^ When type-checking an alias f=e, we do not want
        -- to insert hidden arguments in the end, because
        -- these will become unsolved metas.
  , ColdEnv -> Simplification
envSimplification :: !Simplification
        -- ^ Did we encounter a simplification (proper match)
        --   during the current reduction process?
  , ColdEnv -> ReduceDefs
envReduceDefs :: !ReduceDefs
  , ColdEnv -> Int
envInjectivityDepth :: !Int
        -- ^ Injectivity can cause non-termination for unsolvable contraints
        --   (#431, #3067). Keep a limit on the nesting depth of injectivity
        --   uses.
  , ColdEnv -> UnquoteFlags
envUnquoteFlags :: !UnquoteFlags
  , ColdEnv -> Int
envInstanceDepth :: !Int
      -- ^ Until we get a termination checker for instance search (#1743) we
      --   limit the search depth to ensure termination.
  , ColdEnv -> [QName]
envPrintingPatternLambdas :: [QName]
        -- ^ #3004: pattern lambdas with copatterns may refer to themselves. We
        --   don't have a good story for what to do in this case, but at least
        --   printing shouldn't loop. Here we keep track of which pattern lambdas
        --   we are currently in the process of printing.
  , ColdEnv -> DoGeneralize
envGeneralizeMetas :: !DoGeneralize
        -- ^ Should new metas be generalized over.
  , ColdEnv -> Map QName GeneralizedValue
envGeneralizedVars :: !(Map QName GeneralizedValue)
        -- ^ Values for used generalizable variables.
  , ColdEnv -> Maybe ShortText
envActiveBackendName :: !(Maybe BackendName)
        -- ^ Is some backend active at the moment, and if yes, which?
        --   NB: we only store the 'BackendName' here, otherwise
        --   @instance Data TEnv@ is not derivable.
        --   The actual backend can be obtained from the name via 'stBackends'.
  , ColdEnv -> Maybe OpaqueId
envCurrentOpaqueId :: !(Maybe OpaqueId)
        -- ^ Unique identifier of the opaque block we are
        -- currently under, if any. Used by the scope checker
        -- (to associate definitions to blocks), and by the type
        -- checker (for unfolding control).
  , ColdEnv -> Maybe String
envChasePrefix :: !(Maybe String)
    -- ^ A string to be used as the prefix for module chasing
    -- (Checking, Loading, etc.) messages. If unset, the length
    -- of the import stack is used.
  } deriving (forall x. ColdEnv -> Rep ColdEnv x)
-> (forall x. Rep ColdEnv x -> ColdEnv) -> Generic ColdEnv
forall x. Rep ColdEnv x -> ColdEnv
forall x. ColdEnv -> Rep ColdEnv x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ColdEnv -> Rep ColdEnv x
from :: forall x. ColdEnv -> Rep ColdEnv x
$cto :: forall x. Rep ColdEnv x -> ColdEnv
to :: forall x. Rep ColdEnv x -> ColdEnv
Generic

-- Bool Flags
----------------------------------------------------------------------------------------------------

{-# INLINE envReconstructed #-}
envReconstructed :: Lens' Flags64 Bool
envReconstructed :: Lens' Flags64 Bool
envReconstructed = Int -> Lens' Flags64 Bool
mkFlag Int
0

-- | When @True@, the conversion checker will consider
--   all term constructors as injective, including
--   blocked function applications and metas. Warning:
--   this should only be used when not assigning any
--   metas (e.g. when @envAssignMetas@ is @False@ or
--   when running @pureEqualTerms@) or else we get
--   non-unique meta solutions.
{-# INLINE envCompareBlocked #-}
envCompareBlocked :: Lens' Flags64 Bool
envCompareBlocked :: Lens' Flags64 Bool
envCompareBlocked = Int -> Lens' Flags64 Bool
mkFlag Int
1

-- | When @True@, types will be omitted from printed pi types if they
--   can be inferred.
{-# INLINE envPrintDomainFreePi #-}
envPrintDomainFreePi :: Lens' Flags64 Bool
envPrintDomainFreePi :: Lens' Flags64 Bool
envPrintDomainFreePi = Int -> Lens' Flags64 Bool
mkFlag Int
2

-- | When @True@, throw away meta numbers and meta elims.
--   This is used for reifying terms for feeding into the
--   user's source code, e.g., for the interaction tactics @solveAll@.
{-# INLINE envPrintMetasBare #-}
envPrintMetasBare :: Lens' Flags64 Bool
envPrintMetasBare :: Lens' Flags64 Bool
envPrintMetasBare = Int -> Lens' Flags64 Bool
mkFlag Int
3

-- | Used by the scope checker to make sure that certain forms
--   of expressions are not used inside dot patterns: extended
--   lambdas and let-expressions.
{-# INLINE envInsideDotPattern #-}
envInsideDotPattern :: Lens' Flags64 Bool
envInsideDotPattern :: Lens' Flags64 Bool
envInsideDotPattern = Int -> Lens' Flags64 Bool
mkFlag Int
4

{-# INLINE envIsDebugPrinting #-}
envIsDebugPrinting :: Lens' Flags64 Bool
envIsDebugPrinting :: Lens' Flags64 Bool
envIsDebugPrinting = Int -> Lens' Flags64 Bool
mkFlag Int
5

-- | Use call-by-need evaluation for reductions.
{-# INLINE envCallByNeed #-}
envCallByNeed :: Lens' Flags64 Bool
envCallByNeed :: Lens' Flags64 Bool
envCallByNeed = Int -> Lens' Flags64 Bool
mkFlag Int
6

-- | are we inside a make-case (if so, ignore forcing analysis in unifier)
{-# INLINE envMakeCase #-}
envMakeCase :: Lens' Flags64 Bool
envMakeCase :: Lens' Flags64 Bool
envMakeCase = Int -> Lens' Flags64 Bool
mkFlag Int
7

-- | Are we currently in the process of solving active constraints?
{-# INLINE envSolvingConstraints #-}
envSolvingConstraints :: Lens' Flags64 Bool
envSolvingConstraints :: Lens' Flags64 Bool
envSolvingConstraints = Int -> Lens' Flags64 Bool
mkFlag Int
8

-- | Are we allowed to assign metas?
{-# INLINE envAssignMetas #-}
envAssignMetas :: Lens' Flags64 Bool
envAssignMetas :: Lens' Flags64 Bool
envAssignMetas = Int -> Lens' Flags64 Bool
mkFlag Int
9

-- | Are we currently case-splitting on a strict
--   datatype (i.e. in SSet)? If yes, the
--   pattern-matching unifier will solve reflexive
--   equations even --without-K.
{-# INLINE envSplitOnStrict #-}
envSplitOnStrict :: Lens' Flags64 Bool
envSplitOnStrict :: Lens' Flags64 Bool
envSplitOnStrict = Int -> Lens' Flags64 Bool
mkFlag Int
11

-- | Sometimes we want to disable display forms.
{-# INLINE envDisplayFormsEnabled #-}
envDisplayFormsEnabled :: Lens' Flags64 Bool
envDisplayFormsEnabled :: Lens' Flags64 Bool
envDisplayFormsEnabled = Int -> Lens' Flags64 Bool
mkFlag Int
12

-- | Fold let-bindings when printing terms (default: True)
{-# INLINE envFoldLetBindings #-}
envFoldLetBindings :: Lens' Flags64 Bool
envFoldLetBindings :: Lens' Flags64 Bool
envFoldLetBindings = Int -> Lens' Flags64 Bool
mkFlag Int
13

-- | Are we currently in the process of executing an
--   elaborate-and-give interactive command?
{-# INLINE envCurrentlyElaborating #-}
envCurrentlyElaborating :: Lens' Flags64 Bool
envCurrentlyElaborating :: Lens' Flags64 Bool
envCurrentlyElaborating = Int -> Lens' Flags64 Bool
mkFlag Int
15

-- | Are we working on types? Turned on by 'workOnTypes'.
{-# INLINE envWorkingOnTypes #-}
envWorkingOnTypes :: Lens' Flags64 Bool
envWorkingOnTypes :: Lens' Flags64 Bool
envWorkingOnTypes = Int -> Lens' Flags64 Bool
mkFlag Int
16

-- | Are we doing pure conversion?
{-# INLINE envPureConversion #-}
envPureConversion :: Lens' Flags64 Bool
envPureConversion :: Lens' Flags64 Bool
envPureConversion = Int -> Lens' Flags64 Bool
mkFlag Int
17

-- | Are we in a dynamic extent where type errors are used for control
-- flow?
--
-- Suppresses type error deferral. Examples include executing reflection
-- code, interactive use, and checking builtins.
{-# INLINE envHardErrors #-}
envHardErrors :: Lens' Flags64 Bool
envHardErrors :: Lens' Flags64 Bool
envHardErrors = Int -> Lens' Flags64 Bool
mkFlag Int
18

-- | Choose between behavior in pure conversion and impure conversion.
--   The first branch is the impure case.
ifImpureConv :: TCM a -> TCM a -> TCM a
ifImpureConv :: forall a. TCM a -> TCM a -> TCM a
ifImpureConv TCM a
impure TCM a
pure = Lens' TCEnv Bool -> TCMT IO Bool
forall (m :: * -> *) a. MonadTCEnv m => Lens' TCEnv a -> m a
viewTC (Bool -> f Bool) -> TCEnv -> f TCEnv
Lens' TCEnv Bool
ePureConversion TCMT IO Bool -> (Bool -> TCM a) -> TCM a
forall a b. TCMT IO a -> (a -> TCMT IO b) -> TCMT IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
  Bool
True -> TCM a
pure
  Bool
_    -> TCM a
impure
{-# INLINE ifImpureConv #-}

-- Initial environment
----------------------------------------------------------------------------------------------------

initEnvFlags :: Flags64
initEnvFlags :: Flags64
initEnvFlags = Word64 -> Flags64
Flags64 Word64
0
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envAssignMetas           ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
True
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envSolvingConstraints    ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envReconstructed         ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envCompareBlocked        ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envPrintDomainFreePi     ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envPrintMetasBare        ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envInsideDotPattern      ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envIsDebugPrinting       ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envCallByNeed            ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
True
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envCurrentlyElaborating  ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envSplitOnStrict         ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envDisplayFormsEnabled   ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
True
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envFoldLetBindings       ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
True
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envMakeCase              ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envPureConversion        ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False
  Flags64 -> (Flags64 -> Flags64) -> Flags64
forall a b. a -> (a -> b) -> b
& (Bool -> Identity Bool) -> Flags64 -> Identity Flags64
Lens' Flags64 Bool
envHardErrors            ((Bool -> Identity Bool) -> Flags64 -> Identity Flags64)
-> Bool -> Flags64 -> Flags64
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Bool
False

initTCContext :: TCContext
initTCContext :: TCContext
initTCContext = TCContext {
    envContext :: Context
envContext             = Context
CxEmpty
  , envCurrentCheckpoint :: CheckpointId
envCurrentCheckpoint   = CheckpointId
0
  , envCheckpoints :: Map CheckpointId Substitution
envCheckpoints         = CheckpointId -> Substitution -> Map CheckpointId Substitution
forall k a. k -> a -> Map k a
Map.singleton CheckpointId
0 Substitution
forall a. Substitution' a
IdS
  , envAppDef :: Maybe QName
envAppDef              = Maybe QName
forall a. Maybe a
Nothing
  }

initColdEnv :: ColdEnv
initColdEnv :: ColdEnv
initColdEnv = ColdEnv {
    envCurrentModule :: ModuleName
envCurrentModule         = ModuleName
noModuleName
  , envCurrentPath :: Maybe FileId
envCurrentPath           = Maybe FileId
forall a. Maybe a
Nothing
  , envAnonymousModules :: [(ModuleName, Int)]
envAnonymousModules      = []
  , envImportStack :: [TopLevelModuleName]
envImportStack           = []
  , envMutualBlock :: Maybe MutualId
envMutualBlock           = Maybe MutualId
forall a. Maybe a
Nothing
  , envTerminationCheck :: TerminationCheck
envTerminationCheck      = TerminationCheck
TerminationCheck
  , envCoverageCheck :: CoverageCheck
envCoverageCheck         = CoverageCheck
YesCoverageCheck
  , envCheckingWhere :: WhereClause_
envCheckingWhere         = WhereClause_
C.NoWhere_
  , envUnquoteProblem :: Maybe ProblemId
envUnquoteProblem        = Maybe ProblemId
forall a. Maybe a
Nothing
  , envAbstractMode :: AbstractMode
envAbstractMode          = AbstractMode
ConcreteMode
  -- Andreas, 2013-02-21:  This was 'AbstractMode' until now.
  -- However, top-level checks for mutual blocks, such as
  -- constructor-headedness, should not be able to look into
  -- abstract definitions unless abstract themselves.
  -- (See also discussion on issue 796.)
  -- The initial mode should be 'ConcreteMode', ensuring you
  -- can only look into abstract things in an abstract
  -- definition (which sets 'AbstractMode').
  , envRange :: Range
envRange                  = Range
forall a. Range' a
noRange
  , envHighlightingRange :: Range
envHighlightingRange      = Range
forall a. Range' a
noRange
  , envClause :: IPClause
envClause                 = IPClause
IPNoClause
  , envCall :: Maybe (Closure Call)
envCall                   = Maybe (Closure Call)
forall a. Maybe a
Nothing
  , envHighlightingLevel :: HighlightingLevel
envHighlightingLevel      = HighlightingLevel
None
  , envHighlightingMethod :: HighlightingMethod
envHighlightingMethod     = HighlightingMethod
Indirect
  , envExpandLast :: ExpandHidden
envExpandLast             = ExpandHidden
ExpandLast
  , envSimplification :: Simplification
envSimplification         = Simplification
NoSimplification
  , envReduceDefs :: ReduceDefs
envReduceDefs             = ReduceDefs
reduceAllDefs
  , envInjectivityDepth :: Int
envInjectivityDepth       = Int
0
  , envUnquoteFlags :: UnquoteFlags
envUnquoteFlags           = UnquoteFlags
defaultUnquoteFlags
  , envInstanceDepth :: Int
envInstanceDepth          = Int
0
  , envPrintingPatternLambdas :: [QName]
envPrintingPatternLambdas = []
  , envGeneralizeMetas :: DoGeneralize
envGeneralizeMetas        = DoGeneralize
NoGeneralize
  , envGeneralizedVars :: Map QName GeneralizedValue
envGeneralizedVars        = Map QName GeneralizedValue
forall k a. Map k a
Map.empty
  , envActiveBackendName :: Maybe ShortText
envActiveBackendName      = Maybe ShortText
forall a. Maybe a
Nothing
  , envCurrentOpaqueId :: Maybe OpaqueId
envCurrentOpaqueId        = Maybe OpaqueId
forall a. Maybe a
Nothing
  , envChasePrefix :: Maybe String
envChasePrefix            = Maybe String
forall a. Maybe a
Nothing
  }

initEnv :: TCEnv
initEnv :: TCEnv
initEnv = TCEnv {
    envTCContext :: TCContext
envTCContext         = TCContext
initTCContext
  , envFlags :: Flags64
envFlags             = Flags64
initEnvFlags
  , envActiveProblems :: Set ProblemId
envActiveProblems    = Set ProblemId
forall a. Set a
Set.empty
  , envLetBindings :: LetBindings
envLetBindings       = LetBindings
forall k a. Map k a
Map.empty
  , envAllowedReductions :: AllowedReductions
envAllowedReductions = AllowedReductions
allReductions
  , envColdEnv :: ColdEnv
envColdEnv           = ColdEnv
initColdEnv
  }


-- * e-prefixed lenses
----------------------------------------------------------------------------------------------------

{-# INLINE eUnquoteProblem #-}
eUnquoteProblem :: Lens' TCEnv (Maybe ProblemId)
eUnquoteProblem :: Lens' TCEnv (Maybe ProblemId)
eUnquoteProblem = \Maybe ProblemId -> f (Maybe ProblemId)
f TCEnv
e ->
  Maybe ProblemId -> f (Maybe ProblemId)
f (ColdEnv -> Maybe ProblemId
envUnquoteProblem (TCEnv -> ColdEnv
envColdEnv TCEnv
e)) f (Maybe ProblemId) -> (Maybe ProblemId -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !Maybe ProblemId
x -> TCEnv
e {envColdEnv = (envColdEnv e){envUnquoteProblem = x}}

{-# INLINE eClause #-}
eClause :: Lens' TCEnv IPClause
eClause :: Lens' TCEnv IPClause
eClause = \IPClause -> f IPClause
f TCEnv
e ->
  IPClause -> f IPClause
f (ColdEnv -> IPClause
envClause (TCEnv -> ColdEnv
envColdEnv TCEnv
e)) f IPClause -> (IPClause -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !IPClause
x -> TCEnv
e {envColdEnv = (envColdEnv e){envClause = x}}

{-# INLINE eCurrentOpaqueId #-}
eCurrentOpaqueId :: Lens' TCEnv (Maybe OpaqueId)
eCurrentOpaqueId :: Lens' TCEnv (Maybe OpaqueId)
eCurrentOpaqueId = \Maybe OpaqueId -> f (Maybe OpaqueId)
f TCEnv
e ->
  Maybe OpaqueId -> f (Maybe OpaqueId)
f (ColdEnv -> Maybe OpaqueId
envCurrentOpaqueId (TCEnv -> ColdEnv
envColdEnv TCEnv
e)) f (Maybe OpaqueId) -> (Maybe OpaqueId -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !Maybe OpaqueId
x -> TCEnv
e {envColdEnv = (envColdEnv e){envCurrentOpaqueId = x}}

{-# INLINE eChasePrefix #-}
eChasePrefix :: Lens' TCEnv (Maybe String)
eChasePrefix :: Lens' TCEnv (Maybe String)
eChasePrefix = \Maybe String -> f (Maybe String)
f TCEnv
e ->
  Maybe String -> f (Maybe String)
f (ColdEnv -> Maybe String
envChasePrefix (TCEnv -> ColdEnv
envColdEnv TCEnv
e)) f (Maybe String) -> (Maybe String -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !Maybe String
x -> TCEnv
e {envColdEnv = (envColdEnv e){envChasePrefix = x}}

{-# INLINE eContext #-}
eContext :: Lens' TCEnv Context
eContext :: Lens' TCEnv Context
eContext = \Context -> f Context
f TCEnv
e ->
  Context -> f Context
f (TCContext -> Context
envContext (TCEnv -> TCContext
envTCContext TCEnv
e)) f Context -> (Context -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !Context
x -> TCEnv
e {envTCContext = (envTCContext e){envContext = x}}

{-# INLINE eLetBindings #-}
eLetBindings :: Lens' TCEnv LetBindings
eLetBindings :: Lens' TCEnv LetBindings
eLetBindings = \LetBindings -> f LetBindings
f TCEnv
e ->
  LetBindings -> f LetBindings
f (TCEnv -> LetBindings
envLetBindings TCEnv
e) f LetBindings -> (LetBindings -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !LetBindings
x -> TCEnv
e {envLetBindings = x}

{-# INLINE eCurrentModule #-}
eCurrentModule :: Lens' TCEnv ModuleName
eCurrentModule :: Lens' TCEnv ModuleName
eCurrentModule = \ModuleName -> f ModuleName
f TCEnv
e ->
  ModuleName -> f ModuleName
f (ColdEnv -> ModuleName
envCurrentModule (TCEnv -> ColdEnv
envColdEnv TCEnv
e)) f ModuleName -> (ModuleName -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !ModuleName
x -> TCEnv
e {envColdEnv = (envColdEnv e){envCurrentModule = x}}

{-# INLINE eCurrentPath #-}
eCurrentPath :: Lens' TCEnv (Maybe FileId)
eCurrentPath :: Lens' TCEnv (Maybe FileId)
eCurrentPath = \Maybe FileId -> f (Maybe FileId)
f TCEnv
e ->
  Maybe FileId -> f (Maybe FileId)
f (ColdEnv -> Maybe FileId
envCurrentPath (ColdEnv -> Maybe FileId) -> ColdEnv -> Maybe FileId
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f (Maybe FileId) -> (Maybe FileId -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !Maybe FileId
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envCurrentPath = x }}

{-# INLINE eAnonymousModules #-}
eAnonymousModules :: Lens' TCEnv [(ModuleName, Nat)]
eAnonymousModules :: Lens' TCEnv [(ModuleName, Int)]
eAnonymousModules = \[(ModuleName, Int)] -> f [(ModuleName, Int)]
f TCEnv
e ->
  [(ModuleName, Int)] -> f [(ModuleName, Int)]
f (ColdEnv -> [(ModuleName, Int)]
envAnonymousModules (ColdEnv -> [(ModuleName, Int)]) -> ColdEnv -> [(ModuleName, Int)]
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f [(ModuleName, Int)] -> ([(ModuleName, Int)] -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ![(ModuleName, Int)]
x -> TCEnv
e {envColdEnv = (envColdEnv e) {envAnonymousModules = x }}

{-# INLINE eImportStack #-}
eImportStack :: Lens' TCEnv [TopLevelModuleName]
eImportStack :: Lens' TCEnv [TopLevelModuleName]
eImportStack = \[TopLevelModuleName] -> f [TopLevelModuleName]
f TCEnv
e ->
  [TopLevelModuleName] -> f [TopLevelModuleName]
f (ColdEnv -> [TopLevelModuleName]
envImportStack (ColdEnv -> [TopLevelModuleName])
-> ColdEnv -> [TopLevelModuleName]
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f [TopLevelModuleName]
-> ([TopLevelModuleName] -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ![TopLevelModuleName]
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envImportStack = x }}

{-# INLINE eMutualBlock #-}
eMutualBlock :: Lens' TCEnv (Maybe MutualId)
eMutualBlock :: Lens' TCEnv (Maybe MutualId)
eMutualBlock = \Maybe MutualId -> f (Maybe MutualId)
f TCEnv
e ->
  Maybe MutualId -> f (Maybe MutualId)
f (ColdEnv -> Maybe MutualId
envMutualBlock (ColdEnv -> Maybe MutualId) -> ColdEnv -> Maybe MutualId
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f (Maybe MutualId) -> (Maybe MutualId -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !Maybe MutualId
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envMutualBlock = x }}

{-# INLINE eTerminationCheck #-}
eTerminationCheck :: Lens' TCEnv TerminationCheck
eTerminationCheck :: Lens' TCEnv TerminationCheck
eTerminationCheck = \TerminationCheck -> f TerminationCheck
f TCEnv
e ->
  TerminationCheck -> f TerminationCheck
f (ColdEnv -> TerminationCheck
envTerminationCheck (ColdEnv -> TerminationCheck) -> ColdEnv -> TerminationCheck
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f TerminationCheck -> (TerminationCheck -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !TerminationCheck
x -> TCEnv
e {envColdEnv = (envColdEnv e) { envTerminationCheck = x }}

{-# INLINE eCoverageCheck #-}
eCoverageCheck :: Lens' TCEnv CoverageCheck
eCoverageCheck :: Lens' TCEnv CoverageCheck
eCoverageCheck = \CoverageCheck -> f CoverageCheck
f TCEnv
e ->
  CoverageCheck -> f CoverageCheck
f (ColdEnv -> CoverageCheck
envCoverageCheck (ColdEnv -> CoverageCheck) -> ColdEnv -> CoverageCheck
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f CoverageCheck -> (CoverageCheck -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !CoverageCheck
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envCoverageCheck = x }}

{-# INLINE eCheckingWhere #-}
eCheckingWhere :: Lens' TCEnv C.WhereClause_
eCheckingWhere :: Lens' TCEnv WhereClause_
eCheckingWhere = \WhereClause_ -> f WhereClause_
f TCEnv
e ->
  WhereClause_ -> f WhereClause_
f (ColdEnv -> WhereClause_
envCheckingWhere (ColdEnv -> WhereClause_) -> ColdEnv -> WhereClause_
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f WhereClause_ -> (WhereClause_ -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !WhereClause_
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envCheckingWhere = x }}

{-# INLINE eActiveProblems #-}
eActiveProblems :: Lens' TCEnv (Set ProblemId)
eActiveProblems :: Lens' TCEnv (Set ProblemId)
eActiveProblems = \Set ProblemId -> f (Set ProblemId)
f TCEnv
e ->
  Set ProblemId -> f (Set ProblemId)
f (TCEnv -> Set ProblemId
envActiveProblems TCEnv
e) f (Set ProblemId) -> (Set ProblemId -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !Set ProblemId
x -> TCEnv
e { envActiveProblems = x }

{-# INLINE eAbstractMode #-}
eAbstractMode :: Lens' TCEnv AbstractMode
eAbstractMode :: Lens' TCEnv AbstractMode
eAbstractMode = \AbstractMode -> f AbstractMode
f TCEnv
e ->
  AbstractMode -> f AbstractMode
f (ColdEnv -> AbstractMode
envAbstractMode (ColdEnv -> AbstractMode) -> ColdEnv -> AbstractMode
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f AbstractMode -> (AbstractMode -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !AbstractMode
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envAbstractMode = x }}

{-# INLINE eRange #-}
eRange :: Lens' TCEnv Range
eRange :: Lens' TCEnv Range
eRange = \Range -> f Range
f TCEnv
e -> Range -> f Range
f (ColdEnv -> Range
envRange (ColdEnv -> Range) -> ColdEnv -> Range
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f Range -> (Range -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Range
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envRange = x }}

{-# INLINE eHighlightingRange #-}
eHighlightingRange :: Lens' TCEnv Range
eHighlightingRange :: Lens' TCEnv Range
eHighlightingRange = \Range -> f Range
f TCEnv
e ->
  Range -> f Range
f (ColdEnv -> Range
envHighlightingRange (ColdEnv -> Range) -> ColdEnv -> Range
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f Range -> (Range -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Range
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envHighlightingRange = x }}

{-# INLINE eCall #-}
eCall :: Lens' TCEnv (Maybe (Closure Call))
eCall :: Lens' TCEnv (Maybe (Closure Call))
eCall = \Maybe (Closure Call) -> f (Maybe (Closure Call))
f TCEnv
e -> Maybe (Closure Call) -> f (Maybe (Closure Call))
f (ColdEnv -> Maybe (Closure Call)
envCall (ColdEnv -> Maybe (Closure Call))
-> ColdEnv -> Maybe (Closure Call)
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f (Maybe (Closure Call))
-> (Maybe (Closure Call) -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Maybe (Closure Call)
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envCall = x }}

{-# INLINE eHighlightingLevel #-}
eHighlightingLevel :: Lens' TCEnv HighlightingLevel
eHighlightingLevel :: Lens' TCEnv HighlightingLevel
eHighlightingLevel = \HighlightingLevel -> f HighlightingLevel
f TCEnv
e ->
  HighlightingLevel -> f HighlightingLevel
f (ColdEnv -> HighlightingLevel
envHighlightingLevel (ColdEnv -> HighlightingLevel) -> ColdEnv -> HighlightingLevel
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f HighlightingLevel -> (HighlightingLevel -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !HighlightingLevel
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envHighlightingLevel = x }}

{-# INLINE eHighlightingMethod #-}
eHighlightingMethod :: Lens' TCEnv HighlightingMethod
eHighlightingMethod :: Lens' TCEnv HighlightingMethod
eHighlightingMethod = \HighlightingMethod -> f HighlightingMethod
f TCEnv
e ->
  HighlightingMethod -> f HighlightingMethod
f (ColdEnv -> HighlightingMethod
envHighlightingMethod (ColdEnv -> HighlightingMethod) -> ColdEnv -> HighlightingMethod
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f HighlightingMethod -> (HighlightingMethod -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !HighlightingMethod
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envHighlightingMethod = x }}

{-# INLINE eExpandLast #-}
eExpandLast :: Lens' TCEnv ExpandHidden
eExpandLast :: Lens' TCEnv ExpandHidden
eExpandLast = \ExpandHidden -> f ExpandHidden
f TCEnv
e ->
  ExpandHidden -> f ExpandHidden
f (ColdEnv -> ExpandHidden
envExpandLast (ColdEnv -> ExpandHidden) -> ColdEnv -> ExpandHidden
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f ExpandHidden -> (ExpandHidden -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ !ExpandHidden
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envExpandLast = x }}

{-# INLINE eExpandLastBool #-}
eExpandLastBool :: Lens' TCEnv Bool
eExpandLastBool :: Lens' TCEnv Bool
eExpandLastBool = \Bool -> f Bool
f TCEnv
e ->
  Bool -> f Bool
f (ExpandHidden -> Bool
isExpandLast (ExpandHidden -> Bool) -> ExpandHidden -> Bool
forall a b. (a -> b) -> a -> b
$ ColdEnv -> ExpandHidden
envExpandLast (ColdEnv -> ExpandHidden) -> ColdEnv -> ExpandHidden
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f Bool -> (Bool -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Bool
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envExpandLast = toExpandLast x }}

{-# INLINE eAppDef #-}
eAppDef :: Lens' TCEnv (Maybe QName)
eAppDef :: Lens' TCEnv (Maybe QName)
eAppDef = \Maybe QName -> f (Maybe QName)
f TCEnv
e ->
  Maybe QName -> f (Maybe QName)
f (TCContext -> Maybe QName
envAppDef (TCContext -> Maybe QName) -> TCContext -> Maybe QName
forall a b. (a -> b) -> a -> b
$ TCEnv -> TCContext
envTCContext TCEnv
e) f (Maybe QName) -> (Maybe QName -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Maybe QName
x -> TCEnv
e {envTCContext = (envTCContext e){ envAppDef = x }}

{-# INLINE eSimplification #-}
eSimplification :: Lens' TCEnv Simplification
eSimplification :: Lens' TCEnv Simplification
eSimplification = \Simplification -> f Simplification
f TCEnv
e ->
  Simplification -> f Simplification
f (ColdEnv -> Simplification
envSimplification (ColdEnv -> Simplification) -> ColdEnv -> Simplification
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f Simplification -> (Simplification -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Simplification
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envSimplification = x }}

{-# INLINE eAllowedReductions #-}
eAllowedReductions :: Lens' TCEnv AllowedReductions
eAllowedReductions :: Lens' TCEnv AllowedReductions
eAllowedReductions = \AllowedReductions -> f AllowedReductions
f TCEnv
e ->
  AllowedReductions -> f AllowedReductions
f (TCEnv -> AllowedReductions
envAllowedReductions TCEnv
e) f AllowedReductions -> (AllowedReductions -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ AllowedReductions
x -> TCEnv
e {envAllowedReductions = x }

{-# INLINE eReduceDefs #-}
eReduceDefs :: Lens' TCEnv ReduceDefs
eReduceDefs :: Lens' TCEnv ReduceDefs
eReduceDefs = \ReduceDefs -> f ReduceDefs
f TCEnv
e ->
  ReduceDefs -> f ReduceDefs
f (ColdEnv -> ReduceDefs
envReduceDefs (ColdEnv -> ReduceDefs) -> ColdEnv -> ReduceDefs
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f ReduceDefs -> (ReduceDefs -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ ReduceDefs
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envReduceDefs = x }}

{-# INLINE eReduceDefsPair #-}
eReduceDefsPair :: Lens' TCEnv (Bool, [QName])
eReduceDefsPair :: Lens' TCEnv (Bool, [QName])
eReduceDefsPair = \(Bool, [QName]) -> f (Bool, [QName])
f TCEnv
e ->
  (Bool, [QName]) -> f (Bool, [QName])
f (ReduceDefs -> (Bool, [QName])
fromReduceDefs (ReduceDefs -> (Bool, [QName])) -> ReduceDefs -> (Bool, [QName])
forall a b. (a -> b) -> a -> b
$ ColdEnv -> ReduceDefs
envReduceDefs (ColdEnv -> ReduceDefs) -> ColdEnv -> ReduceDefs
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f (Bool, [QName]) -> ((Bool, [QName]) -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ (Bool, [QName])
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envReduceDefs = toReduceDefs x }}

{-# INLINE eInjectivityDepth #-}
eInjectivityDepth :: Lens' TCEnv Int
eInjectivityDepth :: Lens' TCEnv Int
eInjectivityDepth = \Int -> f Int
f TCEnv
e ->
  Int -> f Int
f (ColdEnv -> Int
envInjectivityDepth (ColdEnv -> Int) -> ColdEnv -> Int
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f Int -> (Int -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Int
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envInjectivityDepth = x }}

{-# INLINE eUnquoteFlags #-}
eUnquoteFlags :: Lens' TCEnv UnquoteFlags
eUnquoteFlags :: Lens' TCEnv UnquoteFlags
eUnquoteFlags = \UnquoteFlags -> f UnquoteFlags
f TCEnv
e ->
  UnquoteFlags -> f UnquoteFlags
f (ColdEnv -> UnquoteFlags
envUnquoteFlags (ColdEnv -> UnquoteFlags) -> ColdEnv -> UnquoteFlags
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f UnquoteFlags -> (UnquoteFlags -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ UnquoteFlags
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envUnquoteFlags = x }}

{-# INLINE eInstanceDepth #-}
eInstanceDepth :: Lens' TCEnv Int
eInstanceDepth :: Lens' TCEnv Int
eInstanceDepth = \Int -> f Int
f TCEnv
e ->
  Int -> f Int
f (ColdEnv -> Int
envInstanceDepth (ColdEnv -> Int) -> ColdEnv -> Int
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f Int -> (Int -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Int
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envInstanceDepth = x }}

{-# INLINE ePrintingPatternLambdas #-}
ePrintingPatternLambdas :: Lens' TCEnv [QName]
ePrintingPatternLambdas :: Lens' TCEnv [QName]
ePrintingPatternLambdas = \[QName] -> f [QName]
f TCEnv
e ->
  [QName] -> f [QName]
f (ColdEnv -> [QName]
envPrintingPatternLambdas (ColdEnv -> [QName]) -> ColdEnv -> [QName]
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f [QName] -> ([QName] -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ [QName]
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envPrintingPatternLambdas = x }}

{-# INLINE eCurrentCheckpoint #-}
eCurrentCheckpoint :: Lens' TCEnv CheckpointId
eCurrentCheckpoint :: Lens' TCEnv CheckpointId
eCurrentCheckpoint = \CheckpointId -> f CheckpointId
f TCEnv
e ->
  CheckpointId -> f CheckpointId
f (TCContext -> CheckpointId
envCurrentCheckpoint (TCContext -> CheckpointId) -> TCContext -> CheckpointId
forall a b. (a -> b) -> a -> b
$ TCEnv -> TCContext
envTCContext TCEnv
e) f CheckpointId -> (CheckpointId -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ CheckpointId
x -> TCEnv
e {envTCContext = (envTCContext e){ envCurrentCheckpoint = x }}

{-# INLINE eCheckpoints #-}
eCheckpoints :: Lens' TCEnv (Map CheckpointId Substitution)
eCheckpoints :: Lens' TCEnv (Map CheckpointId Substitution)
eCheckpoints = \Map CheckpointId Substitution -> f (Map CheckpointId Substitution)
f TCEnv
e ->
  Map CheckpointId Substitution -> f (Map CheckpointId Substitution)
f (TCContext -> Map CheckpointId Substitution
envCheckpoints (TCContext -> Map CheckpointId Substitution)
-> TCContext -> Map CheckpointId Substitution
forall a b. (a -> b) -> a -> b
$ TCEnv -> TCContext
envTCContext TCEnv
e) f (Map CheckpointId Substitution)
-> (Map CheckpointId Substitution -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Map CheckpointId Substitution
x -> TCEnv
e {envTCContext = (envTCContext e){ envCheckpoints = x }}

{-# INLINE eGeneralizeMetas #-}
eGeneralizeMetas :: Lens' TCEnv DoGeneralize
eGeneralizeMetas :: Lens' TCEnv DoGeneralize
eGeneralizeMetas = \DoGeneralize -> f DoGeneralize
f TCEnv
e ->
  DoGeneralize -> f DoGeneralize
f (ColdEnv -> DoGeneralize
envGeneralizeMetas (ColdEnv -> DoGeneralize) -> ColdEnv -> DoGeneralize
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f DoGeneralize -> (DoGeneralize -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ DoGeneralize
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envGeneralizeMetas = x }}

{-# INLINE eGeneralizedVars #-}
eGeneralizedVars :: Lens' TCEnv (Map QName GeneralizedValue)
eGeneralizedVars :: Lens' TCEnv (Map QName GeneralizedValue)
eGeneralizedVars = \Map QName GeneralizedValue -> f (Map QName GeneralizedValue)
f TCEnv
e ->
  Map QName GeneralizedValue -> f (Map QName GeneralizedValue)
f (ColdEnv -> Map QName GeneralizedValue
envGeneralizedVars (ColdEnv -> Map QName GeneralizedValue)
-> ColdEnv -> Map QName GeneralizedValue
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f (Map QName GeneralizedValue)
-> (Map QName GeneralizedValue -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Map QName GeneralizedValue
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envGeneralizedVars = x }}

{-# INLINE eActiveBackendName #-}
eActiveBackendName :: Lens' TCEnv (Maybe BackendName)
eActiveBackendName :: Lens' TCEnv (Maybe ShortText)
eActiveBackendName = \Maybe ShortText -> f (Maybe ShortText)
f TCEnv
e ->
  Maybe ShortText -> f (Maybe ShortText)
f (ColdEnv -> Maybe ShortText
envActiveBackendName (ColdEnv -> Maybe ShortText) -> ColdEnv -> Maybe ShortText
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv TCEnv
e) f (Maybe ShortText) -> (Maybe ShortText -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Maybe ShortText
x -> TCEnv
e {envColdEnv = (envColdEnv e){ envActiveBackendName = x }}

----------------------------------------------------------------------------------------------------

{-# INLINE mkEnvFlag #-}
mkEnvFlag :: Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag :: Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag Lens' Flags64 Bool
l = \Bool -> f Bool
f TCEnv
s ->
  let !old :: Bool
old = Getting Bool Flags64 Bool -> Flags64 -> Bool
forall s (m :: * -> *) a. MonadReader s m => Getting a s a -> m a
view Getting Bool Flags64 Bool
Lens' Flags64 Bool
l (TCEnv -> Flags64
envFlags TCEnv
s) in
  Bool -> f Bool
f Bool
old f Bool -> (Bool -> TCEnv) -> f TCEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \Bool
b ->
    -- avoiding copy on unchanged flags
    if Bool
b Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
old then TCEnv
s else TCEnv
s {envFlags = set l b (envFlags s)}

{-# INLINE eReconstructed #-}
eReconstructed :: Lens' TCEnv Bool
eReconstructed :: Lens' TCEnv Bool
eReconstructed = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envReconstructed

{-# INLINE eCompareBlocked #-}
eCompareBlocked :: Lens' TCEnv Bool
eCompareBlocked :: Lens' TCEnv Bool
eCompareBlocked = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envCompareBlocked

{-# INLINE ePrintDomainFreePi #-}
ePrintDomainFreePi :: Lens' TCEnv Bool
ePrintDomainFreePi :: Lens' TCEnv Bool
ePrintDomainFreePi = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envPrintDomainFreePi

{-# INLINE ePrintMetasBare #-}
ePrintMetasBare :: Lens' TCEnv Bool
ePrintMetasBare :: Lens' TCEnv Bool
ePrintMetasBare = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envPrintMetasBare

{-# INLINE eInsideDotPattern #-}
eInsideDotPattern :: Lens' TCEnv Bool
eInsideDotPattern :: Lens' TCEnv Bool
eInsideDotPattern = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envInsideDotPattern

{-# INLINE eIsDebugPrinting #-}
eIsDebugPrinting :: Lens' TCEnv Bool
eIsDebugPrinting :: Lens' TCEnv Bool
eIsDebugPrinting = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envIsDebugPrinting

{-# INLINE eCallByNeed #-}
eCallByNeed :: Lens' TCEnv Bool
eCallByNeed :: Lens' TCEnv Bool
eCallByNeed = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envCallByNeed

{-# INLINE eMakeCase #-}
eMakeCase :: Lens' TCEnv Bool
eMakeCase :: Lens' TCEnv Bool
eMakeCase = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envMakeCase

{-# INLINE eSolvingConstraints #-}
eSolvingConstraints :: Lens' TCEnv Bool
eSolvingConstraints :: Lens' TCEnv Bool
eSolvingConstraints = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envSolvingConstraints

{-# INLINE eAssignMetas #-}
eAssignMetas :: Lens' TCEnv Bool
eAssignMetas :: Lens' TCEnv Bool
eAssignMetas = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envAssignMetas

{-# INLINE eSplitOnStrict #-}
eSplitOnStrict :: Lens' TCEnv Bool
eSplitOnStrict :: Lens' TCEnv Bool
eSplitOnStrict = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envSplitOnStrict

{-# INLINE eDisplayFormsEnabled #-}
eDisplayFormsEnabled :: Lens' TCEnv Bool
eDisplayFormsEnabled :: Lens' TCEnv Bool
eDisplayFormsEnabled = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envDisplayFormsEnabled

{-# INLINE eFoldLetBindings #-}
eFoldLetBindings :: Lens' TCEnv Bool
eFoldLetBindings :: Lens' TCEnv Bool
eFoldLetBindings = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envFoldLetBindings

{-# INLINE eCurrentlyElaborating #-}
eCurrentlyElaborating :: Lens' TCEnv Bool
eCurrentlyElaborating :: Lens' TCEnv Bool
eCurrentlyElaborating = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envCurrentlyElaborating

{-# INLINE eWorkingOnTypes #-}
eWorkingOnTypes :: Lens' TCEnv Bool
eWorkingOnTypes :: Lens' TCEnv Bool
eWorkingOnTypes = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envWorkingOnTypes

{-# INLINE ePureConversion #-}
ePureConversion :: Lens' TCEnv Bool
ePureConversion :: Lens' TCEnv Bool
ePureConversion = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envPureConversion

{-# INLINE eHardErrors #-}
eHardErrors :: Lens' TCEnv Bool
eHardErrors :: Lens' TCEnv Bool
eHardErrors = Lens' Flags64 Bool -> Lens' TCEnv Bool
mkEnvFlag (Bool -> f Bool) -> Flags64 -> f Flags64
Lens' Flags64 Bool
envHardErrors

----------------------------------------------------------------------------------------------------

class LensTCEnv a where
  lensTCEnv :: Lens' a TCEnv

instance LensTCEnv TCEnv where
  lensTCEnv :: Lens' TCEnv TCEnv
lensTCEnv = (TCEnv -> f TCEnv) -> TCEnv -> f TCEnv
forall a. a -> a
id

data UnquoteFlags = UnquoteFlags { UnquoteFlags -> Bool
_unquoteNormalise :: Bool }
  deriving (forall x. UnquoteFlags -> Rep UnquoteFlags x)
-> (forall x. Rep UnquoteFlags x -> UnquoteFlags)
-> Generic UnquoteFlags
forall x. Rep UnquoteFlags x -> UnquoteFlags
forall x. UnquoteFlags -> Rep UnquoteFlags x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. UnquoteFlags -> Rep UnquoteFlags x
from :: forall x. UnquoteFlags -> Rep UnquoteFlags x
$cto :: forall x. Rep UnquoteFlags x -> UnquoteFlags
to :: forall x. Rep UnquoteFlags x -> UnquoteFlags
Generic

defaultUnquoteFlags :: UnquoteFlags
defaultUnquoteFlags :: UnquoteFlags
defaultUnquoteFlags = UnquoteFlags
  { _unquoteNormalise :: Bool
_unquoteNormalise = Bool
False }

unquoteNormalise :: Lens' UnquoteFlags Bool
unquoteNormalise :: Lens' UnquoteFlags Bool
unquoteNormalise Bool -> f Bool
f UnquoteFlags
e = Bool -> f Bool
f (UnquoteFlags -> Bool
_unquoteNormalise UnquoteFlags
e) f Bool -> (Bool -> UnquoteFlags) -> f UnquoteFlags
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ Bool
x -> UnquoteFlags
e { _unquoteNormalise = x }

eUnquoteNormalise :: Lens' TCEnv Bool
eUnquoteNormalise :: Lens' TCEnv Bool
eUnquoteNormalise = (UnquoteFlags -> f UnquoteFlags) -> TCEnv -> f TCEnv
Lens' TCEnv UnquoteFlags
eUnquoteFlags ((UnquoteFlags -> f UnquoteFlags) -> TCEnv -> f TCEnv)
-> ((Bool -> f Bool) -> UnquoteFlags -> f UnquoteFlags)
-> (Bool -> f Bool)
-> TCEnv
-> f TCEnv
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Bool -> f Bool) -> UnquoteFlags -> f UnquoteFlags
Lens' UnquoteFlags Bool
unquoteNormalise

----------------------------------------------------------------------------------------------------
-- ** Let bindings
----------------------------------------------------------------------------------------------------

type LetBindings = Map Name (Open LetBinding)

data LetBinding = LetBinding
  { LetBinding -> IsAxiom
letAxiom  :: IsAxiom    -- ^ Does this let binding origin from a 'LetAxiom'?
  , LetBinding -> Origin
letOrigin :: Origin
  , LetBinding -> Term
letTerm   :: Term
  , LetBinding -> Dom Type
letType   :: Dom Type
  }
  deriving (Int -> LetBinding -> ShowS
[LetBinding] -> ShowS
LetBinding -> String
(Int -> LetBinding -> ShowS)
-> (LetBinding -> String)
-> ([LetBinding] -> ShowS)
-> Show LetBinding
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LetBinding -> ShowS
showsPrec :: Int -> LetBinding -> ShowS
$cshow :: LetBinding -> String
show :: LetBinding -> String
$cshowList :: [LetBinding] -> ShowS
showList :: [LetBinding] -> ShowS
Show, (forall x. LetBinding -> Rep LetBinding x)
-> (forall x. Rep LetBinding x -> LetBinding) -> Generic LetBinding
forall x. Rep LetBinding x -> LetBinding
forall x. LetBinding -> Rep LetBinding x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. LetBinding -> Rep LetBinding x
from :: forall x. LetBinding -> Rep LetBinding x
$cto :: forall x. Rep LetBinding x -> LetBinding
to :: forall x. Rep LetBinding x -> LetBinding
Generic)

onLetBindingType :: (Dom Type -> Dom Type) -> LetBinding -> LetBinding
onLetBindingType :: (Dom Type -> Dom Type) -> LetBinding -> LetBinding
onLetBindingType Dom Type -> Dom Type
f LetBinding
b = LetBinding
b { letType = f $ letType b }

data IsAxiom
  = YesAxiom
  | NoAxiom
  deriving (IsAxiom -> IsAxiom -> Bool
(IsAxiom -> IsAxiom -> Bool)
-> (IsAxiom -> IsAxiom -> Bool) -> Eq IsAxiom
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: IsAxiom -> IsAxiom -> Bool
== :: IsAxiom -> IsAxiom -> Bool
$c/= :: IsAxiom -> IsAxiom -> Bool
/= :: IsAxiom -> IsAxiom -> Bool
Eq, Int -> IsAxiom -> ShowS
[IsAxiom] -> ShowS
IsAxiom -> String
(Int -> IsAxiom -> ShowS)
-> (IsAxiom -> String) -> ([IsAxiom] -> ShowS) -> Show IsAxiom
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> IsAxiom -> ShowS
showsPrec :: Int -> IsAxiom -> ShowS
$cshow :: IsAxiom -> String
show :: IsAxiom -> String
$cshowList :: [IsAxiom] -> ShowS
showList :: [IsAxiom] -> ShowS
Show, (forall x. IsAxiom -> Rep IsAxiom x)
-> (forall x. Rep IsAxiom x -> IsAxiom) -> Generic IsAxiom
forall x. Rep IsAxiom x -> IsAxiom
forall x. IsAxiom -> Rep IsAxiom x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. IsAxiom -> Rep IsAxiom x
from :: forall x. IsAxiom -> Rep IsAxiom x
$cto :: forall x. Rep IsAxiom x -> IsAxiom
to :: forall x. Rep IsAxiom x -> IsAxiom
Generic)

----------------------------------------------------------------------------------------------------
-- ** Abstract mode
----------------------------------------------------------------------------------------------------

data AbstractMode
  = AbstractMode        -- ^ Abstract things in the current module can be accessed.
  | ConcreteMode        -- ^ No abstract things can be accessed.
  | IgnoreAbstractMode  -- ^ All abstract things can be accessed.
  deriving (Int -> AbstractMode -> ShowS
[AbstractMode] -> ShowS
AbstractMode -> String
(Int -> AbstractMode -> ShowS)
-> (AbstractMode -> String)
-> ([AbstractMode] -> ShowS)
-> Show AbstractMode
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AbstractMode -> ShowS
showsPrec :: Int -> AbstractMode -> ShowS
$cshow :: AbstractMode -> String
show :: AbstractMode -> String
$cshowList :: [AbstractMode] -> ShowS
showList :: [AbstractMode] -> ShowS
Show, AbstractMode -> AbstractMode -> Bool
(AbstractMode -> AbstractMode -> Bool)
-> (AbstractMode -> AbstractMode -> Bool) -> Eq AbstractMode
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AbstractMode -> AbstractMode -> Bool
== :: AbstractMode -> AbstractMode -> Bool
$c/= :: AbstractMode -> AbstractMode -> Bool
/= :: AbstractMode -> AbstractMode -> Bool
Eq, (forall x. AbstractMode -> Rep AbstractMode x)
-> (forall x. Rep AbstractMode x -> AbstractMode)
-> Generic AbstractMode
forall x. Rep AbstractMode x -> AbstractMode
forall x. AbstractMode -> Rep AbstractMode x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. AbstractMode -> Rep AbstractMode x
from :: forall x. AbstractMode -> Rep AbstractMode x
$cto :: forall x. Rep AbstractMode x -> AbstractMode
to :: forall x. Rep AbstractMode x -> AbstractMode
Generic)

aDefToMode :: IsAbstract -> AbstractMode
aDefToMode :: IsAbstract -> AbstractMode
aDefToMode IsAbstract
AbstractDef = AbstractMode
AbstractMode
aDefToMode IsAbstract
ConcreteDef = AbstractMode
ConcreteMode

aModeToDef :: AbstractMode -> Maybe IsAbstract
aModeToDef :: AbstractMode -> Maybe IsAbstract
aModeToDef AbstractMode
AbstractMode = IsAbstract -> Maybe IsAbstract
forall a. a -> Maybe a
Just IsAbstract
AbstractDef
aModeToDef AbstractMode
ConcreteMode = IsAbstract -> Maybe IsAbstract
forall a. a -> Maybe a
Just IsAbstract
ConcreteDef
aModeToDef AbstractMode
_ = Maybe IsAbstract
forall a. Maybe a
Nothing

----------------------------------------------------------------------------------------------------
-- ** Opaque blocks
----------------------------------------------------------------------------------------------------

-- | A block of opaque definitions.
data OpaqueBlock = OpaqueBlock
  { OpaqueBlock -> OpaqueId
opaqueId        :: {-# UNPACK #-} !OpaqueId
    -- ^ Unique identifier for this block.
  , OpaqueBlock -> HashSet QName
opaqueUnfolding :: HashSet QName
    -- ^ Set of names we are allowed to unfold. After scope-checking,
    -- this set should be transitively closed.
  , OpaqueBlock -> HashSet QName
opaqueDecls     :: HashSet QName
    -- ^ Declarations contained in this abstract block.
  , OpaqueBlock -> Maybe OpaqueId
opaqueParent    :: Maybe OpaqueId
    -- ^ Pointer to an enclosing opaque block, if one exists.
  , OpaqueBlock -> Range
opaqueRange     :: Range
    -- ^ Where is this opaque block?
  } deriving (Int -> OpaqueBlock -> ShowS
[OpaqueBlock] -> ShowS
OpaqueBlock -> String
(Int -> OpaqueBlock -> ShowS)
-> (OpaqueBlock -> String)
-> ([OpaqueBlock] -> ShowS)
-> Show OpaqueBlock
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> OpaqueBlock -> ShowS
showsPrec :: Int -> OpaqueBlock -> ShowS
$cshow :: OpaqueBlock -> String
show :: OpaqueBlock -> String
$cshowList :: [OpaqueBlock] -> ShowS
showList :: [OpaqueBlock] -> ShowS
Show, (forall x. OpaqueBlock -> Rep OpaqueBlock x)
-> (forall x. Rep OpaqueBlock x -> OpaqueBlock)
-> Generic OpaqueBlock
forall x. Rep OpaqueBlock x -> OpaqueBlock
forall x. OpaqueBlock -> Rep OpaqueBlock x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. OpaqueBlock -> Rep OpaqueBlock x
from :: forall x. OpaqueBlock -> Rep OpaqueBlock x
$cto :: forall x. Rep OpaqueBlock x -> OpaqueBlock
to :: forall x. Rep OpaqueBlock x -> OpaqueBlock
Generic)

instance Pretty OpaqueBlock where
  pretty :: OpaqueBlock -> Doc
pretty (OpaqueBlock OpaqueId
_ HashSet QName
uf HashSet QName
ds Maybe OpaqueId
p Range
_) = [Doc] -> Doc
forall (t :: * -> *). Foldable t => t Doc -> Doc
vcat
    ([Doc] -> Doc) -> [Doc] -> Doc
forall a b. (a -> b) -> a -> b
$ [ Doc
"opaque (extends " Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Maybe OpaqueId -> Doc
forall a. Pretty a => a -> Doc
pretty Maybe OpaqueId
p Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
") {"
      , Int -> Doc -> Doc
forall a. Int -> Doc a -> Doc a
nest Int
2 Doc
"unfolds"
      ]
    [Doc] -> [Doc] -> [Doc]
forall a. [a] -> [a] -> [a]
++ [ Int -> Doc -> Doc
forall a. Int -> Doc a -> Doc a
nest Int
4 (QName -> Doc
forall a. Pretty a => a -> Doc
pretty QName
n Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
",") | QName
n <- [QName] -> [QName]
forall a. Ord a => [a] -> [a]
List.sort ([QName] -> [QName]) -> [QName] -> [QName]
forall a b. (a -> b) -> a -> b
$ HashSet QName -> [QName]
forall a. HashSet a -> [a]
HashSet.toList HashSet QName
uf ]
         -- Andreas, 2023-08-10, https://github.com/agda/agda/pull/6628#discussion_r1285078454
         -- The HashSet.toList is non-deterministic, order may depend on version of @hashable@.
         -- Thus, we sort the list, so that the output isn't dependent on the specific build.
    [Doc] -> [Doc] -> [Doc]
forall a. [a] -> [a] -> [a]
++ [ Int -> Doc -> Doc
forall a. Int -> Doc a -> Doc a
nest Int
2 Doc
"declares" ]
    [Doc] -> [Doc] -> [Doc]
forall a. [a] -> [a] -> [a]
++ [ Int -> Doc -> Doc
forall a. Int -> Doc a -> Doc a
nest Int
4 (QName -> Doc
forall a. Pretty a => a -> Doc
pretty QName
n Doc -> Doc -> Doc
forall a. Doc a -> Doc a -> Doc a
<+> Doc
": _") | QName
n <- [QName] -> [QName]
forall a. Ord a => [a] -> [a]
List.sort ([QName] -> [QName]) -> [QName] -> [QName]
forall a b. (a -> b) -> a -> b
$ HashSet QName -> [QName]
forall a. HashSet a -> [a]
HashSet.toList HashSet QName
ds ]
    [Doc] -> [Doc] -> [Doc]
forall a. [a] -> [a] -> [a]
++ [ Doc
"}" ]

instance Eq OpaqueBlock where
  OpaqueBlock
xs == :: OpaqueBlock -> OpaqueBlock -> Bool
== OpaqueBlock
ys = OpaqueBlock -> OpaqueId
opaqueId OpaqueBlock
xs OpaqueId -> OpaqueId -> Bool
forall a. Eq a => a -> a -> Bool
== OpaqueBlock -> OpaqueId
opaqueId OpaqueBlock
ys

instance Hashable OpaqueBlock where
  hashWithSalt :: Int -> OpaqueBlock -> Int
hashWithSalt Int
s = Int -> OpaqueId -> Int
forall a. Hashable a => Int -> a -> Int
hashWithSalt Int
s (OpaqueId -> Int)
-> (OpaqueBlock -> OpaqueId) -> OpaqueBlock -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OpaqueBlock -> OpaqueId
opaqueId

----------------------------------------------------------------------------------------------------
-- ** Insertion of implicit arguments
----------------------------------------------------------------------------------------------------

data ExpandHidden
  = ExpandLast      -- ^ Add implicit arguments in the end until type is no longer hidden 'Pi'.
  | DontExpandLast  -- ^ Do not append implicit arguments.
  | ReallyDontExpandLast -- ^ Makes 'doExpandLast' have no effect. Used to avoid implicit insertion of arguments to metavariables.
  deriving (ExpandHidden -> ExpandHidden -> Bool
(ExpandHidden -> ExpandHidden -> Bool)
-> (ExpandHidden -> ExpandHidden -> Bool) -> Eq ExpandHidden
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ExpandHidden -> ExpandHidden -> Bool
== :: ExpandHidden -> ExpandHidden -> Bool
$c/= :: ExpandHidden -> ExpandHidden -> Bool
/= :: ExpandHidden -> ExpandHidden -> Bool
Eq, (forall x. ExpandHidden -> Rep ExpandHidden x)
-> (forall x. Rep ExpandHidden x -> ExpandHidden)
-> Generic ExpandHidden
forall x. Rep ExpandHidden x -> ExpandHidden
forall x. ExpandHidden -> Rep ExpandHidden x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ExpandHidden -> Rep ExpandHidden x
from :: forall x. ExpandHidden -> Rep ExpandHidden x
$cto :: forall x. Rep ExpandHidden x -> ExpandHidden
to :: forall x. Rep ExpandHidden x -> ExpandHidden
Generic)

isExpandLast :: ExpandHidden -> Bool
isExpandLast :: ExpandHidden -> Bool
isExpandLast ExpandHidden
ExpandLast           = Bool
True
isExpandLast ExpandHidden
DontExpandLast       = Bool
False
isExpandLast ExpandHidden
ReallyDontExpandLast = Bool
False

isDontExpandLast :: ExpandHidden -> Bool
isDontExpandLast :: ExpandHidden -> Bool
isDontExpandLast = Bool -> Bool
not (Bool -> Bool) -> (ExpandHidden -> Bool) -> ExpandHidden -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ExpandHidden -> Bool
isExpandLast

toExpandLast :: Bool -> ExpandHidden
toExpandLast :: Bool -> ExpandHidden
toExpandLast Bool
True  = ExpandHidden
ExpandLast
toExpandLast Bool
False = ExpandHidden
DontExpandLast

data CandidateKind
  = LocalCandidate
  | GlobalCandidate QName
  deriving (Int -> CandidateKind -> ShowS
[CandidateKind] -> ShowS
CandidateKind -> String
(Int -> CandidateKind -> ShowS)
-> (CandidateKind -> String)
-> ([CandidateKind] -> ShowS)
-> Show CandidateKind
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CandidateKind -> ShowS
showsPrec :: Int -> CandidateKind -> ShowS
$cshow :: CandidateKind -> String
show :: CandidateKind -> String
$cshowList :: [CandidateKind] -> ShowS
showList :: [CandidateKind] -> ShowS
Show, (forall x. CandidateKind -> Rep CandidateKind x)
-> (forall x. Rep CandidateKind x -> CandidateKind)
-> Generic CandidateKind
forall x. Rep CandidateKind x -> CandidateKind
forall x. CandidateKind -> Rep CandidateKind x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. CandidateKind -> Rep CandidateKind x
from :: forall x. CandidateKind -> Rep CandidateKind x
$cto :: forall x. Rep CandidateKind x -> CandidateKind
to :: forall x. Rep CandidateKind x -> CandidateKind
Generic)

-- | A candidate solution for an instance meta is a term with its type.
--   It may be the case that the candidate is not fully applied yet or
--   of the wrong type, hence the need for the type.
data Candidate  = Candidate
  { Candidate -> CandidateKind
candidateKind    :: CandidateKind
  , Candidate -> Term
candidateTerm    :: Term
  , Candidate -> Type
candidateType    :: Type
  , Candidate -> OverlapMode
candidateOverlap :: OverlapMode
  }
  deriving (Int -> Candidate -> ShowS
[Candidate] -> ShowS
Candidate -> String
(Int -> Candidate -> ShowS)
-> (Candidate -> String)
-> ([Candidate] -> ShowS)
-> Show Candidate
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Candidate -> ShowS
showsPrec :: Int -> Candidate -> ShowS
$cshow :: Candidate -> String
show :: Candidate -> String
$cshowList :: [Candidate] -> ShowS
showList :: [Candidate] -> ShowS
Show, (forall x. Candidate -> Rep Candidate x)
-> (forall x. Rep Candidate x -> Candidate) -> Generic Candidate
forall x. Rep Candidate x -> Candidate
forall x. Candidate -> Rep Candidate x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Candidate -> Rep Candidate x
from :: forall x. Candidate -> Rep Candidate x
$cto :: forall x. Rep Candidate x -> Candidate
to :: forall x. Rep Candidate x -> Candidate
Generic)

instance Free Candidate where
  freeVars :: forall r. ComputeFree r => Candidate -> Reader r (Collect r)
freeVars Candidate
c = ((Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
 -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r)
forall a.
ExpandCase LiftedRep a =>
((a -> Result LiftedRep a) -> Result LiftedRep a) -> a
expand \Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret -> case Candidate
c of
    Candidate CandidateKind
_ Term
t Type
u OverlapMode
_ -> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
ret (Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r)))
-> Reader r (Collect r) -> Result LiftedRep (Reader r (Collect r))
forall a b. (a -> b) -> a -> b
$ (Term, Type) -> Reader r (Collect r)
forall r. ComputeFree r => (Term, Type) -> Reader r (Collect r)
forall t r. (Free t, ComputeFree r) => t -> Reader r (Collect r)
freeVars (Term
t, Type
u)

instance HasOverlapMode Candidate where
  lensOverlapMode :: Lens' Candidate OverlapMode
lensOverlapMode OverlapMode -> f OverlapMode
f Candidate
x = OverlapMode -> f OverlapMode
f (Candidate -> OverlapMode
candidateOverlap Candidate
x) f OverlapMode -> (OverlapMode -> Candidate) -> f Candidate
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \OverlapMode
m -> Candidate
x{ candidateOverlap = m }

----------------------------------------------------------------------------------------------------
-- ** Checking arguments
----------------------------------------------------------------------------------------------------

data CheckedArg = CheckedArg
  { CheckedArg -> Elim
caElim        :: Elim
      -- ^ Checked and inserted argument.
  , CheckedArg -> Range
caRange       :: Range
      -- ^ Range of checked argument, where present.
      --   E.g. inserted implicits have no correponding abstract syntax.
  }
  deriving Int -> CheckedArg -> ShowS
[CheckedArg] -> ShowS
CheckedArg -> String
(Int -> CheckedArg -> ShowS)
-> (CheckedArg -> String)
-> ([CheckedArg] -> ShowS)
-> Show CheckedArg
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CheckedArg -> ShowS
showsPrec :: Int -> CheckedArg -> ShowS
$cshow :: CheckedArg -> String
show :: CheckedArg -> String
$cshowList :: [CheckedArg] -> ShowS
showList :: [CheckedArg] -> ShowS
Show

data ArgsCheckState a = ACState
  { forall a. ArgsCheckState a -> [CheckedArg]
acCheckedArgs :: [CheckedArg]
      -- ^ Checked and inserted arguments so far.
  , forall a. ArgsCheckState a -> Expr
acFun         :: A.Expr
      -- ^ The function applied to the already checked arguments.
  , forall a. ArgsCheckState a -> Type
acType        :: Type
      -- ^ Type of the function (for checking the remaining arguments).
  , forall a. ArgsCheckState a -> a
acData        :: a
  }
  deriving Int -> ArgsCheckState a -> ShowS
[ArgsCheckState a] -> ShowS
ArgsCheckState a -> String
(Int -> ArgsCheckState a -> ShowS)
-> (ArgsCheckState a -> String)
-> ([ArgsCheckState a] -> ShowS)
-> Show (ArgsCheckState a)
forall a. Show a => Int -> ArgsCheckState a -> ShowS
forall a. Show a => [ArgsCheckState a] -> ShowS
forall a. Show a => ArgsCheckState a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall a. Show a => Int -> ArgsCheckState a -> ShowS
showsPrec :: Int -> ArgsCheckState a -> ShowS
$cshow :: forall a. Show a => ArgsCheckState a -> String
show :: ArgsCheckState a -> String
$cshowList :: forall a. Show a => [ArgsCheckState a] -> ShowS
showList :: [ArgsCheckState a] -> ShowS
Show

----------------------------------------------------------------------------------------------------
-- * Type checking warnings (aka non-fatal errors)
----------------------------------------------------------------------------------------------------

data UnsolvedWarning
  = UnsolvedMetaVariables    (Set1 Range)  -- ^ Do not use directly with 'warning'
  | UnsolvedInteractionMetas (Set1 Range)  -- ^ Do not use directly with 'warning'
  | UnsolvedConstraints      (List1 ProblemConstraint)  -- no instance Ord ProblemConstraint
    -- ^ Do not use directly with 'warning'
  | InteractionMetaBoundaries (Set1 Range)
    -- ^ Do not use directly with 'warning'
  deriving (Int -> UnsolvedWarning -> ShowS
[UnsolvedWarning] -> ShowS
UnsolvedWarning -> String
(Int -> UnsolvedWarning -> ShowS)
-> (UnsolvedWarning -> String)
-> ([UnsolvedWarning] -> ShowS)
-> Show UnsolvedWarning
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> UnsolvedWarning -> ShowS
showsPrec :: Int -> UnsolvedWarning -> ShowS
$cshow :: UnsolvedWarning -> String
show :: UnsolvedWarning -> String
$cshowList :: [UnsolvedWarning] -> ShowS
showList :: [UnsolvedWarning] -> ShowS
Show, (forall x. UnsolvedWarning -> Rep UnsolvedWarning x)
-> (forall x. Rep UnsolvedWarning x -> UnsolvedWarning)
-> Generic UnsolvedWarning
forall x. Rep UnsolvedWarning x -> UnsolvedWarning
forall x. UnsolvedWarning -> Rep UnsolvedWarning x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. UnsolvedWarning -> Rep UnsolvedWarning x
from :: forall x. UnsolvedWarning -> Rep UnsolvedWarning x
$cto :: forall x. Rep UnsolvedWarning x -> UnsolvedWarning
to :: forall x. Rep UnsolvedWarning x -> UnsolvedWarning
Generic)

instance HasRange UnsolvedWarning where
  getRange :: UnsolvedWarning -> Range
getRange = \case
    UnsolvedMetaVariables     Set1 Range
ms -> Set1 Range -> Range
forall a. HasRange a => a -> Range
getRange Set1 Range
ms
    UnsolvedInteractionMetas  Set1 Range
ms -> Set1 Range -> Range
forall a. HasRange a => a -> Range
getRange Set1 Range
ms
    UnsolvedConstraints       List1 ProblemConstraint
ms -> List1 ProblemConstraint -> Range
forall a. HasRange a => a -> Range
getRange List1 ProblemConstraint
ms
    InteractionMetaBoundaries Set1 Range
ms -> Set1 Range -> Range
forall a. HasRange a => a -> Range
getRange Set1 Range
ms

-- | A non-fatal error is an error which does not prevent us from
-- checking the document further and interacting with the user.

data Warning
  = TerminationIssue         (List1 TerminationError)
  | UnreachableClauses       QName (List1 Range)
  -- ^ @UnreachableClauses f rs@ means that the clauses in @f@ whose ranges are @rs@
  --   are unreachable.
  | CoverageIssue            QName (List1 (Telescope, [NamedArg DeBruijnPattern]))
  -- ^ `CoverageIssue f pss` means that `pss` are not covered in `f`
  | CoverageNoExactSplit     QName (List1 Clause)
  | InlineNoExactSplit       QName Clause
    -- ^ 'Clause' was turned into copattern matching clause(s) by an @{-# INLINE constructor #-}@
    --   and thus is not a definitional equality any more.
  | NotStrictlyPositive      QName (Seq W.OccursWhere)
  | ConstructorDoesNotFitInData DataOrRecord_ QName Sort Sort TCErr
      -- ^ Checking whether constructor 'QName' 'Sort' fits into @data@ 'Sort'
      --   produced 'TCErr'.
  | CoinductiveEtaRecord QName
      -- ^ A record type declared as both @coinductive@ and having @eta-equality@.

  | CantGeneralizeOverSorts (Set1 MetaId)
  | AbsurdPatternRequiresAbsentRHS
  | OldBuiltin               BuiltinId BuiltinId
    -- ^ In `OldBuiltin old new`, the BUILTIN old has been replaced by new.
  | BuiltinDeclaresIdentifier BuiltinId
    -- ^ The builtin declares a new identifier, so it should not be in scope.
  | DuplicateRecordDirective C.RecordDirective
    -- ^ The given record directive is conflicting with a prior one in the same record declaration.
  | EmptyWhere
    -- ^ An empty @where@ block is dead code.
  | IllformedAsClause String
    -- ^ If the user wrote something other than an unqualified name
    --   in the @as@ clause of an @import@ statement.
    --   The 'String' gives optionally extra explanation.
  | InvalidCharacterLiteral Char
    -- ^ A character literal Agda does not support, e.g. surrogate code points.
  | ClashesViaRenaming NameOrModule (Set1 C.Name)
    -- ^ If a `renaming' import directive introduces a name or module name clash
    --   in the exported names of a module.
    --   (See issue #4154.)
  | UnusedImports A.ModuleName (Maybe (List1 AbstractName))
    -- ^ The given module was opened but the names in the list were not used.
    --   If 'Nothing', then none of the imported name was used.
  | UselessPatternDeclarationForRecord String
    -- ^ The 'pattern' declaration is useless in the presence
    --   of either @coinductive@ or @eta-equality@.
    --   Content of 'String' is "coinductive" or "eta", resp.
  | UselessPragma Range Doc
    -- ^ Warning when pragma is useless and thus ignored.
    --   'Range' is for dead code highlighting.
  | UselessPublic UselessPublicReason
    -- ^ If the user opens a module public before the module header.
    --   (See issue #2377.)
  | UselessHiding (List1 C.ImportedName)
    -- ^ Names in `hiding` directive that don't hide anything
    --   imported by a `using` directive.
  | UselessInline            QName
  | UselessTactic
    -- ^ A tactic attribute applied to a non-hidden (visible or instance) argument.
  | WrongInstanceDeclaration KwRange
    -- ^ The 'KwRange' is the range of the @instance@ keyword.
  | InstanceWithExplicitArg  KwRange QName
    -- ^ An instance was declared with an implicit argument, which means it
    --   will never actually be considered by instance search.
    --   The 'KwRange' is the range of the @instance@ keyword.
  | InstanceNoOutputTypeName Doc
  -- ^ The type of an instance argument doesn't end in a named or
  -- variable type, so it will never be considered by instance search.
  | InstanceArgWithExplicitArg Doc
  -- ^ As InstanceWithExplicitArg, but for local bindings rather than
  --   top-level instances.
  | InversionDepthReached    QName
  -- ^ The --inversion-max-depth was reached.

  -- Safe flag errors
  | SafeFlagPostulate QName
  | SafeFlagPragma (Set String)
      -- ^ Unsafe OPTIONS.
  | ConflictingPragmaOptions String String
    -- ^ `ConflictingPragmaOptions a b`:
    --   Inconsistent options `--a` and `--no-b`, since `--a` implies `--b`. Ignoring `--no-b`.
  | OptionWarning            OptionWarning
  | ParseWarning             ParseWarning
  | LibraryWarning           LibWarning
  | DeprecationWarning String (Maybe String) String
    -- ^ @DeprecationWarning old new version@:
    --   @old@ is deprecated, use @new@ instead (if given).
    --   This will be an error in @version@.
  | UserWarning ShortText
    -- ^ User-defined warning (e.g. to mention that a name is deprecated)
  | DuplicateUsing (List1 C.ImportedName)
    -- ^ Duplicate mentions of the same name in @using@ directive(s).
  | FixityInRenamingModule (List1 Range)
    -- ^ Fixity of modules cannot be changed via renaming (since modules have no fixity).
  | ModuleDoesntExport C.QName [C.Name] [C.Name] (List1 C.ImportedName)
    -- ^ Some imported names are not actually exported by the source module.
    --   The second argument is the names that could be exported.
    --   The third  argument is the module names that could be exported.
  | InfectiveImport Doc
    -- ^ Importing a file using an infective option into one which doesn't
  | CoInfectiveImport Doc
    -- ^ Importing a file not using a coinfective option from one which does
  | PragmaCompileWrongName C.QName IsAmbiguous
    -- ^ @COMPILE@ pragma with name 'C.QName' that is not an unambiguous constructor or definition.
  | PragmaExpectsDefinedSymbol String C.QName
    -- ^ Pragma 'String' with name 'C.QName' that is not an 'A.Def'.
  | PragmaExpectsUnambiguousConstructorOrFunction String C.QName IsAmbiguous
    -- ^ Pragma 'String' with name 'C.QName' that is not an unambiguous constructor or definition.
    --   General form of 'PragmaCompileWrongName'.
  | PragmaExpectsUnambiguousProjectionOrFunction String C.QName IsAmbiguous
    -- ^ Pragma 'String' with name 'C.QName' that is not an unambiguous projection or function.
  | NoMain TopLevelModuleName
    -- ^ Compiler run on module that does not have a @main@ function.
  | NotInScopeW C.QName
    -- ^ Out of scope error we can recover from.
  | UnsupportedIndexedMatch Doc
    -- ^ Was not able to compute a full equivalence when splitting.
  | AsPatternShadowsConstructorOrPatternSynonym ConstructorOrPatternSynonym
    -- ^ The as-name in an as-pattern may not shadow a constructor
    --   or pattern synonym name,
    --   because this can be confusing to read.
  | PatternShadowsConstructor C.Name A.QName
    -- ^ A pattern variable has the name of a constructor
    --   (data constructor or matchable record constructor).
  | RecordFieldWarning RecordFieldWarning

  -- Opaque
  | MissingTypeSignatureForOpaque QName IsOpaque
    -- ^ An @abstract@ or @opaque@ definition lacks a type signature.
  | NotAffectedByOpaque
  | UnfoldingWrongName C.QName
      -- ^ Name in @unfolding@ clause does not resolve to unambiguous defined name.
  | UnfoldTransparentName QName
  | UselessOpaque

  -- Recoverable scope-checking errors
  | HiddenNotInArgumentPosition C.Expr
  | InstanceNotInArgumentPosition C.Expr
  | MacroInLetBindings
  | AbstractInLetBindings
  | IllegalDeclarationInDataDefinition (List1 C.Declaration)
      -- ^ The declaration list comes from a single 'C.NiceDeclaration'.

  -- Display form warnings
  | InvalidDisplayForm QName String
      -- ^ DISPLAY form for 'QName' is invalid because 'String'.
  -- Type checker warnings
  | ShouldBeEtaRecordPattern
      -- ^ Irrefutable match (match in binder) on a non-eta record pattern.
      --   Some expected definitional equalities will not hold.
  | TooManyArgumentsToSort QName (List1 (NamedArg A.Expr))
      -- ^ Extra arguments to sort (will be ignored).
  | DefinitionBeforeDeclaration A.AbstractName
      -- ^ A definition appears before its declaration in a @mutual@ block.
  | RewritesNothing
      -- ^ A @rewrite@ expression that does not fire.
  | WithClauseProjectionFixityMismatch
    { Warning -> NamedArg Pattern
withClausePattern          :: NamedArg A.Pattern
    , Warning -> ProjOrigin
withClauseProjectionOrigin :: ProjOrigin
    , Warning -> NamedArg DeBruijnPattern
parentPattern              :: NamedArg DeBruijnPattern
    , Warning -> ProjOrigin
parentProjectionOrigin     :: ProjOrigin
    }
    -- ^ The with-clause uses projection in a different fixity style
    --   than the parent clause.
  | RecursiveRecordNeedsInductivity QName
      -- ^ A record type inferred as recursive needs a manual declaration
      --   whether it should be inductively or coinductively.

  -- Polarity warnings
  | TooManyPolarities QName PragmaPolarities
    -- ^ Too many polarities given in POLARITY pragma for 'QName'.
    --   'PragmaPolarities' contains the (likely) excessive polarities.

  -- Cubical
  | FaceConstraintCannotBeHidden ArgInfo
    -- ^ Face constraint patterns @(i = 0)@ must be visible arguments.
  | FaceConstraintCannotBeNamed NamedName
    -- ^ Face constraint patterns @(i = 0)@ must be unnamed arguments.

  -- Not source code related
  | CustomBackendWarning String Doc
    -- ^ Used for backend-specific warnings. The string is the backend name.
  deriving (Int -> Warning -> ShowS
[Warning] -> ShowS
Warning -> String
(Int -> Warning -> ShowS)
-> (Warning -> String) -> ([Warning] -> ShowS) -> Show Warning
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Warning -> ShowS
showsPrec :: Int -> Warning -> ShowS
$cshow :: Warning -> String
show :: Warning -> String
$cshowList :: [Warning] -> ShowS
showList :: [Warning] -> ShowS
Show, (forall x. Warning -> Rep Warning x)
-> (forall x. Rep Warning x -> Warning) -> Generic Warning
forall x. Rep Warning x -> Warning
forall x. Warning -> Rep Warning x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Warning -> Rep Warning x
from :: forall x. Warning -> Rep Warning x
$cto :: forall x. Rep Warning x -> Warning
to :: forall x. Rep Warning x -> Warning
Generic)

recordFieldWarningToError :: RecordFieldWarning -> TypeError
recordFieldWarningToError :: RecordFieldWarning -> TypeError
recordFieldWarningToError = \case
  W.DuplicateFields    List1 (Name, List1 Range)
xrs -> List1 Name -> TypeError
DuplicateFields    (List1 Name -> TypeError) -> List1 Name -> TypeError
forall a b. (a -> b) -> a -> b
$ ((Name, List1 Range) -> Name)
-> List1 (Name, List1 Range) -> List1 Name
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Name, List1 Range) -> Name
forall a b. (a, b) -> a
fst List1 (Name, List1 Range)
xrs
  W.TooManyFields QName
q [Name]
ys List1 (Name, Range)
xrs -> QName -> [Name] -> List1 Name -> TypeError
TooManyFields QName
q [Name]
ys (List1 Name -> TypeError) -> List1 Name -> TypeError
forall a b. (a -> b) -> a -> b
$ ((Name, Range) -> Name) -> List1 (Name, Range) -> List1 Name
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Name, Range) -> Name
forall a b. (a, b) -> a
fst List1 (Name, Range)
xrs

warningName :: Warning -> WarningName
warningName :: Warning -> WarningName
warningName = \case
  -- special cases
  OptionWarning OptionWarning
ow             -> OptionWarning -> WarningName
optionWarningName OptionWarning
ow
  ParseWarning ParseWarning
pw              -> ParseWarning -> WarningName
parseWarningName ParseWarning
pw
  LibraryWarning LibWarning
lw            -> LibWarning -> WarningName
libraryWarningName LibWarning
lw
  -- scope- and type-checking errors
  AsPatternShadowsConstructorOrPatternSynonym{} -> WarningName
AsPatternShadowsConstructorOrPatternSynonym_
  PatternShadowsConstructor{}  -> WarningName
PatternShadowsConstructor_
  AbsurdPatternRequiresAbsentRHS{} -> WarningName
AbsurdPatternRequiresAbsentRHS_
  CantGeneralizeOverSorts{}    -> WarningName
CantGeneralizeOverSorts_
  CoverageIssue{}              -> WarningName
CoverageIssue_
  CoverageNoExactSplit{}       -> WarningName
CoverageNoExactSplit_
  InlineNoExactSplit{}         -> WarningName
InlineNoExactSplit_
  DeprecationWarning{}         -> WarningName
DeprecationWarning_
  DuplicateRecordDirective{}   -> WarningName
DuplicateRecordDirective_
  Warning
EmptyWhere                   -> WarningName
EmptyWhere_
  IllformedAsClause{}          -> WarningName
IllformedAsClause_
  WrongInstanceDeclaration{}   -> WarningName
WrongInstanceDeclaration_
  InstanceWithExplicitArg{}    -> WarningName
InstanceWithExplicitArg_
  InstanceNoOutputTypeName{}   -> WarningName
InstanceNoOutputTypeName_
  InstanceArgWithExplicitArg{} -> WarningName
InstanceArgWithExplicitArg_
  DuplicateUsing{}             -> WarningName
DuplicateUsing_
  FixityInRenamingModule{}     -> WarningName
FixityInRenamingModule_
  InvalidCharacterLiteral{}    -> WarningName
InvalidCharacterLiteral_
  UnusedImports{}              -> WarningName
UnusedImports_
  UselessPragma{}              -> WarningName
UselessPragma_
  InversionDepthReached{}      -> WarningName
InversionDepthReached_
  ModuleDoesntExport{}         -> WarningName
ModuleDoesntExport_
  NotInScopeW{}                -> WarningName
NotInScope_
  NotStrictlyPositive{}        -> WarningName
NotStrictlyPositive_
  ConstructorDoesNotFitInData{}-> WarningName
ConstructorDoesNotFitInData_
  CoinductiveEtaRecord{}       -> WarningName
CoinductiveEtaRecord_
  UnsupportedIndexedMatch{}    -> WarningName
UnsupportedIndexedMatch_
  OldBuiltin{}                 -> WarningName
OldBuiltin_
  BuiltinDeclaresIdentifier{}  -> WarningName
BuiltinDeclaresIdentifier_
  SafeFlagPostulate{}          -> WarningName
SafeFlagPostulate_
  SafeFlagPragma{}             -> WarningName
SafeFlagPragma_
  ConflictingPragmaOptions{}   -> WarningName
ConflictingPragmaOptions_
  TerminationIssue{}           -> WarningName
TerminationIssue_
  UnreachableClauses{}         -> WarningName
UnreachableClauses_
  UselessHiding{}              -> WarningName
UselessHiding_
  UselessInline{}              -> WarningName
UselessInline_
  UselessPublic{}              -> WarningName
UselessPublic_
  UselessPatternDeclarationForRecord{} -> WarningName
UselessPatternDeclarationForRecord_
  UselessTactic{}              -> WarningName
UselessTactic_
  ClashesViaRenaming{}         -> WarningName
ClashesViaRenaming_
  UserWarning{}                -> WarningName
UserWarning_
  InfectiveImport{}            -> WarningName
InfectiveImport_
  CoInfectiveImport{}          -> WarningName
CoInfectiveImport_
  PragmaCompileWrongName{}     -> WarningName
PragmaCompileWrongName_
  PragmaExpectsDefinedSymbol{} -> WarningName
PragmaExpectsDefinedSymbol_
  PragmaExpectsUnambiguousConstructorOrFunction{} ->
    WarningName
PragmaExpectsUnambiguousConstructorOrFunction_
  PragmaExpectsUnambiguousProjectionOrFunction{} ->
    WarningName
PragmaExpectsUnambiguousProjectionOrFunction_
  NoMain{}                     -> WarningName
NoMain_
  -- record field warnings
  RecordFieldWarning RecordFieldWarning
w -> case RecordFieldWarning
w of
    W.DuplicateFields{}   -> WarningName
DuplicateFields_
    W.TooManyFields{}     -> WarningName
TooManyFields_

  -- opaque warnings
  MissingTypeSignatureForOpaque{} -> WarningName
MissingTypeSignatureForOpaque_
  NotAffectedByOpaque{}   -> WarningName
NotAffectedByOpaque_
  UselessOpaque{}         -> WarningName
UselessOpaque_
  UnfoldingWrongName{}    -> WarningName
UnfoldingWrongName_
  UnfoldTransparentName{} -> WarningName
UnfoldTransparentName_

  -- Recoverable scope-checking errors
  HiddenNotInArgumentPosition{}   -> WarningName
HiddenNotInArgumentPosition_
  InstanceNotInArgumentPosition{} -> WarningName
InstanceNotInArgumentPosition_
  MacroInLetBindings{}            -> WarningName
MacroInLetBindings_
  AbstractInLetBindings{}         -> WarningName
AbstractInLetBindings_
  IllegalDeclarationInDataDefinition{} -> WarningName
IllegalDeclarationInDataDefinition_

  -- Display forms
  InvalidDisplayForm{}            -> WarningName
InvalidDisplayForm_

  -- Type checking
  ShouldBeEtaRecordPattern{}           -> WarningName
ShouldBeEtaRecordPattern_
  TooManyArgumentsToSort{}             -> WarningName
TooManyArgumentsToSort_
  DefinitionBeforeDeclaration{}        -> WarningName
DefinitionBeforeDeclaration_
  RecursiveRecordNeedsInductivity{}    -> WarningName
RecursiveRecordNeedsInductivity_
  RewritesNothing{}                    -> WarningName
RewritesNothing_
  WithClauseProjectionFixityMismatch{} -> WarningName
WithClauseProjectionFixityMismatch_

  -- Polarities
  TooManyPolarities{}                  -> WarningName
TooManyPolarities_

  -- Cubical
  FaceConstraintCannotBeHidden{} -> WarningName
FaceConstraintCannotBeHidden_
  FaceConstraintCannotBeNamed{}  -> WarningName
FaceConstraintCannotBeNamed_

  -- Backend warnings
  CustomBackendWarning{} -> WarningName
CustomBackendWarning_

-- | A 'TCWarning'' is a boxed 'Diagnostic' which can be stored in the
-- TC state.
--
-- Note: only 'TCWarning's in the "live" TC state can have the
-- 'tcWarning' diagnostic downcast back to its original 'Diagnostic'
-- value. Warnings in interface files are stored as
-- 'EncodedDiagnostic's.
data TCWarning' diag
  = TCWarning
    { forall diag. TCWarning' diag -> CallStack
tcWarningLocation :: CallStack
        -- ^ Location in the internal Agda source code location where the error raised
    , forall diag. TCWarning' diag -> Range
tcWarningRange    :: Range
        -- ^ Range where the warning was raised
    , forall diag. TCWarning' diag -> diag
tcWarning         :: diag
        -- ^ The warning itself
    , forall diag. TCWarning' diag -> Doc
tcWarningDoc      :: Doc -- DocTree
        -- ^ The warning printed in the state and environment where it was raised
    , forall diag. TCWarning' diag -> String
tcWarningString   :: String
        -- ^ Caches @render tcWarningDoc@ for the sake of an 'Ord' instance.
    , forall diag. TCWarning' diag -> Bool
tcWarningCached :: Bool
        -- ^ Should the warning be affected by caching.
    }
  deriving (Int -> TCWarning' diag -> ShowS
[TCWarning' diag] -> ShowS
TCWarning' diag -> String
(Int -> TCWarning' diag -> ShowS)
-> (TCWarning' diag -> String)
-> ([TCWarning' diag] -> ShowS)
-> Show (TCWarning' diag)
forall diag. Show diag => Int -> TCWarning' diag -> ShowS
forall diag. Show diag => [TCWarning' diag] -> ShowS
forall diag. Show diag => TCWarning' diag -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall diag. Show diag => Int -> TCWarning' diag -> ShowS
showsPrec :: Int -> TCWarning' diag -> ShowS
$cshow :: forall diag. Show diag => TCWarning' diag -> String
show :: TCWarning' diag -> String
$cshowList :: forall diag. Show diag => [TCWarning' diag] -> ShowS
showList :: [TCWarning' diag] -> ShowS
Show, (forall x. TCWarning' diag -> Rep (TCWarning' diag) x)
-> (forall x. Rep (TCWarning' diag) x -> TCWarning' diag)
-> Generic (TCWarning' diag)
forall x. Rep (TCWarning' diag) x -> TCWarning' diag
forall x. TCWarning' diag -> Rep (TCWarning' diag) x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
forall diag x. Rep (TCWarning' diag) x -> TCWarning' diag
forall diag x. TCWarning' diag -> Rep (TCWarning' diag) x
$cfrom :: forall diag x. TCWarning' diag -> Rep (TCWarning' diag) x
from :: forall x. TCWarning' diag -> Rep (TCWarning' diag) x
$cto :: forall diag x. Rep (TCWarning' diag) x -> TCWarning' diag
to :: forall x. Rep (TCWarning' diag) x -> TCWarning' diag
Generic, (forall a b. (a -> b) -> TCWarning' a -> TCWarning' b)
-> (forall a b. a -> TCWarning' b -> TCWarning' a)
-> Functor TCWarning'
forall a b. a -> TCWarning' b -> TCWarning' a
forall a b. (a -> b) -> TCWarning' a -> TCWarning' b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall a b. (a -> b) -> TCWarning' a -> TCWarning' b
fmap :: forall a b. (a -> b) -> TCWarning' a -> TCWarning' b
$c<$ :: forall a b. a -> TCWarning' b -> TCWarning' a
<$ :: forall a b. a -> TCWarning' b -> TCWarning' a
Functor)

type TCWarning = TCWarning' SomeDiagnostic

tcWarningOrigin :: TCWarning' a -> SrcFile
tcWarningOrigin :: forall a. TCWarning' a -> Maybe RangeFile
tcWarningOrigin = Range -> Maybe RangeFile
rangeFile (Range -> Maybe RangeFile)
-> (TCWarning' a -> Range) -> TCWarning' a -> Maybe RangeFile
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TCWarning' a -> Range
forall diag. TCWarning' diag -> Range
tcWarningRange

instance HasRange (TCWarning' a) where
  getRange :: TCWarning' a -> Range
getRange = TCWarning' a -> Range
forall diag. TCWarning' diag -> Range
tcWarningRange

instance Eq (TCWarning' a) where
  == :: TCWarning' a -> TCWarning' a -> Bool
(==) = (Range, String) -> (Range, String) -> Bool
forall a. Eq a => a -> a -> Bool
(==) ((Range, String) -> (Range, String) -> Bool)
-> (TCWarning' a -> (Range, String))
-> TCWarning' a
-> TCWarning' a
-> Bool
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` TCWarning' a -> Range
forall diag. TCWarning' diag -> Range
tcWarningRange (TCWarning' a -> Range)
-> (TCWarning' a -> String) -> TCWarning' a -> (Range, String)
forall b c c'. (b -> c) -> (b -> c') -> b -> (c, c')
forall (a :: * -> * -> *) b c c'.
Arrow a =>
a b c -> a b c' -> a b (c, c')
&&& TCWarning' a -> String
forall diag. TCWarning' diag -> String
tcWarningString

instance Ord (TCWarning' a) where
  compare :: TCWarning' a -> TCWarning' a -> Ordering
compare = (Range, String) -> (Range, String) -> Ordering
forall a. Ord a => a -> a -> Ordering
compare ((Range, String) -> (Range, String) -> Ordering)
-> (TCWarning' a -> (Range, String))
-> TCWarning' a
-> TCWarning' a
-> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` TCWarning' a -> Range
forall diag. TCWarning' diag -> Range
tcWarningRange (TCWarning' a -> Range)
-> (TCWarning' a -> String) -> TCWarning' a -> (Range, String)
forall b c c'. (b -> c) -> (b -> c') -> b -> (c, c')
forall (a :: * -> * -> *) b c c'.
Arrow a =>
a b c -> a b c' -> a b (c, c')
&&& TCWarning' a -> String
forall diag. TCWarning' diag -> String
tcWarningString

----------------------------------------------------------------------------------------------------
-- * Type checking errors
----------------------------------------------------------------------------------------------------

-- | Information about a call.

data CallInfo = CallInfo
  { CallInfo -> QName
callInfoTarget    :: !QName
    -- ^ Target function name.  (Contains its range.)
  , CallInfo -> Bool
callInfoHighlight :: !Bool
    -- ^ Should this call be highlighted?
    -- (True for RHS occurrences, false for linking LHS nodes.)
  , CallInfo -> Closure Term
callInfoCall :: Closure Term
    -- ^ To-be-formatted representation of the call.
  } deriving (Int -> CallInfo -> ShowS
[CallInfo] -> ShowS
CallInfo -> String
(Int -> CallInfo -> ShowS)
-> (CallInfo -> String) -> ([CallInfo] -> ShowS) -> Show CallInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CallInfo -> ShowS
showsPrec :: Int -> CallInfo -> ShowS
$cshow :: CallInfo -> String
show :: CallInfo -> String
$cshowList :: [CallInfo] -> ShowS
showList :: [CallInfo] -> ShowS
Show, (forall x. CallInfo -> Rep CallInfo x)
-> (forall x. Rep CallInfo x -> CallInfo) -> Generic CallInfo
forall x. Rep CallInfo x -> CallInfo
forall x. CallInfo -> Rep CallInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. CallInfo -> Rep CallInfo x
from :: forall x. CallInfo -> Rep CallInfo x
$cto :: forall x. Rep CallInfo x -> CallInfo
to :: forall x. Rep CallInfo x -> CallInfo
Generic)
    -- no Eq, Ord instances: too expensive! (see issues 851, 852)

instance HasRange CallInfo where
  getRange :: CallInfo -> Range
getRange = QName -> Range
forall a. HasRange a => a -> Range
getRange (QName -> Range) -> (CallInfo -> QName) -> CallInfo -> Range
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CallInfo -> QName
callInfoTarget

-- | We only 'show' the name of the callee.
instance Pretty CallInfo where pretty :: CallInfo -> Doc
pretty = QName -> Doc
forall a. Pretty a => a -> Doc
pretty (QName -> Doc) -> (CallInfo -> QName) -> CallInfo -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CallInfo -> QName
callInfoTarget

-- | Information about a mutual block which did not pass the
-- termination checker.

data TerminationError = TerminationError
  { TerminationError -> Set QName
termErrFunctions :: Set QName
    -- ^ The functions which failed to check. (May not include
    -- automatically generated functions.)
  , TerminationError -> List1 CallInfo
termErrCalls :: List1 CallInfo
    -- ^ The problematic call sites.
  } deriving (Int -> TerminationError -> ShowS
[TerminationError] -> ShowS
TerminationError -> String
(Int -> TerminationError -> ShowS)
-> (TerminationError -> String)
-> ([TerminationError] -> ShowS)
-> Show TerminationError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TerminationError -> ShowS
showsPrec :: Int -> TerminationError -> ShowS
$cshow :: TerminationError -> String
show :: TerminationError -> String
$cshowList :: [TerminationError] -> ShowS
showList :: [TerminationError] -> ShowS
Show, (forall x. TerminationError -> Rep TerminationError x)
-> (forall x. Rep TerminationError x -> TerminationError)
-> Generic TerminationError
forall x. Rep TerminationError x -> TerminationError
forall x. TerminationError -> Rep TerminationError x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TerminationError -> Rep TerminationError x
from :: forall x. TerminationError -> Rep TerminationError x
$cto :: forall x. Rep TerminationError x -> TerminationError
to :: forall x. Rep TerminationError x -> TerminationError
Generic)

data NegativeUnification
  = UnifyConflict Telescope Term Term
  | UnifyCycle Telescope Int Term
  deriving (Int -> NegativeUnification -> ShowS
[NegativeUnification] -> ShowS
NegativeUnification -> String
(Int -> NegativeUnification -> ShowS)
-> (NegativeUnification -> String)
-> ([NegativeUnification] -> ShowS)
-> Show NegativeUnification
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> NegativeUnification -> ShowS
showsPrec :: Int -> NegativeUnification -> ShowS
$cshow :: NegativeUnification -> String
show :: NegativeUnification -> String
$cshowList :: [NegativeUnification] -> ShowS
showList :: [NegativeUnification] -> ShowS
Show, (forall x. NegativeUnification -> Rep NegativeUnification x)
-> (forall x. Rep NegativeUnification x -> NegativeUnification)
-> Generic NegativeUnification
forall x. Rep NegativeUnification x -> NegativeUnification
forall x. NegativeUnification -> Rep NegativeUnification x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. NegativeUnification -> Rep NegativeUnification x
from :: forall x. NegativeUnification -> Rep NegativeUnification x
$cto :: forall x. Rep NegativeUnification x -> NegativeUnification
to :: forall x. Rep NegativeUnification x -> NegativeUnification
Generic)

-- | Errors thrown during elaboration.
--
-- __NOTE__: New errors should not be added to this data-type! They
-- should be placed next to the code that raises them and made into
-- instances of 'Mikan.TypeChecking.Monad.Diagnostic.Diagnostic'.
data TypeError
        = InternalError String
        | CompilationError String
        | SyntaxError String
             -- ^ Essential syntax error thrown after successful parsing.
             --   Description in 'String'.
        | OptionError OptionError
             -- ^ Error thrown by the option parser.
        | DoNotationError String
             -- ^ Error during unsugaring some @do@ notation.
             --   Error message in 'String'.
        | IdiomBracketError String
             -- ^ Error during (operator) parsing and interpreting the contents of idiom brackets.
             --   Error message in 'String'.
        | NoKnownRecordWithSuchFields [C.Name]
            -- ^ The user has given a record expression with the given fields,
            --   but no record type known to type inference has all these fields.
            --   The list can be empty.
        | ShouldEndInApplicationOfTheDatatype Type
            -- ^ The target of a constructor isn't an application of its
            -- datatype. The 'Type' records what it does target.
        | ConstructorPatternInWrongDatatype QName QName -- ^ constructor, datatype
        | CantResolveOverloadedConstructorsTargetingSameDatatype
            Type
            -- ^ Expected type at position
            (List1 (QName, Type, Maybe TCState))
            -- ^ Resolved constructor name, its return type, and possibly the
            -- new TC state.
        | ConstructorDoesNotTargetGivenType QName Type -- ^ constructor, type
        | InvalidDottedExpression
            -- ^ @.e@ in non-argument position.
        | LiteralTooBig
            -- ^ An integer literal that would be too costly to expand to unary.
        | NegativeLiteralInPattern
            -- ^ Negative literals are not supported in patterns.
        | WrongHidingInLHS Hiding
            -- ^ The left hand side of a function definition has a hidden argument
            --   where a non-hidden was expected.
        | WrongHidingInLambda Hiding Type
            -- ^ Expected a non-hidden function and found a hidden lambda.
        | WrongHidingInApplication Hiding Type
            -- ^ A function is applied to a hidden argument where a non-hidden was expected.
        | WrongHidingInProjection Hiding Hiding QName
        | IllegalHidingInPostfixProjection (NamedArg C.Expr)
        | WrongNamedArgument (NamedArg A.Expr) (List1 NamedName)
            -- ^ A function is applied to a hidden named argument it does not have.
            -- The list contains names of possible hidden arguments at this point.
        | HidingMismatch Hiding Hiding
            -- ^ The given hiding does not correspond to the expected hiding.
        | ForcedConstructorNotInstantiated A.Pattern
        | IllformedProjectionPatternAbstract A.Pattern
        | IllformedProjectionPatternConcrete C.Pattern
        | WrongNumberOfConstructorArguments QName Nat Nat
        | ShouldBeEmpty Type [DeBruijnPattern]
            -- ^ Type should be empty. The list gives possible patterns that match, but can be empty.
        | ShouldBeASort Type
            -- ^ The given type should have been a sort.
        | ShouldBePi Type
            -- ^ The given type should have been a pi.
        | ShouldBePath Type
        | ShouldBeRecordType Type
        | ShouldBeRecordPattern
        | CannotApply A.Expr Type
            -- ^ The given expression is used as a function
            --   but its type is not a function type.
        | InvalidTypeSort Sort
            -- ^ This sort is not a type expression.
        | NotLeqSort Sort Sort
        | MetaCannotDependOn MetaId Term Nat
            -- ^ The arguments are the meta variable, the proposed solution,
            --   and the parameter that it wants to depend on.
        | UserError Doc
            -- ^ Error message produced by a meta program.
        | BuiltinMustBeConstructor BuiltinId A.Expr
        | BuiltinMustBeData BuiltinId Int
        | BuiltinMustBeDef BuiltinId
        | BuiltinMustBeFunction BuiltinId
        | BuiltinMustBePostulate BuiltinId
        | NoSuchBuiltinName ShortText
        | InvalidBuiltin String
        | DuplicateBuiltinBinding BuiltinId Term Term
        | NoBindingForBuiltin BuiltinId
        | NoBindingForPrimitive PrimitiveId
        | NoSuchPrimitiveFunction ShortText
        | DuplicatePrimitiveBinding PrimitiveId QName QName
        | ShadowedModule C.Name (List1 A.ModuleName)
        | BuiltinInParameterisedModule BuiltinId
        | IllegalLetInTelescope C.TypedBinding
        | IllegalPatternInTelescope C.Binder
        | AbsentRHSRequiresAbsurdPattern
        | TooManyFields QName [C.Name] (List1 C.Name)
          -- ^ Record type, fields not supplied by user, possibly non-fields but supplied.
        | DuplicateFields (List1 C.Name)
        | DuplicateConstructors (List1 C.Name)
        | DuplicateOverlapPragma QName OverlapMode OverlapMode
        | WithOnFreeVariable A.Expr Term
        | UnexpectedWithPatterns (List1 A.Pattern)
        | WithClausePatternMismatch A.Pattern (NamedArg DeBruijnPattern)
        | IllTypedPatternAfterWithAbstraction A.Pattern
        | TooFewPatternsInWithClause
        | TooManyPatternsInWithClause
        | PathAbstractionFailed (Abs Type)
        | ModuleArityMismatch A.ModuleName Telescope (Either (List1 (NamedArg A.Expr)) Args)
        | GeneralizeCyclicDependency
        | MismatchedProjectionsError QName QName
        | InvalidProjectionParameter (NamedArg A.Expr)
        | TacticAttributeNotAllowed
        | CannotRewriteByNonEquation Type
        | MacroResultTypeMismatch Type
        | NonLocalWhereModuleInRefinedContext [Term] [ShortText]
            -- ^ The lists should have the same length.
            --   TODO: enforce this by construction.
        | ComatchingDisabledForRecord QName
    -- Cubical errors
        | CannotGenerateTransportClause QName (Closure (Abs Type))
            -- ^ Cannot generate transport clause because type is not fibrant.
        | CubicalPrimitiveNotFullyApplied QName
        | ExpectedIntervalLiteral A.Expr
            -- ^ Expected an interval literal (0 or 1) but found 'A.Expr'.
        | FaceConstraintDisjunction
        | FaceConstraintUnsatisfiable
        | PatternInPathLambda
            -- ^ Attempt to pattern match in an abstraction of interval type.
        | PatternInSystem
        -- ^ Attempt to pattern or copattern match in a system.

    -- Data errors
        | UnexpectedParameter A.LamBinding
        | NoParameterOfName ArgName
        | UnexpectedTypeSignatureForParameter (List1 (NamedArg A.Binder))
        | SortDoesNotAdmitDataDefinitions QName Sort
        | SortCannotDependOnItsIndex QName Type
    -- Coverage errors
        | ImpossibleConstructor QName NegativeUnification

    -- Import errors
        | LibraryError LibErrors
            -- ^ Collected errors when processing the @.agda-lib@ file.
        | LibTooFarDown TopLevelModuleName AgdaLibFile
            -- ^ The @.agda-lib@ file for the given module is not on the right level.
        | SolvedButOpenHoles TopLevelModuleNameWithSourceFile
          -- ^ Some interaction points (holes) in the given module have not been filled by the user.
          --   These are not 'UnsolvedMetas' since unification solved them.
          --   This is an error, since interaction points are never filled
          --   without user interaction.
        | CyclicModuleDependency (List2 TopLevelModuleName)
            -- ^ The cycle starts and ends with the same module.
        | FileNotFound TopLevelModuleName (List1 AbsolutePath)
            -- ^ No file for the module was found when searching
            --   in the given list of include directories.
        | OverlappingProjects AbsolutePath TopLevelModuleName TopLevelModuleName
        | AmbiguousTopLevelModuleName TopLevelModuleName (List2 AbsolutePath)
            -- ^ The given module has at least 2 file locations.
        | ModuleNameUnexpected TopLevelModuleNameWithSourceFile TopLevelModuleName
          -- ^ Found module name, expected module name.
        | ModuleNameDoesntMatchFileName TopLevelModuleName (List1 AbsolutePath)
            -- ^ No matching file for the module was found when searching
            --   in the given list of include directories.
        | ModuleDefinedInOtherFile TopLevelModuleName AbsolutePath AbsolutePath
          -- ^ Module name, file from which it was loaded, file which
          -- the include path says contains the module.
        | InvalidFileName AbsolutePath InvalidFileNameReason
          -- ^ The file name does not correspond to a module name.
        | ModuleNameHashCollision RawTopLevelModuleName (Maybe RawTopLevelModuleName)
    -- Scope errors
        | BothWithAndRHS
        | AbstractConstructorNotInScope A.QName
        | CopatternHeadNotProjection C.QName
        | NotAllowedInDotPatterns NotAllowedInDotPatterns
        | NotInScope C.QName
        | NoSuchModule C.QName
        | AmbiguousName C.QName AmbiguousNameReason
        | AmbiguousModule C.QName (List1 A.ModuleName)
        | AmbiguousField C.Name (List2 A.ModuleName)
        | AmbiguousConstructor QName (List2 QName)
            -- ^ The list contains all interpretations of the name.
        | ClashingDefinition C.QName ClashingName (Maybe NiceDeclaration)
        | ClashingModule A.ModuleName A.ModuleName
        | DefinitionInDifferentModule A.QName
            -- ^ The given data/record definition rests in a different module than its signature.
        | DuplicateImports C.QName (List1 C.ImportedName)
        | InvalidPattern C.Pattern
        | InvalidPun ConstructorOrPatternSynonym C.QName
            -- ^ Expected the identifier to be a variable, not a constructor or pattern synonym.
        | RepeatedNamesInImportDirective (List1 (List2 C.ImportedName))
            -- ^ Some names are bound several times by an @import@/@open@ directive.
        | RepeatedVariablesInPattern (List1 C.Name)
        | CannotGeneralizeEtaExpandable A.QName Type
        | GeneralizationFailed Doc
        | GeneralizationPrepruneErrorRefinedContext (Closure MetaId)
        | GeneralizationPrepruneErrorCyclicDependencies (Closure MetaId)
        | GeneralizationPrepruneErrorFailedToInstantiate (Closure MetaId)
        | GeneralizeNotSupportedHere A.QName
        | GeneralizedVarInLetOpenedModule A.QName
        | MultipleFixityDecls (List1 (C.Name, Pair Fixity'))
        | MultiplePolarityPragmas (List1 C.Name)
        | ConstructorNameOfNonRecord ResolvedName
    -- Concrete to Abstract errors
        | CannotQuote CannotQuote
        | CannotQuoteTerm CannotQuoteTerm
        | DeclarationsAfterTopLevelModule
        | IllegalDeclarationBeforeTopLevelModule
        | MissingTypeSignature MissingTypeSignatureInfo
        | NotAnExpression C.Expr
        | NotAValidLetBinding (Maybe NotAValidLetBinding)
        | NotAValidLetExpression NotAValidLetExpression
        | QualifiedLocalModule
    -- Operator errors
        | NoParseForApplication (List2 C.Expr)
        | AmbiguousParseForApplication (List2 C.Expr) (List1 C.Expr)
        | NoParseForLHS LHSOrPatSyn [C.Pattern] C.Pattern
            -- ^ The list contains patterns that failed to be interpreted.
            --   If it is non-empty, the first entry could be printed as error hint.
        | AmbiguousParseForLHS LHSOrPatSyn C.Pattern (List2 C.Pattern)
            -- ^ Pattern and its possible interpretations.
        | AmbiguousProjection QName (List1 QName)
            -- ^ The list contains alternative interpretations of the name.
        | AmbiguousOverloadedProjection AmbiguousQName Doc
        | OperatorInformation [NotationSection] OperatorScope TypeError
            -- ^ The list of notations can be empty.

    -- Usage errors
    -- Instance search errors
    -- Reflection errors
        | DeBruijnIndexOutOfScope Nat Telescope [Name]
            -- ^ The list can be empty.
        | MissingBindingsForTelescopeVariables (List1 ShortText)
    -- Language option errors
        | NeedOptionAllowExec
        | NeedOptionCopatterns
        | NeedOptionPatternMatching
        | NeedOptionProp
    -- Failure associated to warnings
        | NonFatalErrors (Set1 TCWarning)
        | TriedToCopyConstrainedPrim QName
    -- Backend errors
        | BackendDoesNotSupportOnlyScopeChecking BackendName
            -- ^ The given backend does not support @--only-scope-checking@.
        | CustomBackendError BackendName Doc
            -- ^ Used for backend-specific errors. The string is the backend name.
        | UnknownBackend BackendName (Set BackendName)
            -- ^ Unknown backend requested, known ones are in the 'Set'.
          deriving (Int -> TypeError -> ShowS
[TypeError] -> ShowS
TypeError -> String
(Int -> TypeError -> ShowS)
-> (TypeError -> String)
-> ([TypeError] -> ShowS)
-> Show TypeError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TypeError -> ShowS
showsPrec :: Int -> TypeError -> ShowS
$cshow :: TypeError -> String
show :: TypeError -> String
$cshowList :: [TypeError] -> ShowS
showList :: [TypeError] -> ShowS
Show, (forall x. TypeError -> Rep TypeError x)
-> (forall x. Rep TypeError x -> TypeError) -> Generic TypeError
forall x. Rep TypeError x -> TypeError
forall x. TypeError -> Rep TypeError x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. TypeError -> Rep TypeError x
from :: forall x. TypeError -> Rep TypeError x
$cto :: forall x. Rep TypeError x -> TypeError
to :: forall x. Rep TypeError x -> TypeError
Generic)

-- | Name a 'ClashingDefinition' clashes with.
data ClashingName
  = ClashingAbstractName AbstractName
      -- ^ We have 'WhyInScope' information for the previously defined name.
  | ClashingQName        QName
      -- ^ We have no extra information for the previously defined name.
  deriving (Int -> ClashingName -> ShowS
[ClashingName] -> ShowS
ClashingName -> String
(Int -> ClashingName -> ShowS)
-> (ClashingName -> String)
-> ([ClashingName] -> ShowS)
-> Show ClashingName
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ClashingName -> ShowS
showsPrec :: Int -> ClashingName -> ShowS
$cshow :: ClashingName -> String
show :: ClashingName -> String
$cshowList :: [ClashingName] -> ShowS
showList :: [ClashingName] -> ShowS
Show, (forall x. ClashingName -> Rep ClashingName x)
-> (forall x. Rep ClashingName x -> ClashingName)
-> Generic ClashingName
forall x. Rep ClashingName x -> ClashingName
forall x. ClashingName -> Rep ClashingName x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ClashingName -> Rep ClashingName x
from :: forall x. ClashingName -> Rep ClashingName x
$cto :: forall x. Rep ClashingName x -> ClashingName
to :: forall x. Rep ClashingName x -> ClashingName
Generic)

-- | Extract the 'QName' from the 'ClashingName'.
clashingQName :: ClashingName -> QName
clashingQName :: ClashingName -> QName
clashingQName = \case
  ClashingAbstractName AbstractName
x -> AbstractName -> QName
anameName AbstractName
x
  ClashingQName QName
x -> QName
x

-- | Extra information for 'MissingTypeSignature' error.
data MissingTypeSignatureInfo
  = MissingDataSignature     C.Name
      -- ^ The @data@ definition for 'C.Name' lacks a data signature.
  | MissingRecordSignature   C.Name
      -- ^ The @record@ definition for 'C.Name' lacks a record signature.
  | MissingFunctionSignature C.LHS
      -- ^ The function lhs misses a type signature.
  deriving (Int -> MissingTypeSignatureInfo -> ShowS
[MissingTypeSignatureInfo] -> ShowS
MissingTypeSignatureInfo -> String
(Int -> MissingTypeSignatureInfo -> ShowS)
-> (MissingTypeSignatureInfo -> String)
-> ([MissingTypeSignatureInfo] -> ShowS)
-> Show MissingTypeSignatureInfo
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MissingTypeSignatureInfo -> ShowS
showsPrec :: Int -> MissingTypeSignatureInfo -> ShowS
$cshow :: MissingTypeSignatureInfo -> String
show :: MissingTypeSignatureInfo -> String
$cshowList :: [MissingTypeSignatureInfo] -> ShowS
showList :: [MissingTypeSignatureInfo] -> ShowS
Show, (forall x.
 MissingTypeSignatureInfo -> Rep MissingTypeSignatureInfo x)
-> (forall x.
    Rep MissingTypeSignatureInfo x -> MissingTypeSignatureInfo)
-> Generic MissingTypeSignatureInfo
forall x.
Rep MissingTypeSignatureInfo x -> MissingTypeSignatureInfo
forall x.
MissingTypeSignatureInfo -> Rep MissingTypeSignatureInfo x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x.
MissingTypeSignatureInfo -> Rep MissingTypeSignatureInfo x
from :: forall x.
MissingTypeSignatureInfo -> Rep MissingTypeSignatureInfo x
$cto :: forall x.
Rep MissingTypeSignatureInfo x -> MissingTypeSignatureInfo
to :: forall x.
Rep MissingTypeSignatureInfo x -> MissingTypeSignatureInfo
Generic)

-- | Extra information for 'NotAHaskellType' error.
data WhyNotAHaskellType
  = NoPragmaFor QName
  | WrongPragmaFor Range QName
  | BadLambda Term
  | BadMeta Term
  | BadDontCare Term
  | NotCompiled QName
  deriving (Int -> WhyNotAHaskellType -> ShowS
[WhyNotAHaskellType] -> ShowS
WhyNotAHaskellType -> String
(Int -> WhyNotAHaskellType -> ShowS)
-> (WhyNotAHaskellType -> String)
-> ([WhyNotAHaskellType] -> ShowS)
-> Show WhyNotAHaskellType
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> WhyNotAHaskellType -> ShowS
showsPrec :: Int -> WhyNotAHaskellType -> ShowS
$cshow :: WhyNotAHaskellType -> String
show :: WhyNotAHaskellType -> String
$cshowList :: [WhyNotAHaskellType] -> ShowS
showList :: [WhyNotAHaskellType] -> ShowS
Show, (forall x. WhyNotAHaskellType -> Rep WhyNotAHaskellType x)
-> (forall x. Rep WhyNotAHaskellType x -> WhyNotAHaskellType)
-> Generic WhyNotAHaskellType
forall x. Rep WhyNotAHaskellType x -> WhyNotAHaskellType
forall x. WhyNotAHaskellType -> Rep WhyNotAHaskellType x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. WhyNotAHaskellType -> Rep WhyNotAHaskellType x
from :: forall x. WhyNotAHaskellType -> Rep WhyNotAHaskellType x
$cto :: forall x. Rep WhyNotAHaskellType x -> WhyNotAHaskellType
to :: forall x. Rep WhyNotAHaskellType x -> WhyNotAHaskellType
Generic)

-- | Extra information for 'InvalidFileName' error.
data InvalidFileNameReason
  = DoesNotCorrespondToValidModuleName
  | RootNameModuleNotAQualifiedModuleName Text
  deriving (Int -> InvalidFileNameReason -> ShowS
[InvalidFileNameReason] -> ShowS
InvalidFileNameReason -> String
(Int -> InvalidFileNameReason -> ShowS)
-> (InvalidFileNameReason -> String)
-> ([InvalidFileNameReason] -> ShowS)
-> Show InvalidFileNameReason
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> InvalidFileNameReason -> ShowS
showsPrec :: Int -> InvalidFileNameReason -> ShowS
$cshow :: InvalidFileNameReason -> String
show :: InvalidFileNameReason -> String
$cshowList :: [InvalidFileNameReason] -> ShowS
showList :: [InvalidFileNameReason] -> ShowS
Show, (forall x. InvalidFileNameReason -> Rep InvalidFileNameReason x)
-> (forall x. Rep InvalidFileNameReason x -> InvalidFileNameReason)
-> Generic InvalidFileNameReason
forall x. Rep InvalidFileNameReason x -> InvalidFileNameReason
forall x. InvalidFileNameReason -> Rep InvalidFileNameReason x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. InvalidFileNameReason -> Rep InvalidFileNameReason x
from :: forall x. InvalidFileNameReason -> Rep InvalidFileNameReason x
$cto :: forall x. Rep InvalidFileNameReason x -> InvalidFileNameReason
to :: forall x. Rep InvalidFileNameReason x -> InvalidFileNameReason
Generic)

type DataOrRecordE = DataOrRecord' InductionAndEta

data InductionAndEta = InductionAndEta
  { InductionAndEta -> Maybe Induction
recordInduction   :: Maybe Induction
  , InductionAndEta -> EtaEquality
recordEtaEquality :: EtaEquality
  } deriving (Int -> InductionAndEta -> ShowS
[InductionAndEta] -> ShowS
InductionAndEta -> String
(Int -> InductionAndEta -> ShowS)
-> (InductionAndEta -> String)
-> ([InductionAndEta] -> ShowS)
-> Show InductionAndEta
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> InductionAndEta -> ShowS
showsPrec :: Int -> InductionAndEta -> ShowS
$cshow :: InductionAndEta -> String
show :: InductionAndEta -> String
$cshowList :: [InductionAndEta] -> ShowS
showList :: [InductionAndEta] -> ShowS
Show, (forall x. InductionAndEta -> Rep InductionAndEta x)
-> (forall x. Rep InductionAndEta x -> InductionAndEta)
-> Generic InductionAndEta
forall x. Rep InductionAndEta x -> InductionAndEta
forall x. InductionAndEta -> Rep InductionAndEta x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. InductionAndEta -> Rep InductionAndEta x
from :: forall x. InductionAndEta -> Rep InductionAndEta x
$cto :: forall x. Rep InductionAndEta x -> InductionAndEta
to :: forall x. Rep InductionAndEta x -> InductionAndEta
Generic)

-- | Boolean flag whether a name is ambiguous.
data IsAmbiguous
  = YesAmbiguous AmbiguousQName
  | NotAmbiguous
  deriving (Int -> IsAmbiguous -> ShowS
[IsAmbiguous] -> ShowS
IsAmbiguous -> String
(Int -> IsAmbiguous -> ShowS)
-> (IsAmbiguous -> String)
-> ([IsAmbiguous] -> ShowS)
-> Show IsAmbiguous
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> IsAmbiguous -> ShowS
showsPrec :: Int -> IsAmbiguous -> ShowS
$cshow :: IsAmbiguous -> String
show :: IsAmbiguous -> String
$cshowList :: [IsAmbiguous] -> ShowS
showList :: [IsAmbiguous] -> ShowS
Show, (forall x. IsAmbiguous -> Rep IsAmbiguous x)
-> (forall x. Rep IsAmbiguous x -> IsAmbiguous)
-> Generic IsAmbiguous
forall x. Rep IsAmbiguous x -> IsAmbiguous
forall x. IsAmbiguous -> Rep IsAmbiguous x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. IsAmbiguous -> Rep IsAmbiguous x
from :: forall x. IsAmbiguous -> Rep IsAmbiguous x
$cto :: forall x. Rep IsAmbiguous x -> IsAmbiguous
to :: forall x. Rep IsAmbiguous x -> IsAmbiguous
Generic)

-- | Extra information for error 'CannotQuote'.
data CannotQuote
  = CannotQuoteAmbiguous AmbiguousQName
      -- ^ @quote@ is applied to a really ambiguous name.
  | CannotQuoteExpression A.Expr
      -- ^ @quote@ is applied to an expression that is not an unambiguous defined name.
  | CannotQuoteHidden
      -- ^ @quote@ is applied to a non-visible argument.
  | CannotQuoteNothing
      -- ^ @quote@ is unapplied.
  | CannotQuotePattern (NamedArg C.Pattern)
      -- ^ @quote@ is applied to a pattern that is not an unambiguous defined name.
    deriving (Int -> CannotQuote -> ShowS
[CannotQuote] -> ShowS
CannotQuote -> String
(Int -> CannotQuote -> ShowS)
-> (CannotQuote -> String)
-> ([CannotQuote] -> ShowS)
-> Show CannotQuote
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CannotQuote -> ShowS
showsPrec :: Int -> CannotQuote -> ShowS
$cshow :: CannotQuote -> String
show :: CannotQuote -> String
$cshowList :: [CannotQuote] -> ShowS
showList :: [CannotQuote] -> ShowS
Show, (forall x. CannotQuote -> Rep CannotQuote x)
-> (forall x. Rep CannotQuote x -> CannotQuote)
-> Generic CannotQuote
forall x. Rep CannotQuote x -> CannotQuote
forall x. CannotQuote -> Rep CannotQuote x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. CannotQuote -> Rep CannotQuote x
from :: forall x. CannotQuote -> Rep CannotQuote x
$cto :: forall x. Rep CannotQuote x -> CannotQuote
to :: forall x. Rep CannotQuote x -> CannotQuote
Generic)

-- | Distinguish error message when parsing lhs or pattern synonym, resp.
data LHSOrPatSyn = IsLHS | IsPatSyn
  deriving (LHSOrPatSyn -> LHSOrPatSyn -> Bool
(LHSOrPatSyn -> LHSOrPatSyn -> Bool)
-> (LHSOrPatSyn -> LHSOrPatSyn -> Bool) -> Eq LHSOrPatSyn
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LHSOrPatSyn -> LHSOrPatSyn -> Bool
== :: LHSOrPatSyn -> LHSOrPatSyn -> Bool
$c/= :: LHSOrPatSyn -> LHSOrPatSyn -> Bool
/= :: LHSOrPatSyn -> LHSOrPatSyn -> Bool
Eq, Int -> LHSOrPatSyn -> ShowS
[LHSOrPatSyn] -> ShowS
LHSOrPatSyn -> String
(Int -> LHSOrPatSyn -> ShowS)
-> (LHSOrPatSyn -> String)
-> ([LHSOrPatSyn] -> ShowS)
-> Show LHSOrPatSyn
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LHSOrPatSyn -> ShowS
showsPrec :: Int -> LHSOrPatSyn -> ShowS
$cshow :: LHSOrPatSyn -> String
show :: LHSOrPatSyn -> String
$cshowList :: [LHSOrPatSyn] -> ShowS
showList :: [LHSOrPatSyn] -> ShowS
Show, (forall x. LHSOrPatSyn -> Rep LHSOrPatSyn x)
-> (forall x. Rep LHSOrPatSyn x -> LHSOrPatSyn)
-> Generic LHSOrPatSyn
forall x. Rep LHSOrPatSyn x -> LHSOrPatSyn
forall x. LHSOrPatSyn -> Rep LHSOrPatSyn x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. LHSOrPatSyn -> Rep LHSOrPatSyn x
from :: forall x. LHSOrPatSyn -> Rep LHSOrPatSyn x
$cto :: forall x. Rep LHSOrPatSyn x -> LHSOrPatSyn
to :: forall x. Rep LHSOrPatSyn x -> LHSOrPatSyn
Generic, LHSOrPatSyn
LHSOrPatSyn -> LHSOrPatSyn -> Bounded LHSOrPatSyn
forall a. a -> a -> Bounded a
$cminBound :: LHSOrPatSyn
minBound :: LHSOrPatSyn
$cmaxBound :: LHSOrPatSyn
maxBound :: LHSOrPatSyn
Bounded, Int -> LHSOrPatSyn
LHSOrPatSyn -> Int
LHSOrPatSyn -> [LHSOrPatSyn]
LHSOrPatSyn -> LHSOrPatSyn
LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn]
LHSOrPatSyn -> LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn]
(LHSOrPatSyn -> LHSOrPatSyn)
-> (LHSOrPatSyn -> LHSOrPatSyn)
-> (Int -> LHSOrPatSyn)
-> (LHSOrPatSyn -> Int)
-> (LHSOrPatSyn -> [LHSOrPatSyn])
-> (LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn])
-> (LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn])
-> (LHSOrPatSyn -> LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn])
-> Enum LHSOrPatSyn
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: LHSOrPatSyn -> LHSOrPatSyn
succ :: LHSOrPatSyn -> LHSOrPatSyn
$cpred :: LHSOrPatSyn -> LHSOrPatSyn
pred :: LHSOrPatSyn -> LHSOrPatSyn
$ctoEnum :: Int -> LHSOrPatSyn
toEnum :: Int -> LHSOrPatSyn
$cfromEnum :: LHSOrPatSyn -> Int
fromEnum :: LHSOrPatSyn -> Int
$cenumFrom :: LHSOrPatSyn -> [LHSOrPatSyn]
enumFrom :: LHSOrPatSyn -> [LHSOrPatSyn]
$cenumFromThen :: LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn]
enumFromThen :: LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn]
$cenumFromTo :: LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn]
enumFromTo :: LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn]
$cenumFromThenTo :: LHSOrPatSyn -> LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn]
enumFromThenTo :: LHSOrPatSyn -> LHSOrPatSyn -> LHSOrPatSyn -> [LHSOrPatSyn]
Enum)

-- | Exceptions that can be thrown for control flow in the 'TCM'.
--
-- The primary 'TCErr' is 'TypeError', which wraps a 'Diagnostic'
-- signalling an error in the input program into something that can be
-- printed independently of leaving the context or backtracking past the
-- creation of metavariables on the way to raising the error.
--
-- However, 'TCErr' also wraps other nonlocal exits needed during
-- type-checking, like "pattern violations" (signalling that a
-- computation is blocked and should be added as a constraint) or
-- internal errors.
data TCErr
  = TypeError
    { TCErr -> CallStack
tcErrLocation :: CallStack
      -- ^ Location where the error was /originally/ raised.
      --
      -- This value most often comes from a 'HasCallStack' constraint
      -- in the 'Mikan.TypeChecking.Monad.Diagnostic' methods used to
      -- raise the error, but it should be preserved when errors are
      -- re-thrown.
    , TCErr -> TCState
tcErrState    :: TCState
      -- ^ The state in which the error was raised.
      --
      -- This must be switched to before printing the diagnostic, since
      -- it might store arbitrary references to metavariables which no
      -- longer exist after backtracking to where the error was caught.
    , TCErr -> Closure SomeDiagnostic
tcErrClosErr  :: Closure SomeDiagnostic
      -- ^ The diagnostic itself, together with a 'Closure' wrapping its
      -- environment.
      --
      -- Since the 'Closure' stores the 'Call' where the error was
      -- handled, and this is attached to the diagnostic message as
      -- user-facing context, it is important to 'enterClosure' before
      -- doing anything to the diagnostic, and re-thrown diagnostics
      -- should either preserve the 'Closure' or re-build one with the
      -- correct 'Call'.
    }
  | ParserError ParseError
    -- ^ Error raised by the Happy parser.
  | GenericException String
    -- ^ Unspecific error without 'Range'.
  | IOException (Maybe TCState) Range E.IOException
    -- ^ The first argument is the state in which the error was raised.
  | PatternErr Blocker
    -- ^ Raised by elaborator computations blocked on a partial program;
    -- the 'Blocker' is a boolean formula on unsolved metavariables and
    -- partial function definitions which indicates when the computation
    -- should be retried.
    --
    -- A computation that can throw 'PatternErr's should always be wrapped
    -- with a method like 'catchConstraint', which catches the exception
    -- and schedules for it to be retried when the 'Blocker' is solved.
    -- Uncaught 'PatternErr's are equivalent to internal errors.

instance Show TCErr where
  show :: TCErr -> String
show = \case
    TypeError CallStack
_ TCState
_ Closure SomeDiagnostic
e      -> Range -> String
forall a. Pretty a => a -> String
prettyShow (ColdEnv -> Range
envRange (ColdEnv -> Range) -> ColdEnv -> Range
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv (TCEnv -> ColdEnv) -> TCEnv -> ColdEnv
forall a b. (a -> b) -> a -> b
$ Closure SomeDiagnostic -> TCEnv
forall a. Closure a -> TCEnv
clEnv Closure SomeDiagnostic
e) String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
": " String -> ShowS
forall a. [a] -> [a] -> [a]
++ SomeDiagnostic -> String
forall a. Show a => a -> String
show (Closure SomeDiagnostic -> SomeDiagnostic
forall a. Closure a -> a
clValue Closure SomeDiagnostic
e)
    ParserError ParseError
e        -> ParseError -> String
forall a. Pretty a => a -> String
prettyShow ParseError
e
    GenericException String
msg -> String
msg
    IOException Maybe TCState
_ Range
r IOException
e    -> Range -> String
forall a. Pretty a => a -> String
prettyShow Range
r String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
": " String -> ShowS
forall a. [a] -> [a] -> [a]
++ IOException -> String
forall e. Exception e => e -> String
showIOException IOException
e
    PatternErr{}         -> String
"Pattern violation (you shouldn't see this)"

instance HasRange TCErr where
  getRange :: TCErr -> Range
getRange (TypeError CallStack
_ TCState
_ Closure SomeDiagnostic
cl)  = ColdEnv -> Range
envRange (ColdEnv -> Range) -> ColdEnv -> Range
forall a b. (a -> b) -> a -> b
$ TCEnv -> ColdEnv
envColdEnv (TCEnv -> ColdEnv) -> TCEnv -> ColdEnv
forall a b. (a -> b) -> a -> b
$ Closure SomeDiagnostic -> TCEnv
forall a. Closure a -> TCEnv
clEnv Closure SomeDiagnostic
cl
  getRange (ParserError ParseError
e)     = ParseError -> Range
forall a. HasRange a => a -> Range
getRange ParseError
e
  getRange GenericException{}  = Range
forall a. Range' a
noRange
  getRange (IOException Maybe TCState
_ Range
r IOException
_) = Range
r
  getRange PatternErr{}        = Range
forall a. Range' a
noRange

instance E.Exception TCErr

-- | Assorted warnings and errors to be displayed to the user
data WarningsAndNonFatalErrors = WarningsAndNonFatalErrors
  { WarningsAndNonFatalErrors -> Set TCWarning
tcWarnings     :: Set TCWarning
  , WarningsAndNonFatalErrors -> Set TCWarning
nonFatalErrors :: Set TCWarning
  }

instance Null WarningsAndNonFatalErrors where
  null :: WarningsAndNonFatalErrors -> Bool
null (WarningsAndNonFatalErrors Set TCWarning
ws Set TCWarning
errs) = Set TCWarning -> Bool
forall a. Null a => a -> Bool
null Set TCWarning
ws Bool -> Bool -> Bool
&& Set TCWarning -> Bool
forall a. Null a => a -> Bool
null Set TCWarning
errs
  empty :: WarningsAndNonFatalErrors
empty = Set TCWarning -> Set TCWarning -> WarningsAndNonFatalErrors
WarningsAndNonFatalErrors Set TCWarning
forall a. Null a => a
empty Set TCWarning
forall a. Null a => a
empty

------------------------------------------------------------------------------------------------------
-- * Accessing options
------------------------------------------------------------------------------------------------------

instance MonadIO m => HasOptions (TCMT m) where
  pragmaOptions :: TCMT m PragmaOptions
pragmaOptions = Getter TCState PragmaOptions -> TCMT m PragmaOptions
forall (m :: * -> *) a. ReadTCState m => Getter TCState a -> m a
useTC (PragmaOptions -> f PragmaOptions) -> TCState -> f TCState
Lens' TCState PragmaOptions
Getter TCState PragmaOptions
stPragmaOptions
  {-# INLINE pragmaOptions #-}

  commandLineOptions :: TCMT m CommandLineOptions
commandLineOptions = do
    p  <- Getter TCState PragmaOptions -> TCMT m PragmaOptions
forall (m :: * -> *) a. ReadTCState m => Getter TCState a -> m a
useTC (PragmaOptions -> f PragmaOptions) -> TCState -> f TCState
Lens' TCState PragmaOptions
Getter TCState PragmaOptions
stPragmaOptions
    cl <- stPersistentOptions . stPersistentState <$> getTC
    return $ cl { optPragmaOptions = p }
  {-# SPECIALIZE commandLineOptions :: TCM CommandLineOptions #-}

-- HasOptions lifts through monad transformers
-- (see default signatures in the HasOptions class).

enableCaching :: HasOptions m => m Bool
enableCaching :: forall (m :: * -> *). HasOptions m => m Bool
enableCaching = PragmaOptions -> Bool
optCaching (PragmaOptions -> Bool) -> m PragmaOptions -> m Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> m PragmaOptions
forall (m :: * -> *). HasOptions m => m PragmaOptions
pragmaOptions
{-# INLINE enableCaching #-}

-- * The reduce monad
------------------------------------------------------------------------------------------------------

-- | Environment of the reduce monad.
data ReduceEnv = ReduceEnv
  { ReduceEnv -> TCEnv
redEnv  :: !TCEnv    -- ^ Read only access to environment.
  , ReduceEnv -> TCState
redSt   :: !TCState  -- ^ Read only access to state (signature, metas...).
  , ReduceEnv -> SessionState
redSess :: !SessionState -- ^ Read only access to the *session* state (module - source maps, etc)
  , ReduceEnv -> Maybe (MetaId -> ReduceM Bool)
redPred :: !(Maybe (MetaId -> ReduceM Bool))
    -- ^ An optional predicate that is used by 'instantiate'' and
    -- 'instantiateFull'': meta-variables are only instantiated if
    -- they satisfy this predicate.
  }

mapRedEnv :: (TCEnv -> TCEnv) -> ReduceEnv -> ReduceEnv
mapRedEnv :: (TCEnv -> TCEnv) -> ReduceEnv -> ReduceEnv
mapRedEnv TCEnv -> TCEnv
f ReduceEnv
s = ReduceEnv
s { redEnv = f (redEnv s) }
{-# INLINE mapRedEnv #-}

mapRedSt :: (TCState -> TCState) -> ReduceEnv -> ReduceEnv
mapRedSt :: (TCState -> TCState) -> ReduceEnv -> ReduceEnv
mapRedSt TCState -> TCState
f ReduceEnv
s = ReduceEnv
s { redSt = f (redSt s) }
{-# INLINE mapRedSt #-}

mapRedEnvSt :: (TCEnv -> TCEnv) -> (TCState -> TCState) -> ReduceEnv
            -> ReduceEnv
mapRedEnvSt :: (TCEnv -> TCEnv) -> (TCState -> TCState) -> ReduceEnv -> ReduceEnv
mapRedEnvSt TCEnv -> TCEnv
f TCState -> TCState
g (ReduceEnv TCEnv
e TCState
s SessionState
sess Maybe (MetaId -> ReduceM Bool)
p) = TCEnv
-> TCState
-> SessionState
-> Maybe (MetaId -> ReduceM Bool)
-> ReduceEnv
ReduceEnv (TCEnv -> TCEnv
f TCEnv
e) (TCState -> TCState
g TCState
s) SessionState
sess Maybe (MetaId -> ReduceM Bool)
p
{-# INLINE mapRedEnvSt #-}

-- Lenses
reduceEnv :: Lens' ReduceEnv TCEnv
reduceEnv :: Lens' ReduceEnv TCEnv
reduceEnv TCEnv -> f TCEnv
f ReduceEnv
s = TCEnv -> f TCEnv
f (ReduceEnv -> TCEnv
redEnv ReduceEnv
s) f TCEnv -> (TCEnv -> ReduceEnv) -> f ReduceEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ TCEnv
e -> ReduceEnv
s { redEnv = e }
{-# INLINE reduceEnv #-}

reduceSt :: Lens' ReduceEnv TCState
reduceSt :: Lens' ReduceEnv TCState
reduceSt TCState -> f TCState
f ReduceEnv
s = TCState -> f TCState
f (ReduceEnv -> TCState
redSt ReduceEnv
s) f TCState -> (TCState -> ReduceEnv) -> f ReduceEnv
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \ TCState
e -> ReduceEnv
s { redSt = e }
{-# INLINE reduceSt #-}

newtype ReduceM a = ReduceM# { forall a. ReduceM a -> ReduceEnv -> a
unReduceM :: ReduceEnv -> a }

pattern ReduceM :: (ReduceEnv -> a) -> ReduceM a
pattern $bReduceM :: forall a. (ReduceEnv -> a) -> ReduceM a
$mReduceM :: forall {r} {a}.
ReduceM a -> ((ReduceEnv -> a) -> r) -> ((# #) -> r) -> r
ReduceM f <- ReduceM# f where
  ReduceM ReduceEnv -> a
f = (ReduceEnv -> a) -> ReduceM a
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM# ((ReduceEnv -> a) -> ReduceEnv -> a
forall a b. (a -> b) -> a -> b
oneShot \ !ReduceEnv
e -> ReduceEnv -> a
f ReduceEnv
e)
{-# INLINE ReduceM #-}
{-# COMPLETE ReduceM #-}

{-# INLINE unKleisli #-}
unKleisli :: (a -> ReduceM b) -> ReduceM (a -> b)
unKleisli :: forall a b. (a -> ReduceM b) -> ReduceM (a -> b)
unKleisli a -> ReduceM b
f = (ReduceEnv -> a -> b) -> ReduceM (a -> b)
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM \ReduceEnv
env a
x -> ReduceM b -> ReduceEnv -> b
forall a. ReduceM a -> ReduceEnv -> a
unReduceM (a -> ReduceM b
f a
x) ReduceEnv
env

onReduceEnv :: (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a
onReduceEnv :: forall a. (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a
onReduceEnv ReduceEnv -> ReduceEnv
f (ReduceM ReduceEnv -> a
m) = (ReduceEnv -> a) -> ReduceM a
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM \ReduceEnv
e -> ReduceEnv -> a
m (ReduceEnv -> a) -> ReduceEnv -> a
forall a b. (a -> b) -> a -> b
$! ReduceEnv -> ReduceEnv
f ReduceEnv
e
{-# INLINE onReduceEnv #-}

fmapReduce :: (a -> b) -> ReduceM a -> ReduceM b
fmapReduce :: forall a b. (a -> b) -> ReduceM a -> ReduceM b
fmapReduce a -> b
f (ReduceM ReduceEnv -> a
m) = (ReduceEnv -> b) -> ReduceM b
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM \ReduceEnv
e -> a -> b
f (a -> b) -> a -> b
forall a b. (a -> b) -> a -> b
$! ReduceEnv -> a
m ReduceEnv
e
{-# INLINE fmapReduce #-}

-- Andreas, 2021-05-12, issue #5379:
-- It seems more stable to force to evaluate @mf <*> ma@
-- from left to right, for the sake of printing
-- debug messages in order.
apReduce :: ReduceM (a -> b) -> ReduceM a -> ReduceM b
apReduce :: forall a b. ReduceM (a -> b) -> ReduceM a -> ReduceM b
apReduce (ReduceM ReduceEnv -> a -> b
f) (ReduceM ReduceEnv -> a
x) = (ReduceEnv -> b) -> ReduceM b
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM \ReduceEnv
e ->
  let g :: a -> b
g = ReduceEnv -> a -> b
f ReduceEnv
e
      a :: a
a = ReduceEnv -> a
x ReduceEnv
e
  in  a -> b
g (a -> b) -> b -> b
forall a b. a -> b -> b
`pseq` a
a a -> b -> b
forall a b. a -> b -> b
`pseq` a -> b
g a
a
{-# INLINE apReduce #-}


-- Andreas, 2021-05-12, issue #5379
-- Since the MonadDebug instance of ReduceM is implemented via
-- unsafePerformIO, we need to force results that later
-- computations do not depend on, otherwise we lose debug messages.
thenReduce :: ReduceM a -> ReduceM b -> ReduceM b
thenReduce :: forall a b. ReduceM a -> ReduceM b -> ReduceM b
thenReduce (ReduceM ReduceEnv -> a
x) (ReduceM ReduceEnv -> b
y) = (ReduceEnv -> b) -> ReduceM b
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM \ReduceEnv
e -> ReduceEnv -> a
x ReduceEnv
e a -> b -> b
forall a b. a -> b -> b
`pseq` ReduceEnv -> b
y ReduceEnv
e
{-# INLINE thenReduce #-}


-- Andreas, 2021-05-14:
-- `seq` does not force evaluation order, the optimizier is allowed to replace
-- @
--    a `seq` b`
-- @
-- by:
-- @
--    b `seq` a `seq` b
-- @
-- see https://hackage.haskell.org/package/parallel/docs/Control-Parallel.html
--
-- In contrast, `pseq` is only strict in its first argument, so such a permutation
-- is forbidden.
-- If we want to ensure that debug messages are printed before exceptions are
-- propagated, we need to use `pseq`, as in:
-- @
--    unsafePerformIO (putStrLn "Black hawk is going down...") `pseq` throw HitByRPG
-- @
beforeReduce :: ReduceM a -> ReduceM b -> ReduceM a
beforeReduce :: forall a b. ReduceM a -> ReduceM b -> ReduceM a
beforeReduce (ReduceM ReduceEnv -> a
x) (ReduceM ReduceEnv -> b
y) = (ReduceEnv -> a) -> ReduceM a
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM ((ReduceEnv -> a) -> ReduceM a) -> (ReduceEnv -> a) -> ReduceM a
forall a b. (a -> b) -> a -> b
$ \ ReduceEnv
e ->
  let a :: a
a = ReduceEnv -> a
x ReduceEnv
e
  in  a
a a -> a -> a
forall a b. a -> b -> b
`pseq` ReduceEnv -> b
y ReduceEnv
e b -> a -> a
forall a b. a -> b -> b
`pseq` a
a
{-# INLINE beforeReduce #-}

bindReduce :: ReduceM a -> (a -> ReduceM b) -> ReduceM b
bindReduce :: forall a b. ReduceM a -> (a -> ReduceM b) -> ReduceM b
bindReduce (ReduceM ReduceEnv -> a
m) a -> ReduceM b
f = (ReduceEnv -> b) -> ReduceM b
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM ((ReduceEnv -> b) -> ReduceM b) -> (ReduceEnv -> b) -> ReduceM b
forall a b. (a -> b) -> a -> b
$ \ ReduceEnv
e -> ReduceM b -> ReduceEnv -> b
forall a. ReduceM a -> ReduceEnv -> a
unReduceM (a -> ReduceM b
f (a -> ReduceM b) -> a -> ReduceM b
forall a b. (a -> b) -> a -> b
$! ReduceEnv -> a
m ReduceEnv
e) ReduceEnv
e
{-# INLINE bindReduce #-}

instance Functor ReduceM where
  fmap :: forall a b. (a -> b) -> ReduceM a -> ReduceM b
fmap = (a -> b) -> ReduceM a -> ReduceM b
forall a b. (a -> b) -> ReduceM a -> ReduceM b
fmapReduce

instance Applicative ReduceM where
  pure :: forall a. a -> ReduceM a
pure a
x = (ReduceEnv -> a) -> ReduceM a
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM (a -> ReduceEnv -> a
forall a b. a -> b -> a
const a
x)
  <*> :: forall a b. ReduceM (a -> b) -> ReduceM a -> ReduceM b
(<*>) = ReduceM (a -> b) -> ReduceM a -> ReduceM b
forall a b. ReduceM (a -> b) -> ReduceM a -> ReduceM b
apReduce
  *> :: forall a b. ReduceM a -> ReduceM b -> ReduceM b
(*>)  = ReduceM a -> ReduceM b -> ReduceM b
forall a b. ReduceM a -> ReduceM b -> ReduceM b
thenReduce
  <* :: forall a b. ReduceM a -> ReduceM b -> ReduceM a
(<*)  = ReduceM a -> ReduceM b -> ReduceM a
forall a b. ReduceM a -> ReduceM b -> ReduceM a
beforeReduce

instance Monad ReduceM where
  return :: forall a. a -> ReduceM a
return = a -> ReduceM a
forall a. a -> ReduceM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
  >>= :: forall a b. ReduceM a -> (a -> ReduceM b) -> ReduceM b
(>>=) = ReduceM a -> (a -> ReduceM b) -> ReduceM b
forall a b. ReduceM a -> (a -> ReduceM b) -> ReduceM b
bindReduce
  >> :: forall a b. ReduceM a -> ReduceM b -> ReduceM b
(>>) = ReduceM a -> ReduceM b -> ReduceM b
forall a b. ReduceM a -> ReduceM b -> ReduceM b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
(*>)

instance MonadFail ReduceM where
  fail :: forall a. String -> ReduceM a
fail = String -> ReduceM a
forall a. HasCallStack => String -> a
error

instance ReadTCState ReduceM where
  getTCState :: ReduceM TCState
getTCState = (ReduceEnv -> TCState) -> ReduceM TCState
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM ReduceEnv -> TCState
redSt
  getSessionState :: ReduceM SessionState
getSessionState = (ReduceEnv -> SessionState) -> ReduceM SessionState
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM ReduceEnv -> SessionState
redSess

  locallyTCState :: forall a b. Lens' TCState a -> (a -> a) -> ReduceM b -> ReduceM b
locallyTCState Lens' TCState a
l a -> a
f = (ReduceEnv -> ReduceEnv) -> ReduceM b -> ReduceM b
forall a. (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a
onReduceEnv ((ReduceEnv -> ReduceEnv) -> ReduceM b -> ReduceM b)
-> (ReduceEnv -> ReduceEnv) -> ReduceM b -> ReduceM b
forall a b. (a -> b) -> a -> b
$ (TCState -> TCState) -> ReduceEnv -> ReduceEnv
mapRedSt ((TCState -> TCState) -> ReduceEnv -> ReduceEnv)
-> (TCState -> TCState) -> ReduceEnv -> ReduceEnv
forall a b. (a -> b) -> a -> b
$ ASetter TCState TCState a a -> (a -> a) -> TCState -> TCState
forall s t a b. ASetter s t a b -> (a -> b) -> s -> t
over ASetter TCState TCState a a
Lens' TCState a
l a -> a
f

instance ExpandCase rep a => ExpandCase rep (ReduceM a) where
  type Result rep (ReduceM a) = Result rep a
  {-# INLINE expand #-}
  expand :: ((ReduceM a -> Result rep (ReduceM a)) -> Result rep (ReduceM a))
-> ReduceM a
expand (ReduceM a -> Result rep (ReduceM a)) -> Result rep (ReduceM a)
k =
    (ReduceEnv -> a) -> ReduceM a
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM ((ReduceEnv -> a) -> ReduceEnv -> a
forall a b. (a -> b) -> a -> b
oneShot \ ~ReduceEnv
r ->
     ((a -> Result rep a) -> Result rep a) -> a
forall a.
ExpandCase LiftedRep a =>
((a -> Result LiftedRep a) -> Result LiftedRep a) -> a
expand (((a -> Result rep a) -> Result rep a)
-> (a -> Result rep a) -> Result rep a
forall a b. (a -> b) -> a -> b
oneShot \a -> Result rep a
deflateA -> let r' :: ReduceEnv
r' = ReduceEnv
r in (ReduceM a -> Result rep (ReduceM a)) -> Result rep (ReduceM a)
k ((ReduceM a -> Result rep a) -> ReduceM a -> Result rep a
forall a b. (a -> b) -> a -> b
oneShot \ReduceM a
act -> a -> Result rep a
deflateA (ReduceM a -> ReduceEnv -> a
forall a. ReduceM a -> ReduceEnv -> a
unReduceM ReduceM a
act ReduceEnv
r'))))

runReduceM :: ReduceM a -> TCM a
runReduceM :: forall a. ReduceM a -> TCM a
runReduceM ReduceM a
m = (IORef TCState -> TCEnv -> IO a) -> TCMT IO a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> IO a) -> TCMT IO a)
-> (IORef TCState -> TCEnv -> IO a) -> TCMT IO a
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
r TCEnv
e -> do
  s <- IORef TCState -> IO TCState
forall a. IORef a -> IO a
Strict.readIORef IORef TCState
r
  sess <- readAtomic (stPersistentSession (stPersistentState s))
  E.evaluate $ unReduceM m $ ReduceEnv e s sess Nothing
  -- Andreas, 2021-05-13, issue #5379
  -- This was the following, which is apparently not strict enough
  -- to force all unsafePerformIOs...
  -- runReduceM m = do
  --   e <- askTC
  --   s <- getTC
  --   return $! unReduceM m (ReduceEnv e s)

instance MonadTCEnv ReduceM where
  {-# INLINE askTC #-}
  askTC :: ReduceM TCEnv
askTC   = (ReduceEnv -> TCEnv) -> ReduceM TCEnv
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM ReduceEnv -> TCEnv
redEnv
  {-# INLINE localTC #-}
  localTC :: forall a. (TCEnv -> TCEnv) -> ReduceM a -> ReduceM a
localTC = (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a
forall a. (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a
onReduceEnv ((ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a)
-> ((TCEnv -> TCEnv) -> ReduceEnv -> ReduceEnv)
-> (TCEnv -> TCEnv)
-> ReduceM a
-> ReduceM a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TCEnv -> TCEnv) -> ReduceEnv -> ReduceEnv
mapRedEnv

-- Andrea comments (https://github.com/agda/agda/issues/1829#issuecomment-522312084):
--
--   useR forces the result of projecting the lens,
--   this usually prevents retaining the whole structure when we only need a field.
--
-- This fixes (or contributes to the fix of) the space leak issue #1829 (caching).
useR :: (ReadTCState m) => Lens' TCState a -> m a
useR :: forall (m :: * -> *) a. ReadTCState m => Lens' TCState a -> m a
useR Lens' TCState a
l = do
  !x <- m TCState
forall (m :: * -> *). ReadTCState m => m TCState
getTCState m TCState -> (TCState -> a) -> m a
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> (TCState -> Getting a TCState a -> a
forall s a. s -> Getting a s a -> a
^. Getting a TCState a
Lens' TCState a
l)
  return x
{-# INLINE useR #-}

askR :: ReduceM ReduceEnv
askR :: ReduceM ReduceEnv
askR = (ReduceEnv -> ReduceEnv) -> ReduceM ReduceEnv
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM ReduceEnv -> ReduceEnv
forall r (m :: * -> *). MonadReader r m => m r
ask
{-# INLINE askR #-}

localR :: (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a
localR :: forall a. (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a
localR ReduceEnv -> ReduceEnv
f = (ReduceEnv -> a) -> ReduceM a
forall a. (ReduceEnv -> a) -> ReduceM a
ReduceM ((ReduceEnv -> a) -> ReduceM a)
-> (ReduceM a -> ReduceEnv -> a) -> ReduceM a -> ReduceM a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ReduceEnv -> ReduceEnv) -> (ReduceEnv -> a) -> ReduceEnv -> a
forall a.
(ReduceEnv -> ReduceEnv) -> (ReduceEnv -> a) -> ReduceEnv -> a
forall r (m :: * -> *) a. MonadReader r m => (r -> r) -> m a -> m a
local ReduceEnv -> ReduceEnv
f ((ReduceEnv -> a) -> ReduceEnv -> a)
-> (ReduceM a -> ReduceEnv -> a) -> ReduceM a -> ReduceEnv -> a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ReduceM a -> ReduceEnv -> a
forall a. ReduceM a -> ReduceEnv -> a
unReduceM
{-# INLINE localR #-}

instance HasOptions ReduceM where
  pragmaOptions :: ReduceM PragmaOptions
pragmaOptions      = Lens' TCState PragmaOptions -> ReduceM PragmaOptions
forall (m :: * -> *) a. ReadTCState m => Lens' TCState a -> m a
useR (PragmaOptions -> f PragmaOptions) -> TCState -> f TCState
Lens' TCState PragmaOptions
stPragmaOptions
  commandLineOptions :: ReduceM CommandLineOptions
commandLineOptions = do
    p  <- Lens' TCState PragmaOptions -> ReduceM PragmaOptions
forall (m :: * -> *) a. ReadTCState m => Lens' TCState a -> m a
useR (PragmaOptions -> f PragmaOptions) -> TCState -> f TCState
Lens' TCState PragmaOptions
stPragmaOptions
    cl <- stPersistentOptions . stPersistentState <$> getTCState
    return $ cl{ optPragmaOptions = p }

class ( Applicative m
      , MonadTCEnv m
      , ReadTCState m
      , HasOptions m
      ) => MonadReduce m where
  liftReduce :: ReduceM a -> m a

  default liftReduce :: (MonadTrans t, MonadReduce n, t n ~ m) => ReduceM a -> m a
  liftReduce = n a -> m a
n a -> t n a
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (n a -> m a) -> (ReduceM a -> n a) -> ReduceM a -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ReduceM a -> n a
forall a. ReduceM a -> n a
forall (m :: * -> *) a. MonadReduce m => ReduceM a -> m a
liftReduce

instance MonadReduce ReduceM where
  liftReduce :: forall a. ReduceM a -> ReduceM a
liftReduce = ReduceM a -> ReduceM a
forall a. a -> a
id

instance MonadReduce m => MonadReduce (ChangeT m)
instance MonadReduce m => MonadReduce (ExceptT err m)
instance MonadReduce m => MonadReduce (IdentityT m)
instance MonadReduce m => MonadReduce (ListT m)
instance MonadReduce m => MonadReduce (MaybeT m)
instance MonadReduce m => MonadReduce (ReaderT r m)
instance MonadReduce m => MonadReduce (StateT w m)
instance (Monoid w, MonadReduce m) => MonadReduce (WriterT w m)
instance MonadReduce m => MonadReduce (Strict.ReaderT r m)
instance MonadReduce m => MonadReduce (Strict.StateT w m)
instance (Monoid w, MonadReduce m) => MonadReduce (Strict.WriterT w m)
instance MonadReduce m => MonadReduce (BlockT m)

----------------------------------------------------------------------------------------------------
-- * Monad with read-only 'TCEnv'
----------------------------------------------------------------------------------------------------

-- | @MonadTCEnv@ made into its own dedicated service class.
--   This allows us to use 'MonadReader' for 'ReaderT' extensions of @TCM@.
class Monad m => MonadTCEnv m where
  askTC   :: m TCEnv
  localTC :: (TCEnv -> TCEnv) -> m a -> m a

  default askTC :: (MonadTrans t, MonadTCEnv n, t n ~ m) => m TCEnv
  askTC = n TCEnv -> t n TCEnv
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift n TCEnv
forall (m :: * -> *). MonadTCEnv m => m TCEnv
askTC

  default localTC
    :: (MonadTransControl t, MonadTCEnv n, t n ~ m)
    =>  (TCEnv -> TCEnv) -> m a -> m a
  localTC = (n (StT t a) -> n (StT t a)) -> m a -> m a
(n (StT t a) -> n (StT t a)) -> t n a -> t n a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a b.
(MonadTransControl t, Monad (t m), Monad m) =>
(m (StT t a) -> m (StT t b)) -> t m a -> t m b
liftThrough ((n (StT t a) -> n (StT t a)) -> m a -> m a)
-> ((TCEnv -> TCEnv) -> n (StT t a) -> n (StT t a))
-> (TCEnv -> TCEnv)
-> m a
-> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TCEnv -> TCEnv) -> n (StT t a) -> n (StT t a)
forall a. (TCEnv -> TCEnv) -> n a -> n a
forall (m :: * -> *) a.
MonadTCEnv m =>
(TCEnv -> TCEnv) -> m a -> m a
localTC

instance MonadTCEnv m => MonadTCEnv (ChangeT m)
instance MonadTCEnv m => MonadTCEnv (ExceptT err m)
instance MonadTCEnv m => MonadTCEnv (IdentityT m)
instance MonadTCEnv m => MonadTCEnv (MaybeT m)
instance MonadTCEnv m => MonadTCEnv (ReaderT r m)
instance MonadTCEnv m => MonadTCEnv (StateT s m)
instance (Monoid w, MonadTCEnv m) => MonadTCEnv (WriterT w m)
instance MonadTCEnv m => MonadTCEnv (Strict.ReaderT r m)
instance MonadTCEnv m => MonadTCEnv (Strict.StateT s m)
instance (Monoid w, MonadTCEnv m) => MonadTCEnv (Strict.WriterT w m)

instance MonadTCEnv m => MonadTCEnv (ListT m) where
  localTC :: forall a. (TCEnv -> TCEnv) -> ListT m a -> ListT m a
localTC = (m (Maybe (a, ListT m a)) -> m (Maybe (a, ListT m a)))
-> ListT m a -> ListT m a
forall (m :: * -> *) a (n :: * -> *) b.
(m (Maybe (a, ListT m a)) -> n (Maybe (b, ListT n b)))
-> ListT m a -> ListT n b
mapListT ((m (Maybe (a, ListT m a)) -> m (Maybe (a, ListT m a)))
 -> ListT m a -> ListT m a)
-> ((TCEnv -> TCEnv)
    -> m (Maybe (a, ListT m a)) -> m (Maybe (a, ListT m a)))
-> (TCEnv -> TCEnv)
-> ListT m a
-> ListT m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TCEnv -> TCEnv)
-> m (Maybe (a, ListT m a)) -> m (Maybe (a, ListT m a))
forall a. (TCEnv -> TCEnv) -> m a -> m a
forall (m :: * -> *) a.
MonadTCEnv m =>
(TCEnv -> TCEnv) -> m a -> m a
localTC

{-# INLINE asksTC #-}
asksTC :: MonadTCEnv m => (TCEnv -> a) -> m a
asksTC :: forall (m :: * -> *) a. MonadTCEnv m => (TCEnv -> a) -> m a
asksTC TCEnv -> a
f = TCEnv -> a
f (TCEnv -> a) -> m TCEnv -> m a
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> m TCEnv
forall (m :: * -> *). MonadTCEnv m => m TCEnv
askTC

{-# INLINE viewTC #-}
viewTC :: MonadTCEnv m => Lens' TCEnv a -> m a
viewTC :: forall (m :: * -> *) a. MonadTCEnv m => Lens' TCEnv a -> m a
viewTC Lens' TCEnv a
l = (TCEnv -> a) -> m a
forall (m :: * -> *) a. MonadTCEnv m => (TCEnv -> a) -> m a
asksTC (TCEnv -> Getting a TCEnv a -> a
forall s a. s -> Getting a s a -> a
^. Getting a TCEnv a
Lens' TCEnv a
l)

{-# INLINE locallyTC #-}
-- | Modify the lens-indicated part of the @TCEnv@ in a subcomputation.
locallyTC :: MonadTCEnv m => Lens' TCEnv a -> (a -> a) -> m b -> m b
locallyTC :: forall (m :: * -> *) a b.
MonadTCEnv m =>
Lens' TCEnv a -> (a -> a) -> m b -> m b
locallyTC Lens' TCEnv a
l = (TCEnv -> TCEnv) -> m b -> m b
forall a. (TCEnv -> TCEnv) -> m a -> m a
forall (m :: * -> *) a.
MonadTCEnv m =>
(TCEnv -> TCEnv) -> m a -> m a
localTC ((TCEnv -> TCEnv) -> m b -> m b)
-> ((a -> a) -> TCEnv -> TCEnv) -> (a -> a) -> m b -> m b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ASetter TCEnv TCEnv a a -> (a -> a) -> TCEnv -> TCEnv
forall s t a b. ASetter s t a b -> (a -> b) -> s -> t
over ASetter TCEnv TCEnv a a
Lens' TCEnv a
l

----------------------------------------------------------------------------------------------------
-- * Monad with mutable 'TCState'
----------------------------------------------------------------------------------------------------

-- | A 'Monad' that has read/write access to the module-local mutable
-- 'TCState'.
class Monad m => MonadTCState m where
  -- | Read the current TC state.
  getTC :: m TCState

  -- | Replace the entire TC state. This method should be strict in the state!
  putTC :: TCState -> m ()

  default getTC :: (MonadTrans t, MonadTCState n, t n ~ m) => m TCState
  getTC = n TCState -> t n TCState
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift n TCState
forall (m :: * -> *). MonadTCState m => m TCState
getTC

  default putTC :: (MonadTrans t, MonadTCState n, t n ~ m) => TCState -> m ()
  putTC = n () -> m ()
n () -> t n ()
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (n () -> m ()) -> (TCState -> n ()) -> TCState -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TCState -> n ()
forall (m :: * -> *). MonadTCState m => TCState -> m ()
putTC

  {-# INLINE modifyTC #-}
  -- | Apply a function to the current TC state.
  --
  -- This method should be strict in the new state! The default
  -- implementation is in terms of 'getTC' and 'putTC', so it inherits
  -- the strictness of 'putTC'.
  modifyTC :: (TCState -> TCState) -> m ()
  modifyTC TCState -> TCState
f = do
    s <- m TCState
forall (m :: * -> *). MonadTCState m => m TCState
getTC
    putTC $! f s

instance MonadTCState m => MonadTCState (MaybeT m)
instance MonadTCState m => MonadTCState (ListT m)
instance MonadTCState m => MonadTCState (ExceptT err m)
instance MonadTCState m => MonadTCState (ReaderT r m)
instance MonadTCState m => MonadTCState (StateT s m)
instance (Monoid w, MonadTCState m) => MonadTCState (WriterT w m)
instance MonadTCState m => MonadTCState (ChangeT m)
instance MonadTCState m => MonadTCState (IdentityT m)
instance MonadTCState m => MonadTCState (Strict.ReaderT r m)
instance MonadTCState m => MonadTCState (Strict.StateT s m)
instance (Monoid w, MonadTCState m) => MonadTCState (Strict.WriterT w m)


{-# INLINE getsTC #-}
-- ** @TCState@ accessors (no lenses)
getsTC :: ReadTCState m => (TCState -> a) -> m a
getsTC :: forall (m :: * -> *) a. ReadTCState m => (TCState -> a) -> m a
getsTC TCState -> a
f = TCState -> a
f (TCState -> a) -> m TCState -> m a
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> m TCState
forall (m :: * -> *). ReadTCState m => m TCState
getTCState

-- ** @TCState@ accessors via lenses

{-# INLINE useTC #-}
-- | Read the value of a 'Getter' into the 'TCState'.
--
-- This is strict in the returned value.
useTC :: ReadTCState m => Getter TCState a -> m a
useTC :: forall (m :: * -> *) a. ReadTCState m => Getter TCState a -> m a
useTC Getter TCState a
l = do
  !x <- (TCState -> a) -> m a
forall (m :: * -> *) a. ReadTCState m => (TCState -> a) -> m a
getsTC (TCState -> Getting a TCState a -> a
forall s a. s -> Getting a s a -> a
^. Getting a TCState a
Getter TCState a
l)
  return x

infix 4 `setTCLens`

{-# INLINE setTCLens #-}
-- | Overwrite the part of the 'TCState' focused on by the lens.
--
-- This is strict in the spine of the 'TCState', but not necessarily in
-- the value (e.g., if the lens targets a lazy field).
setTCLens :: MonadTCState m => ASetter' TCState a -> a -> m ()
setTCLens :: forall (m :: * -> *) a.
MonadTCState m =>
ASetter' TCState a -> a -> m ()
setTCLens ASetter' TCState a
l = (TCState -> TCState) -> m ()
forall (m :: * -> *).
MonadTCState m =>
(TCState -> TCState) -> m ()
modifyTC ((TCState -> TCState) -> m ())
-> (a -> TCState -> TCState) -> a -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ASetter' TCState a -> a -> TCState -> TCState
forall s t a b. ASetter s t a b -> b -> s -> t
set ASetter' TCState a
l

{-# INLINE modifyingTC #-}
-- | Modify the part of the 'TCState' focused on by the lens.
--
-- This is strict in the spine of the 'TCState', but not necessarily in
-- the value (e.g., if the lens targets a lazy field).
modifyingTC :: MonadTCState m => ASetter' TCState a -> (a -> a) -> m ()
modifyingTC :: forall (m :: * -> *) a.
MonadTCState m =>
ASetter' TCState a -> (a -> a) -> m ()
modifyingTC ASetter' TCState a
l = (TCState -> TCState) -> m ()
forall (m :: * -> *).
MonadTCState m =>
(TCState -> TCState) -> m ()
modifyTC ((TCState -> TCState) -> m ())
-> ((a -> a) -> TCState -> TCState) -> (a -> a) -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ASetter' TCState a -> (a -> a) -> TCState -> TCState
forall s t a b. ASetter s t a b -> (a -> b) -> s -> t
over ASetter' TCState a
l

{-# INLINE modifyingTCM #-}
-- | Modify a part of the state monadically.
--
-- This is an instance of 'Mikan.Utils.Lens.%=='.
modifyingTCM :: (MonadTCState m, ReadTCState m) => Lens' TCState a -> (a -> m a) -> m ()
modifyingTCM :: forall (m :: * -> *) a.
(MonadTCState m, ReadTCState m) =>
Lens' TCState a -> (a -> m a) -> m ()
modifyingTCM Lens' TCState a
l a -> m a
f = Getter TCState a -> m a
forall (m :: * -> *) a. ReadTCState m => Getter TCState a -> m a
useTC (a -> f a) -> TCState -> f TCState
Lens' TCState a
Getter TCState a
l m a -> (a -> m a) -> m a
forall a b. m a -> (a -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= a -> m a
f m a -> (a -> m ()) -> m ()
forall a b. m a -> (a -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ASetter' TCState a -> a -> m ()
forall (m :: * -> *) a.
MonadTCState m =>
ASetter' TCState a -> a -> m ()
setTCLens ASetter' TCState a
Lens' TCState a
l
  -- Note:
  -- The implementation @getTC >>= l f >>= putTC@ loses state changes
  -- contained in @f@, see https://github.com/agda/agda/pull/7470#discussion_r1747232483

{-# INLINE stateTCLens #-}
-- | Modify the part of the 'TCState' focused on by the lens, and return some result.
stateTCLens :: (MonadTCState m, ReadTCState m) => Lens' TCState a -> (a -> (r , a)) -> m r
stateTCLens :: forall (m :: * -> *) a r.
(MonadTCState m, ReadTCState m) =>
Lens' TCState a -> (a -> (r, a)) -> m r
stateTCLens Lens' TCState a
l a -> (r, a)
f = Lens' TCState a -> (a -> m (r, a)) -> m r
forall (m :: * -> *) a r.
(MonadTCState m, ReadTCState m) =>
Lens' TCState a -> (a -> m (r, a)) -> m r
stateTCLensM (a -> f a) -> TCState -> f TCState
Lens' TCState a
l ((a -> m (r, a)) -> m r) -> (a -> m (r, a)) -> m r
forall a b. (a -> b) -> a -> b
$ (r, a) -> m (r, a)
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ((r, a) -> m (r, a)) -> (a -> (r, a)) -> a -> m (r, a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> (r, a)
f

{-# INLINE stateTCLensM #-}
-- | Modify a part of the state monadically, and return some result.
--
--   This is an instance of 'Mikan.Utils.Lens.%%=!'.
stateTCLensM :: (MonadTCState m, ReadTCState m) => Lens' TCState a -> (a -> m (r , a)) -> m r
stateTCLensM :: forall (m :: * -> *) a r.
(MonadTCState m, ReadTCState m) =>
Lens' TCState a -> (a -> m (r, a)) -> m r
stateTCLensM Lens' TCState a
l a -> m (r, a)
f = do
  a <- Getter TCState a -> m a
forall (m :: * -> *) a. ReadTCState m => Getter TCState a -> m a
useTC (a -> f a) -> TCState -> f TCState
Lens' TCState a
Getter TCState a
l
  (result , a') <- f a
  result <$ setTCLens l a'

{-# INLINE useSession #-}
-- | Access a part of the 'SessionState' through a lens.
useSession :: ReadTCState m => Lens' SessionState a -> m a
useSession :: forall (m :: * -> *) a.
ReadTCState m =>
Lens' SessionState a -> m a
useSession Lens' SessionState a
l = Getting a SessionState a -> SessionState -> a
forall s (m :: * -> *) a. MonadReader s m => Getting a s a -> m a
view Getting a SessionState a
Lens' SessionState a
l (SessionState -> a) -> m SessionState -> m a
forall (m :: * -> *) a b. Monad m => (a -> b) -> m a -> m b
<$!> m SessionState
forall (m :: * -> *). ReadTCState m => m SessionState
getSessionState

class ReadTCState m => ModifySession m where
  -- | Modify a part of the 'SessionState' through a lens. If the
  -- continuation fails, modifications to the *session* state are reset.
  -- Other monadic states will not necessarily be reverted.
  --
  -- This function keeps an **exclusive** lock on the session state
  -- **for the entire execution of the continuation**, regardless of
  -- what the given lens focuses on.
  --
  -- No thread can access **any** part of the session state while
  -- 'stateSessionLensM' is executing. This includes the continuation!
  -- Nested applications of this function **will always** deadlock.
  --
  -- This function is strict in the modification to the session state,
  -- and the exclusive lock on the session state is maintained for the
  -- duration of forcing the new session state.
  --
  -- This function has a few variants if less flexibility is required:
  -- * 'stateSessionLens' takes a pure modification function.
  -- * 'modifySession' does not allow returning an additional result.
  stateSessionLensM :: Lens' SessionState a -> (a -> m (r, a)) -> m r

instance (MonadIO m, Catch.MonadMask m) => ModifySession (TCMT m) where

  -- The heavy lifting for synchronization and atomicity is handled by
  -- 'modifyAtomic', we just have to thread the TCM part of the state
  -- through.
  stateSessionLensM :: Lens' SessionState a -> (a -> TCMT m (r, a)) -> TCMT m r
  stateSessionLensM :: forall a r.
Lens' SessionState a -> (a -> TCMT m (r, a)) -> TCMT m r
stateSessionLensM Lens' SessionState a
l a -> TCMT m (r, a)
f = (IORef TCState -> TCEnv -> m r) -> TCMT m r
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM \IORef TCState
st TCEnv
env -> do
    mv <- PersistentTCState -> Atomic SessionState
stPersistentSession (PersistentTCState -> Atomic SessionState)
-> (TCState -> PersistentTCState) -> TCState -> Atomic SessionState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TCState -> PersistentTCState
stPersistentState (TCState -> Atomic SessionState)
-> m TCState -> m (Atomic SessionState)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO TCState -> m TCState
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IORef TCState -> IO TCState
forall a. IORef a -> IO a
Strict.readIORef IORef TCState
st)
    modifyAtomic mv \SessionState
sess -> do
      (ret, new) <- TCMT m (r, a) -> IORef TCState -> TCEnv -> m (r, a)
forall (m :: * -> *) a. TCMT m a -> IORef TCState -> TCEnv -> m a
unTCM (a -> TCMT m (r, a)
f (a -> TCMT m (r, a)) -> a -> TCMT m (r, a)
forall a b. (a -> b) -> a -> b
$! SessionState
sess SessionState -> Getting a SessionState a -> a
forall s a. s -> Getting a s a -> a
^. Getting a SessionState a
Lens' SessionState a
l) IORef TCState
st TCEnv
env
      let sess' = ASetter SessionState SessionState a a
-> a -> SessionState -> SessionState
forall s t a b. ASetter s t a b -> b -> s -> t
set ASetter SessionState SessionState a a
Lens' SessionState a
l a
new SessionState
sess
      sess' `seq` pure (sess', ret)

instance ModifySession m => ModifySession (StateT s m) where
  stateSessionLensM :: forall a r.
Lens' SessionState a -> (a -> StateT s m (r, a)) -> StateT s m r
stateSessionLensM Lens' SessionState a
l a -> StateT s m (r, a)
k = (s -> m (r, s)) -> StateT s m r
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT \s
s -> Lens' SessionState a -> (a -> m ((r, s), a)) -> m (r, s)
forall a r. Lens' SessionState a -> (a -> m (r, a)) -> m r
forall (m :: * -> *) a r.
ModifySession m =>
Lens' SessionState a -> (a -> m (r, a)) -> m r
stateSessionLensM (a -> f a) -> SessionState -> f SessionState
Lens' SessionState a
l \a
v ->
    StateT s m (r, a) -> s -> m ((r, a), s)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT (a -> StateT s m (r, a)
k a
v) s
s m ((r, a), s) -> (((r, a), s) -> ((r, s), a)) -> m ((r, s), a)
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \((r
r, a
a), s
s) -> ((r
r, s
s), a
a)

instance ModifySession m => ModifySession (MaybeT m) where
  stateSessionLensM :: forall a r.
Lens' SessionState a -> (a -> MaybeT m (r, a)) -> MaybeT m r
stateSessionLensM Lens' SessionState a
l a -> MaybeT m (r, a)
k = m (Maybe r) -> MaybeT m r
forall (m :: * -> *) a. m (Maybe a) -> MaybeT m a
MaybeT (m (Maybe r) -> MaybeT m r) -> m (Maybe r) -> MaybeT m r
forall a b. (a -> b) -> a -> b
$ Lens' SessionState a -> (a -> m (Maybe r, a)) -> m (Maybe r)
forall a r. Lens' SessionState a -> (a -> m (r, a)) -> m r
forall (m :: * -> *) a r.
ModifySession m =>
Lens' SessionState a -> (a -> m (r, a)) -> m r
stateSessionLensM (a -> f a) -> SessionState -> f SessionState
Lens' SessionState a
l \a
v -> MaybeT m (r, a) -> m (Maybe (r, a))
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (a -> MaybeT m (r, a)
k a
v) m (Maybe (r, a))
-> (Maybe (r, a) -> m (Maybe r, a)) -> m (Maybe r, a)
forall a b. m a -> (a -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Just (r
r, a
a) -> (Maybe r, a) -> m (Maybe r, a)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (r -> Maybe r
forall a. a -> Maybe a
Just r
r, a
a)
    Maybe (r, a)
Nothing     -> (Maybe r, a) -> m (Maybe r, a)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe r
forall a. Maybe a
Nothing, a
v)

{-# INLINE stateSessionLens #-}
-- | Like 'stateSessionLensM', but the modification function is not
-- allowed to perform effects.
stateSessionLens :: ModifySession m => Lens' SessionState a -> (a -> (r, a)) -> m r
stateSessionLens :: forall (m :: * -> *) a r.
ModifySession m =>
Lens' SessionState a -> (a -> (r, a)) -> m r
stateSessionLens Lens' SessionState a
l a -> (r, a)
f = Lens' SessionState a -> (a -> m (r, a)) -> m r
forall a r. Lens' SessionState a -> (a -> m (r, a)) -> m r
forall (m :: * -> *) a r.
ModifySession m =>
Lens' SessionState a -> (a -> m (r, a)) -> m r
stateSessionLensM (a -> f a) -> SessionState -> f SessionState
Lens' SessionState a
l ((a -> m (r, a)) -> m r) -> (a -> m (r, a)) -> m r
forall a b. (a -> b) -> a -> b
$ (r, a) -> m (r, a)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((r, a) -> m (r, a)) -> (a -> (r, a)) -> a -> m (r, a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> (r, a)
f

{-# INLINE modifySession #-}
-- | Like 'stateSessionLens', but the modification function can not
-- return an extra result.
modifySession :: ModifySession m => Lens' SessionState a -> (a -> a) -> m ()
modifySession :: forall (m :: * -> *) a.
ModifySession m =>
Lens' SessionState a -> (a -> a) -> m ()
modifySession Lens' SessionState a
l a -> a
f = Lens' SessionState a -> (a -> ((), a)) -> m ()
forall (m :: * -> *) a r.
ModifySession m =>
Lens' SessionState a -> (a -> (r, a)) -> m r
stateSessionLens (a -> f a) -> SessionState -> f SessionState
Lens' SessionState a
l ((a -> ((), a)) -> m ()) -> (a -> ((), a)) -> m ()
forall a b. (a -> b) -> a -> b
$ a -> ((), a)
forall a. a -> ((), a)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (a -> ((), a)) -> (a -> a) -> a -> ((), a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> a
f

{-# INLINE setSession #-}
-- | Like 'modifySession', but with a constant new value.
--
-- If the computation of the new value depends on a previous
-- 'useSession', this function is prone to suffering from time-of-check
-- vs. time-of-use issues. Prefer the 'stateSessionLensM' family of
-- functions instead.
setSession :: ModifySession m => Lens' SessionState a -> a -> m ()
setSession :: forall (m :: * -> *) a.
ModifySession m =>
Lens' SessionState a -> a -> m ()
setSession Lens' SessionState a
l a
v = Lens' SessionState a -> (a -> a) -> m ()
forall (m :: * -> *) a.
ModifySession m =>
Lens' SessionState a -> (a -> a) -> m ()
modifySession (a -> f a) -> SessionState -> f SessionState
Lens' SessionState a
l (a -> a -> a
forall a b. a -> b -> a
const a
v)

----------------------------------------------------------------------------------------------------
-- ** Monad with capability to block a computation
----------------------------------------------------------------------------------------------------

class Monad m => MonadBlock m where

  -- | `patternViolation b` aborts the current computation
  patternViolation :: Blocker -> m a

  default patternViolation :: (MonadTrans t, MonadBlock n, m ~ t n) => Blocker -> m a
  patternViolation = n a -> m a
n a -> t n a
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (n a -> m a) -> (Blocker -> n a) -> Blocker -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blocker -> n a
forall a. Blocker -> n a
forall (m :: * -> *) a. MonadBlock m => Blocker -> m a
patternViolation

  -- | `catchPatternErr handle m` runs m, handling pattern violations
  --    with `handle` (doesn't roll back the state)
  catchPatternErr :: (Blocker -> m a) -> m a -> m a

newtype BlockT m a = BlockT { forall (m :: * -> *) a. BlockT m a -> ExceptT Blocker m a
unBlockT :: ExceptT Blocker m a }
  deriving ( (forall a b. (a -> b) -> BlockT m a -> BlockT m b)
-> (forall a b. a -> BlockT m b -> BlockT m a)
-> Functor (BlockT m)
forall a b. a -> BlockT m b -> BlockT m a
forall a b. (a -> b) -> BlockT m a -> BlockT m b
forall (m :: * -> *) a b.
Functor m =>
a -> BlockT m b -> BlockT m a
forall (m :: * -> *) a b.
Functor m =>
(a -> b) -> BlockT m a -> BlockT m b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall (m :: * -> *) a b.
Functor m =>
(a -> b) -> BlockT m a -> BlockT m b
fmap :: forall a b. (a -> b) -> BlockT m a -> BlockT m b
$c<$ :: forall (m :: * -> *) a b.
Functor m =>
a -> BlockT m b -> BlockT m a
<$ :: forall a b. a -> BlockT m b -> BlockT m a
Functor, Functor (BlockT m)
Functor (BlockT m) =>
(forall a. a -> BlockT m a)
-> (forall a b. BlockT m (a -> b) -> BlockT m a -> BlockT m b)
-> (forall a b c.
    (a -> b -> c) -> BlockT m a -> BlockT m b -> BlockT m c)
-> (forall a b. BlockT m a -> BlockT m b -> BlockT m b)
-> (forall a b. BlockT m a -> BlockT m b -> BlockT m a)
-> Applicative (BlockT m)
forall a. a -> BlockT m a
forall a b. BlockT m a -> BlockT m b -> BlockT m a
forall a b. BlockT m a -> BlockT m b -> BlockT m b
forall a b. BlockT m (a -> b) -> BlockT m a -> BlockT m b
forall a b c.
(a -> b -> c) -> BlockT m a -> BlockT m b -> BlockT m c
forall (m :: * -> *). Monad m => Functor (BlockT m)
forall (m :: * -> *) a. Monad m => a -> BlockT m a
forall (m :: * -> *) a b.
Monad m =>
BlockT m a -> BlockT m b -> BlockT m a
forall (m :: * -> *) a b.
Monad m =>
BlockT m a -> BlockT m b -> BlockT m b
forall (m :: * -> *) a b.
Monad m =>
BlockT m (a -> b) -> BlockT m a -> BlockT m b
forall (m :: * -> *) a b c.
Monad m =>
(a -> b -> c) -> BlockT m a -> BlockT m b -> BlockT m c
forall (f :: * -> *).
Functor f =>
(forall a. a -> f a)
-> (forall a b. f (a -> b) -> f a -> f b)
-> (forall a b c. (a -> b -> c) -> f a -> f b -> f c)
-> (forall a b. f a -> f b -> f b)
-> (forall a b. f a -> f b -> f a)
-> Applicative f
$cpure :: forall (m :: * -> *) a. Monad m => a -> BlockT m a
pure :: forall a. a -> BlockT m a
$c<*> :: forall (m :: * -> *) a b.
Monad m =>
BlockT m (a -> b) -> BlockT m a -> BlockT m b
<*> :: forall a b. BlockT m (a -> b) -> BlockT m a -> BlockT m b
$cliftA2 :: forall (m :: * -> *) a b c.
Monad m =>
(a -> b -> c) -> BlockT m a -> BlockT m b -> BlockT m c
liftA2 :: forall a b c.
(a -> b -> c) -> BlockT m a -> BlockT m b -> BlockT m c
$c*> :: forall (m :: * -> *) a b.
Monad m =>
BlockT m a -> BlockT m b -> BlockT m b
*> :: forall a b. BlockT m a -> BlockT m b -> BlockT m b
$c<* :: forall (m :: * -> *) a b.
Monad m =>
BlockT m a -> BlockT m b -> BlockT m a
<* :: forall a b. BlockT m a -> BlockT m b -> BlockT m a
Applicative, Applicative (BlockT m)
Applicative (BlockT m) =>
(forall a b. BlockT m a -> (a -> BlockT m b) -> BlockT m b)
-> (forall a b. BlockT m a -> BlockT m b -> BlockT m b)
-> (forall a. a -> BlockT m a)
-> Monad (BlockT m)
forall a. a -> BlockT m a
forall a b. BlockT m a -> BlockT m b -> BlockT m b
forall a b. BlockT m a -> (a -> BlockT m b) -> BlockT m b
forall (m :: * -> *). Monad m => Applicative (BlockT m)
forall (m :: * -> *) a. Monad m => a -> BlockT m a
forall (m :: * -> *) a b.
Monad m =>
BlockT m a -> BlockT m b -> BlockT m b
forall (m :: * -> *) a b.
Monad m =>
BlockT m a -> (a -> BlockT m b) -> BlockT m b
forall (m :: * -> *).
Applicative m =>
(forall a b. m a -> (a -> m b) -> m b)
-> (forall a b. m a -> m b -> m b)
-> (forall a. a -> m a)
-> Monad m
$c>>= :: forall (m :: * -> *) a b.
Monad m =>
BlockT m a -> (a -> BlockT m b) -> BlockT m b
>>= :: forall a b. BlockT m a -> (a -> BlockT m b) -> BlockT m b
$c>> :: forall (m :: * -> *) a b.
Monad m =>
BlockT m a -> BlockT m b -> BlockT m b
>> :: forall a b. BlockT m a -> BlockT m b -> BlockT m b
$creturn :: forall (m :: * -> *) a. Monad m => a -> BlockT m a
return :: forall a. a -> BlockT m a
Monad, (forall (m :: * -> *). Monad m => Monad (BlockT m)) =>
(forall (m :: * -> *) a. Monad m => m a -> BlockT m a)
-> MonadTrans BlockT
forall (m :: * -> *). Monad m => Monad (BlockT m)
forall (m :: * -> *) a. Monad m => m a -> BlockT m a
forall (t :: (* -> *) -> * -> *).
(forall (m :: * -> *). Monad m => Monad (t m)) =>
(forall (m :: * -> *) a. Monad m => m a -> t m a) -> MonadTrans t
$clift :: forall (m :: * -> *) a. Monad m => m a -> BlockT m a
lift :: forall (m :: * -> *) a. Monad m => m a -> BlockT m a
MonadTrans -- , MonadTransControl -- requires GHC >= 8.2
           , Monad (BlockT m)
Monad (BlockT m) =>
(forall a. IO a -> BlockT m a) -> MonadIO (BlockT m)
forall a. IO a -> BlockT m a
forall (m :: * -> *).
Monad m =>
(forall a. IO a -> m a) -> MonadIO m
forall (m :: * -> *). MonadIO m => Monad (BlockT m)
forall (m :: * -> *) a. MonadIO m => IO a -> BlockT m a
$cliftIO :: forall (m :: * -> *) a. MonadIO m => IO a -> BlockT m a
liftIO :: forall a. IO a -> BlockT m a
MonadIO, Monad (BlockT m)
Monad (BlockT m) =>
(forall a. String -> BlockT m a) -> MonadFail (BlockT m)
forall a. String -> BlockT m a
forall (m :: * -> *).
Monad m =>
(forall a. String -> m a) -> MonadFail m
forall (m :: * -> *). MonadFail m => Monad (BlockT m)
forall (m :: * -> *) a. MonadFail m => String -> BlockT m a
$cfail :: forall (m :: * -> *) a. MonadFail m => String -> BlockT m a
fail :: forall a. String -> BlockT m a
MonadFail
           , Monad (BlockT m)
BlockT m SessionState
BlockT m TCState
Monad (BlockT m) =>
BlockT m TCState
-> (forall a b.
    Lens' TCState a -> (a -> a) -> BlockT m b -> BlockT m b)
-> BlockT m SessionState
-> (forall a. (TCState -> TCState) -> BlockT m a -> BlockT m a)
-> ReadTCState (BlockT m)
forall a. (TCState -> TCState) -> BlockT m a -> BlockT m a
forall a b. Lens' TCState a -> (a -> a) -> BlockT m b -> BlockT m b
forall (m :: * -> *).
Monad m =>
m TCState
-> (forall a b. Lens' TCState a -> (a -> a) -> m b -> m b)
-> m SessionState
-> (forall a. (TCState -> TCState) -> m a -> m a)
-> ReadTCState m
forall (m :: * -> *). ReadTCState m => Monad (BlockT m)
forall (m :: * -> *). ReadTCState m => BlockT m SessionState
forall (m :: * -> *). ReadTCState m => BlockT m TCState
forall (m :: * -> *) a.
ReadTCState m =>
(TCState -> TCState) -> BlockT m a -> BlockT m a
forall (m :: * -> *) a b.
ReadTCState m =>
Lens' TCState a -> (a -> a) -> BlockT m b -> BlockT m b
$cgetTCState :: forall (m :: * -> *). ReadTCState m => BlockT m TCState
getTCState :: BlockT m TCState
$clocallyTCState :: forall (m :: * -> *) a b.
ReadTCState m =>
Lens' TCState a -> (a -> a) -> BlockT m b -> BlockT m b
locallyTCState :: forall a b. Lens' TCState a -> (a -> a) -> BlockT m b -> BlockT m b
$cgetSessionState :: forall (m :: * -> *). ReadTCState m => BlockT m SessionState
getSessionState :: BlockT m SessionState
$cwithTCState :: forall (m :: * -> *) a.
ReadTCState m =>
(TCState -> TCState) -> BlockT m a -> BlockT m a
withTCState :: forall a. (TCState -> TCState) -> BlockT m a -> BlockT m a
ReadTCState, Monad (BlockT m)
Functor (BlockT m)
Applicative (BlockT m)
BlockT m CommandLineOptions
BlockT m PragmaOptions
(Functor (BlockT m), Applicative (BlockT m), Monad (BlockT m)) =>
BlockT m PragmaOptions
-> BlockT m CommandLineOptions -> HasOptions (BlockT m)
forall (m :: * -> *).
(Functor m, Applicative m, Monad m) =>
m PragmaOptions -> m CommandLineOptions -> HasOptions m
forall (m :: * -> *). HasOptions m => Monad (BlockT m)
forall (m :: * -> *). HasOptions m => Functor (BlockT m)
forall (m :: * -> *). HasOptions m => Applicative (BlockT m)
forall (m :: * -> *). HasOptions m => BlockT m CommandLineOptions
forall (m :: * -> *). HasOptions m => BlockT m PragmaOptions
$cpragmaOptions :: forall (m :: * -> *). HasOptions m => BlockT m PragmaOptions
pragmaOptions :: BlockT m PragmaOptions
$ccommandLineOptions :: forall (m :: * -> *). HasOptions m => BlockT m CommandLineOptions
commandLineOptions :: BlockT m CommandLineOptions
HasOptions
           , Monad (BlockT m)
BlockT m TCEnv
Monad (BlockT m) =>
BlockT m TCEnv
-> (forall a. (TCEnv -> TCEnv) -> BlockT m a -> BlockT m a)
-> MonadTCEnv (BlockT m)
forall a. (TCEnv -> TCEnv) -> BlockT m a -> BlockT m a
forall (m :: * -> *).
Monad m =>
m TCEnv
-> (forall a. (TCEnv -> TCEnv) -> m a -> m a) -> MonadTCEnv m
forall (m :: * -> *). MonadTCEnv m => Monad (BlockT m)
forall (m :: * -> *). MonadTCEnv m => BlockT m TCEnv
forall (m :: * -> *) a.
MonadTCEnv m =>
(TCEnv -> TCEnv) -> BlockT m a -> BlockT m a
$caskTC :: forall (m :: * -> *). MonadTCEnv m => BlockT m TCEnv
askTC :: BlockT m TCEnv
$clocalTC :: forall (m :: * -> *) a.
MonadTCEnv m =>
(TCEnv -> TCEnv) -> BlockT m a -> BlockT m a
localTC :: forall a. (TCEnv -> TCEnv) -> BlockT m a -> BlockT m a
MonadTCEnv, Monad (BlockT m)
BlockT m TCState
Monad (BlockT m) =>
BlockT m TCState
-> (TCState -> BlockT m ())
-> ((TCState -> TCState) -> BlockT m ())
-> MonadTCState (BlockT m)
TCState -> BlockT m ()
(TCState -> TCState) -> BlockT m ()
forall (m :: * -> *).
Monad m =>
m TCState
-> (TCState -> m ())
-> ((TCState -> TCState) -> m ())
-> MonadTCState m
forall (m :: * -> *). MonadTCState m => Monad (BlockT m)
forall (m :: * -> *). MonadTCState m => BlockT m TCState
forall (m :: * -> *). MonadTCState m => TCState -> BlockT m ()
forall (m :: * -> *).
MonadTCState m =>
(TCState -> TCState) -> BlockT m ()
$cgetTC :: forall (m :: * -> *). MonadTCState m => BlockT m TCState
getTC :: BlockT m TCState
$cputTC :: forall (m :: * -> *). MonadTCState m => TCState -> BlockT m ()
putTC :: TCState -> BlockT m ()
$cmodifyTC :: forall (m :: * -> *).
MonadTCState m =>
(TCState -> TCState) -> BlockT m ()
modifyTC :: (TCState -> TCState) -> BlockT m ()
MonadTCState, Applicative (BlockT m)
MonadIO (BlockT m)
HasOptions (BlockT m)
MonadTCEnv (BlockT m)
MonadTCState (BlockT m)
(Applicative (BlockT m), MonadIO (BlockT m), MonadTCEnv (BlockT m),
 MonadTCState (BlockT m), HasOptions (BlockT m)) =>
(forall a. TCM a -> BlockT m a) -> MonadTCM (BlockT m)
forall a. TCM a -> BlockT m a
forall (tcm :: * -> *).
(Applicative tcm, MonadIO tcm, MonadTCEnv tcm, MonadTCState tcm,
 HasOptions tcm) =>
(forall a. TCM a -> tcm a) -> MonadTCM tcm
forall (m :: * -> *). MonadTCM m => Applicative (BlockT m)
forall (m :: * -> *). MonadTCM m => MonadIO (BlockT m)
forall (m :: * -> *). MonadTCM m => HasOptions (BlockT m)
forall (m :: * -> *). MonadTCM m => MonadTCEnv (BlockT m)
forall (m :: * -> *). MonadTCM m => MonadTCState (BlockT m)
forall (m :: * -> *) a. MonadTCM m => TCM a -> BlockT m a
$cliftTCM :: forall (m :: * -> *) a. MonadTCM m => TCM a -> BlockT m a
liftTCM :: forall a. TCM a -> BlockT m a
MonadTCM
           )

instance Monad m => MonadBlock (BlockT m) where
  patternViolation :: forall a. Blocker -> BlockT m a
patternViolation = ExceptT Blocker m a -> BlockT m a
forall (m :: * -> *) a. ExceptT Blocker m a -> BlockT m a
BlockT (ExceptT Blocker m a -> BlockT m a)
-> (Blocker -> ExceptT Blocker m a) -> Blocker -> BlockT m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blocker -> ExceptT Blocker m a
forall a. Blocker -> ExceptT Blocker m a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError
  catchPatternErr :: forall a. (Blocker -> BlockT m a) -> BlockT m a -> BlockT m a
catchPatternErr Blocker -> BlockT m a
h BlockT m a
f = ExceptT Blocker m a -> BlockT m a
forall (m :: * -> *) a. ExceptT Blocker m a -> BlockT m a
BlockT (ExceptT Blocker m a -> BlockT m a)
-> ExceptT Blocker m a -> BlockT m a
forall a b. (a -> b) -> a -> b
$ ExceptT Blocker m a
-> (Blocker -> ExceptT Blocker m a) -> ExceptT Blocker m a
forall a.
ExceptT Blocker m a
-> (Blocker -> ExceptT Blocker m a) -> ExceptT Blocker m a
forall e (m :: * -> *) a.
MonadError e m =>
m a -> (e -> m a) -> m a
catchError (BlockT m a -> ExceptT Blocker m a
forall (m :: * -> *) a. BlockT m a -> ExceptT Blocker m a
unBlockT BlockT m a
f) (BlockT m a -> ExceptT Blocker m a
forall (m :: * -> *) a. BlockT m a -> ExceptT Blocker m a
unBlockT (BlockT m a -> ExceptT Blocker m a)
-> (Blocker -> BlockT m a) -> Blocker -> ExceptT Blocker m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blocker -> BlockT m a
h)

instance Monad m => MonadBlock (ExceptT TCErr m) where
  patternViolation :: forall a. Blocker -> ExceptT TCErr m a
patternViolation = TCErr -> ExceptT TCErr m a
forall a. TCErr -> ExceptT TCErr m a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (TCErr -> ExceptT TCErr m a)
-> (Blocker -> TCErr) -> Blocker -> ExceptT TCErr m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blocker -> TCErr
PatternErr
  catchPatternErr :: forall a.
(Blocker -> ExceptT TCErr m a)
-> ExceptT TCErr m a -> ExceptT TCErr m a
catchPatternErr Blocker -> ExceptT TCErr m a
h ExceptT TCErr m a
f = ExceptT TCErr m a
-> (TCErr -> ExceptT TCErr m a) -> ExceptT TCErr m a
forall a.
ExceptT TCErr m a
-> (TCErr -> ExceptT TCErr m a) -> ExceptT TCErr m a
forall e (m :: * -> *) a.
MonadError e m =>
m a -> (e -> m a) -> m a
catchError ExceptT TCErr m a
f ((TCErr -> ExceptT TCErr m a) -> ExceptT TCErr m a)
-> (TCErr -> ExceptT TCErr m a) -> ExceptT TCErr m a
forall a b. (a -> b) -> a -> b
$ \case
    PatternErr Blocker
b -> Blocker -> ExceptT TCErr m a
h Blocker
b
    TCErr
err          -> TCErr -> ExceptT TCErr m a
forall a. TCErr -> ExceptT TCErr m a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError TCErr
err

runBlocked :: BlockT m a -> m (Either Blocker a)
runBlocked :: forall (m :: * -> *) a. BlockT m a -> m (Either Blocker a)
runBlocked = ExceptT Blocker m a -> m (Either Blocker a)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT Blocker m a -> m (Either Blocker a))
-> (BlockT m a -> ExceptT Blocker m a)
-> BlockT m a
-> m (Either Blocker a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BlockT m a -> ExceptT Blocker m a
forall (m :: * -> *) a. BlockT m a -> ExceptT Blocker m a
unBlockT
{-# INLINE runBlocked #-}

instance MonadBlock m => MonadBlock (MaybeT m) where
  catchPatternErr :: forall a. (Blocker -> MaybeT m a) -> MaybeT m a -> MaybeT m a
catchPatternErr Blocker -> MaybeT m a
h MaybeT m a
m = m (Maybe a) -> MaybeT m a
forall (m :: * -> *) a. m (Maybe a) -> MaybeT m a
MaybeT (m (Maybe a) -> MaybeT m a) -> m (Maybe a) -> MaybeT m a
forall a b. (a -> b) -> a -> b
$ (Blocker -> m (Maybe a)) -> m (Maybe a) -> m (Maybe a)
forall a. (Blocker -> m a) -> m a -> m a
forall (m :: * -> *) a.
MonadBlock m =>
(Blocker -> m a) -> m a -> m a
catchPatternErr (MaybeT m a -> m (Maybe a)
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (MaybeT m a -> m (Maybe a))
-> (Blocker -> MaybeT m a) -> Blocker -> m (Maybe a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blocker -> MaybeT m a
h) (m (Maybe a) -> m (Maybe a)) -> m (Maybe a) -> m (Maybe a)
forall a b. (a -> b) -> a -> b
$ MaybeT m a -> m (Maybe a)
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT MaybeT m a
m

instance MonadBlock m => MonadBlock (ReaderT e m) where
  catchPatternErr :: forall a.
(Blocker -> ReaderT e m a) -> ReaderT e m a -> ReaderT e m a
catchPatternErr Blocker -> ReaderT e m a
h ReaderT e m a
m = (e -> m a) -> ReaderT e m a
forall r (m :: * -> *) a. (r -> m a) -> ReaderT r m a
ReaderT ((e -> m a) -> ReaderT e m a) -> (e -> m a) -> ReaderT e m a
forall a b. (a -> b) -> a -> b
$ \ e
e ->
    let run :: ReaderT e m a -> m a
run = (ReaderT e m a -> e -> m a) -> e -> ReaderT e m a -> m a
forall a b c. (a -> b -> c) -> b -> a -> c
flip ReaderT e m a -> e -> m a
forall r (m :: * -> *) a. ReaderT r m a -> r -> m a
runReaderT e
e in (Blocker -> m a) -> m a -> m a
forall a. (Blocker -> m a) -> m a -> m a
forall (m :: * -> *) a.
MonadBlock m =>
(Blocker -> m a) -> m a -> m a
catchPatternErr (ReaderT e m a -> m a
run (ReaderT e m a -> m a)
-> (Blocker -> ReaderT e m a) -> Blocker -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blocker -> ReaderT e m a
h) (ReaderT e m a -> m a
run ReaderT e m a
m)

instance MonadBlock m => MonadBlock (Strict.ReaderT e m) where
  catchPatternErr :: forall a.
(Blocker -> ReaderT e m a) -> ReaderT e m a -> ReaderT e m a
catchPatternErr Blocker -> ReaderT e m a
h ReaderT e m a
m = (e -> m a) -> ReaderT e m a
forall r (m :: * -> *) a. (r -> m a) -> ReaderT r m a
Strict.ReaderT ((e -> m a) -> ReaderT e m a) -> (e -> m a) -> ReaderT e m a
forall a b. (a -> b) -> a -> b
$ \ e
e ->
    let run :: ReaderT e m a -> m a
run = (ReaderT e m a -> e -> m a) -> e -> ReaderT e m a -> m a
forall a b c. (a -> b -> c) -> b -> a -> c
flip ReaderT e m a -> e -> m a
forall r (m :: * -> *) a. ReaderT r m a -> r -> m a
Strict.runReaderT e
e in (Blocker -> m a) -> m a -> m a
forall a. (Blocker -> m a) -> m a -> m a
forall (m :: * -> *) a.
MonadBlock m =>
(Blocker -> m a) -> m a -> m a
catchPatternErr (ReaderT e m a -> m a
run (ReaderT e m a -> m a)
-> (Blocker -> ReaderT e m a) -> Blocker -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Blocker -> ReaderT e m a
h) (ReaderT e m a -> m a
run ReaderT e m a
m)

instance MonadFileId m => MonadFileId (BlockT m)

----------------------------------------------------------------------------------------------------
-- * Type checking monad transformer
----------------------------------------------------------------------------------------------------

-- | The type checking monad transformer.
-- Adds readonly 'TCEnv' and mutable 'TCState'.
newtype TCMT m a = TCM# { forall (m :: * -> *) a.
TCMT m a -> MutVar# RealWorld TCState -> TCEnv -> m a
unTCM# :: MutVar# RealWorld TCState -> TCEnv -> m a }

pattern TCM :: (Strict.IORef TCState -> TCEnv -> m a) -> TCMT m a
pattern $bTCM :: forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
$mTCM :: forall {r} {m :: * -> *} {a}.
TCMT m a
-> ((IORef TCState -> TCEnv -> m a) -> r) -> ((# #) -> r) -> r
TCM f <- TCM# ((\MutVar# RealWorld TCState -> TCEnv -> m a
f (Strict.StrictIORef (IORef (STRef MutVar# RealWorld TCState
r))) TCEnv
e -> MutVar# RealWorld TCState -> TCEnv -> m a
f MutVar# RealWorld TCState
r TCEnv
e) -> f) where
  TCM IORef TCState -> TCEnv -> m a
f = (MutVar# RealWorld TCState -> TCEnv -> m a) -> TCMT m a
forall (m :: * -> *) a.
(MutVar# RealWorld TCState -> TCEnv -> m a) -> TCMT m a
TCM# ((MutVar# RealWorld TCState -> TCEnv -> m a)
-> MutVar# RealWorld TCState -> TCEnv -> m a
forall a b. (a -> b) -> a -> b
oneShot \MutVar# RealWorld TCState
s -> (TCEnv -> m a) -> TCEnv -> m a
forall a b. (a -> b) -> a -> b
oneShot \ !TCEnv
e -> IORef TCState -> TCEnv -> m a
f (IORef TCState -> IORef TCState
forall a. IORef a -> IORef a
Strict.StrictIORef (STRef RealWorld TCState -> IORef TCState
forall a. STRef RealWorld a -> IORef a
IORef (MutVar# RealWorld TCState -> STRef RealWorld TCState
forall s a. MutVar# s a -> STRef s a
STRef MutVar# RealWorld TCState
s))) TCEnv
e)
{-# INLINE TCM #-}
{-# COMPLETE TCM #-}

{-# INLINE unTCM #-}
unTCM :: TCMT m a -> Strict.IORef TCState -> TCEnv -> m a
unTCM :: forall (m :: * -> *) a. TCMT m a -> IORef TCState -> TCEnv -> m a
unTCM (TCM IORef TCState -> TCEnv -> m a
f) = IORef TCState -> TCEnv -> m a
f

-- | Type checking monad.
type TCM = TCMT IO

instance ExpandCase LiftedRep (TCM a) where
  type Result LiftedRep (TCM a) = IO a
  {-# INLINE expand #-}
  expand :: ((TCM a -> Result LiftedRep (TCM a)) -> Result LiftedRep (TCM a))
-> TCM a
expand (TCM a -> Result LiftedRep (TCM a)) -> Result LiftedRep (TCM a)
k = (MutVar# RealWorld TCState -> TCEnv -> IO a) -> TCM a
forall (m :: * -> *) a.
(MutVar# RealWorld TCState -> TCEnv -> m a) -> TCMT m a
TCM# ((MutVar# RealWorld TCState -> TCEnv -> IO a)
-> MutVar# RealWorld TCState -> TCEnv -> IO a
forall a b. (a -> b) -> a -> b
oneShot \MutVar# RealWorld TCState
s -> (TCEnv -> IO a) -> TCEnv -> IO a
forall a b. (a -> b) -> a -> b
oneShot \ !TCEnv
e -> (TCM a -> Result LiftedRep (TCM a)) -> Result LiftedRep (TCM a)
k ((TCM a -> IO a) -> TCM a -> IO a
forall a b. (a -> b) -> a -> b
oneShot (\(TCM# MutVar# RealWorld TCState -> TCEnv -> IO a
act) -> MutVar# RealWorld TCState -> TCEnv -> IO a
act MutVar# RealWorld TCState
s TCEnv
e)))


-- 9.14 cannot do this specialization with {-# LANGUAGE DeepSubsumption #-}
-- https://gitlab.haskell.org/ghc/ghc/-/issues/26349
-- #if __GLASGOW_HASKELL__ < 914
{-# SPECIALIZE INLINE mapTCMT :: (forall a. IO a -> IO a) -> TCM a -> TCM a #-}
-- #endif
mapTCMT :: (forall a. m a -> n a) -> TCMT m a -> TCMT n a
mapTCMT :: forall (m :: * -> *) (n :: * -> *) a.
(forall a. m a -> n a) -> TCMT m a -> TCMT n a
mapTCMT forall a. m a -> n a
f (TCM IORef TCState -> TCEnv -> m a
m) = (IORef TCState -> TCEnv -> n a) -> TCMT n a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> n a) -> TCMT n a)
-> (IORef TCState -> TCEnv -> n a) -> TCMT n a
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
s TCEnv
e -> m a -> n a
forall a. m a -> n a
f (IORef TCState -> TCEnv -> m a
m IORef TCState
s TCEnv
e)

pureTCM :: MonadIO m => (TCState -> TCEnv -> a) -> TCMT m a
pureTCM :: forall (m :: * -> *) a.
MonadIO m =>
(TCState -> TCEnv -> a) -> TCMT m a
pureTCM TCState -> TCEnv -> a
f = (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m a) -> TCMT m a)
-> (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
r TCEnv
e -> do
  s <- IO TCState -> m TCState
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO TCState -> m TCState) -> IO TCState -> m TCState
forall a b. (a -> b) -> a -> b
$ IORef TCState -> IO TCState
forall a. IORef a -> IO a
Strict.readIORef IORef TCState
r
  return (f s e)
{-# INLINE pureTCM #-}

-- One goal of the definitions and pragmas below is to inline the
-- monad operations as much as possible. This doesn't seem to have a
-- large effect on the performance of the normal executable, but (at
-- least on one machine/configuration) it has a massive effect on the
-- performance of the profiling executable [1], and reduces the time
-- attributed to bind from over 90% to about 25%.
--
-- [1] When compiled with -auto-all and run with -p: roughly 750%
-- faster for one example.

returnTCMT :: Applicative m => a -> TCMT m a
returnTCMT :: forall (m :: * -> *) a. Applicative m => a -> TCMT m a
returnTCMT = \a
x -> (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m a) -> TCMT m a)
-> (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall a b. (a -> b) -> a -> b
$ \IORef TCState
_ TCEnv
_ -> a -> m a
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
x
{-# INLINE returnTCMT #-}

bindTCMT :: Monad m => TCMT m a -> (a -> TCMT m b) -> TCMT m b
bindTCMT :: forall (m :: * -> *) a b.
Monad m =>
TCMT m a -> (a -> TCMT m b) -> TCMT m b
bindTCMT = \(TCM IORef TCState -> TCEnv -> m a
m) a -> TCMT m b
k -> (IORef TCState -> TCEnv -> m b) -> TCMT m b
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m b) -> TCMT m b)
-> (IORef TCState -> TCEnv -> m b) -> TCMT m b
forall a b. (a -> b) -> a -> b
$ \IORef TCState
r TCEnv
e -> IORef TCState -> TCEnv -> m a
m IORef TCState
r TCEnv
e m a -> (a -> m b) -> m b
forall a b. m a -> (a -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \a
x -> TCMT m b -> IORef TCState -> TCEnv -> m b
forall (m :: * -> *) a. TCMT m a -> IORef TCState -> TCEnv -> m a
unTCM (a -> TCMT m b
k a
x) IORef TCState
r TCEnv
e
{-# INLINE bindTCMT #-}

thenTCMT :: Applicative m => TCMT m a -> TCMT m b -> TCMT m b
thenTCMT :: forall (m :: * -> *) a b.
Applicative m =>
TCMT m a -> TCMT m b -> TCMT m b
thenTCMT = \(TCM IORef TCState -> TCEnv -> m a
m1) (TCM IORef TCState -> TCEnv -> m b
m2) -> (IORef TCState -> TCEnv -> m b) -> TCMT m b
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m b) -> TCMT m b)
-> (IORef TCState -> TCEnv -> m b) -> TCMT m b
forall a b. (a -> b) -> a -> b
$ \IORef TCState
r TCEnv
e -> IORef TCState -> TCEnv -> m a
m1 IORef TCState
r TCEnv
e m a -> m b -> m b
forall a b. m a -> m b -> m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> IORef TCState -> TCEnv -> m b
m2 IORef TCState
r TCEnv
e
{-# INLINE thenTCMT #-}

instance Functor m => Functor (TCMT m) where
  fmap :: forall a b. (a -> b) -> TCMT m a -> TCMT m b
fmap = (a -> b) -> TCMT m a -> TCMT m b
forall (m :: * -> *) a b.
Functor m =>
(a -> b) -> TCMT m a -> TCMT m b
fmapTCMT; {-# INLINE fmap #-}

fmapTCMT :: Functor m => (a -> b) -> TCMT m a -> TCMT m b
fmapTCMT :: forall (m :: * -> *) a b.
Functor m =>
(a -> b) -> TCMT m a -> TCMT m b
fmapTCMT = \a -> b
f (TCM IORef TCState -> TCEnv -> m a
m) -> (IORef TCState -> TCEnv -> m b) -> TCMT m b
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m b) -> TCMT m b)
-> (IORef TCState -> TCEnv -> m b) -> TCMT m b
forall a b. (a -> b) -> a -> b
$ \IORef TCState
r TCEnv
e -> (a -> b) -> m a -> m b
forall a b. (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> b
f (IORef TCState -> TCEnv -> m a
m IORef TCState
r TCEnv
e)
{-# INLINE fmapTCMT #-}

instance Applicative m => Applicative (TCMT m) where
  pure :: forall a. a -> TCMT m a
pure  = a -> TCMT m a
forall (m :: * -> *) a. Applicative m => a -> TCMT m a
returnTCMT; {-# INLINE pure #-}
  <*> :: forall a b. TCMT m (a -> b) -> TCMT m a -> TCMT m b
(<*>) = TCMT m (a -> b) -> TCMT m a -> TCMT m b
forall (m :: * -> *) a b.
Applicative m =>
TCMT m (a -> b) -> TCMT m a -> TCMT m b
apTCMT; {-# INLINE (<*>) #-}

apTCMT :: Applicative m => TCMT m (a -> b) -> TCMT m a -> TCMT m b
apTCMT :: forall (m :: * -> *) a b.
Applicative m =>
TCMT m (a -> b) -> TCMT m a -> TCMT m b
apTCMT = \(TCM IORef TCState -> TCEnv -> m (a -> b)
mf) (TCM IORef TCState -> TCEnv -> m a
m) -> (IORef TCState -> TCEnv -> m b) -> TCMT m b
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m b) -> TCMT m b)
-> (IORef TCState -> TCEnv -> m b) -> TCMT m b
forall a b. (a -> b) -> a -> b
$ \IORef TCState
r TCEnv
e -> IORef TCState -> TCEnv -> m (a -> b)
mf IORef TCState
r TCEnv
e m (a -> b) -> m a -> m b
forall a b. m (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> IORef TCState -> TCEnv -> m a
m IORef TCState
r TCEnv
e
{-# INLINE apTCMT #-}

instance MonadTrans TCMT where
    lift :: forall (m :: * -> *) a. Monad m => m a -> TCMT m a
lift m a
m = (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m a) -> TCMT m a)
-> (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall a b. (a -> b) -> a -> b
$ \IORef TCState
_ TCEnv
_ -> m a
m; {-# INLINE lift #-}

-- We want a special monad implementation of fail.
-- Andreas, 2022-02-02, issue #5659:
-- @transformers-0.6@ requires exactly a @Monad@ superclass constraint here
-- if we want @instance MonadTrans TCMT@.
instance Monad m => Monad (TCMT m) where
    return :: forall a. a -> TCMT m a
return = a -> TCMT m a
forall a. a -> TCMT m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure; {-# INLINE return #-}
    >>= :: forall a b. TCMT m a -> (a -> TCMT m b) -> TCMT m b
(>>=)  = TCMT m a -> (a -> TCMT m b) -> TCMT m b
forall (m :: * -> *) a b.
Monad m =>
TCMT m a -> (a -> TCMT m b) -> TCMT m b
bindTCMT; {-# INLINE (>>=) #-}
    >> :: forall a b. TCMT m a -> TCMT m b -> TCMT m b
(>>)   = TCMT m a -> TCMT m b -> TCMT m b
forall a b. TCMT m a -> TCMT m b -> TCMT m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
(*>); {-# INLINE (>>) #-}

instance MonadFail TCM where
  fail :: forall a. String -> TCM a
fail String
s = (CallStack -> TCM a) -> TCM a
forall b. HasCallStack => (CallStack -> b) -> b
withCallerCallStack \CallStack
loc -> TCErr -> TCM a
forall a. TCErr -> TCMT IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (TCErr -> TCM a) -> TCMT IO TCErr -> TCM a
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< CallStack -> TCState -> Closure SomeDiagnostic -> TCErr
TypeError CallStack
loc (TCState -> Closure SomeDiagnostic -> TCErr)
-> TCMT IO TCState -> TCMT IO (Closure SomeDiagnostic -> TCErr)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TCMT IO TCState
forall (m :: * -> *). ReadTCState m => m TCState
getTCState TCMT IO (Closure SomeDiagnostic -> TCErr)
-> TCMT IO (Closure SomeDiagnostic) -> TCMT IO TCErr
forall a b. TCMT IO (a -> b) -> TCMT IO a -> TCMT IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> SomeDiagnostic -> TCMT IO (Closure SomeDiagnostic)
forall (m :: * -> *) a.
(MonadTCEnv m, ReadTCState m) =>
a -> m (Closure a)
buildClosure (String -> SomeDiagnostic
internalErrorDiagnostic String
s)
  {-# INLINE fail #-}

instance MonadIO m => MonadIO (TCMT m) where
  liftIO :: forall a. IO a -> TCMT m a
liftIO IO a
m = (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m a) -> TCMT m a)
-> (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
s TCEnv
env -> do
    IO a -> m a
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO a -> m a) -> IO a -> m a
forall a b. (a -> b) -> a -> b
$ IORef TCState -> Range -> IO a -> IO a
forall {a}. IORef TCState -> Range -> IO a -> IO a
wrap IORef TCState
s (TCEnv
env TCEnv -> Getting Range TCEnv Range -> Range
forall s a. s -> Getting a s a -> a
^. Getting Range TCEnv Range
Lens' TCEnv Range
eRange) (IO a -> IO a) -> IO a -> IO a
forall a b. (a -> b) -> a -> b
$ do
      x <- IO a
m
      x `seq` return x
    where
      wrap :: IORef TCState -> Range -> IO a -> IO a
wrap IORef TCState
s Range
r IO a
m = IO a -> (IOException -> IO a) -> IO a
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
E.catch IO a
m ((IOException -> IO a) -> IO a) -> (IOException -> IO a) -> IO a
forall a b. (a -> b) -> a -> b
$ \ IOException
err -> do
        s <- IORef TCState -> IO TCState
forall a. IORef a -> IO a
Strict.readIORef IORef TCState
s
        E.throwIO $ IOException (Just s) r err

instance MonadIO m => MonadTCEnv (TCMT m) where
  askTC :: TCMT m TCEnv
askTC             = (IORef TCState -> TCEnv -> m TCEnv) -> TCMT m TCEnv
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m TCEnv) -> TCMT m TCEnv)
-> (IORef TCState -> TCEnv -> m TCEnv) -> TCMT m TCEnv
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
_ TCEnv
e -> TCEnv -> m TCEnv
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return TCEnv
e; {-# INLINE askTC #-}
  localTC :: forall a. (TCEnv -> TCEnv) -> TCMT m a -> TCMT m a
localTC TCEnv -> TCEnv
f (TCM IORef TCState -> TCEnv -> m a
m) = (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m a) -> TCMT m a)
-> (IORef TCState -> TCEnv -> m a) -> TCMT m a
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
s TCEnv
e -> IORef TCState -> TCEnv -> m a
m IORef TCState
s (TCEnv -> TCEnv
f TCEnv
e); {-# INLINE localTC #-}

instance MonadIO m => MonadTCState (TCMT m) where
  getTC :: TCMT m TCState
getTC   = (IORef TCState -> TCEnv -> m TCState) -> TCMT m TCState
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m TCState) -> TCMT m TCState)
-> (IORef TCState -> TCEnv -> m TCState) -> TCMT m TCState
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
r TCEnv
_e -> IO TCState -> m TCState
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IORef TCState -> IO TCState
forall a. IORef a -> IO a
Strict.readIORef IORef TCState
r); {-# INLINE getTC #-}
  putTC :: TCState -> TCMT m ()
putTC TCState
s = (IORef TCState -> TCEnv -> m ()) -> TCMT m ()
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> m ()) -> TCMT m ())
-> (IORef TCState -> TCEnv -> m ()) -> TCMT m ()
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
r TCEnv
_e -> IO () -> m ()
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IORef TCState -> TCState -> IO ()
forall a. IORef a -> a -> IO ()
Strict.writeIORef IORef TCState
r TCState
s); {-# INLINE putTC #-}
  modifyTC :: (TCState -> TCState) -> TCMT m ()
modifyTC TCState -> TCState
f = TCState -> TCMT m ()
forall (m :: * -> *). MonadTCState m => TCState -> m ()
putTC (TCState -> TCMT m ())
-> (TCState -> TCState) -> TCState -> TCMT m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TCState -> TCState
f (TCState -> TCMT m ()) -> TCMT m TCState -> TCMT m ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< TCMT m TCState
forall (m :: * -> *). MonadTCState m => m TCState
getTC; {-# INLINE modifyTC #-}

instance MonadIO m => ReadTCState (TCMT m) where
  getTCState :: TCMT m TCState
getTCState = TCMT m TCState
forall (m :: * -> *). MonadTCState m => m TCState
getTC; {-# INLINE getTCState #-}
  locallyTCState :: forall a b. Lens' TCState a -> (a -> a) -> TCMT m b -> TCMT m b
locallyTCState Lens' TCState a
l a -> a
f = TCMT m a -> (a -> TCMT m ()) -> TCMT m b -> TCMT m b
forall (m :: * -> *) a b.
Monad m =>
m a -> (a -> m ()) -> m b -> m b
bracket_ (Getter TCState a -> TCMT m a
forall (m :: * -> *) a. ReadTCState m => Getter TCState a -> m a
useTC (a -> f a) -> TCState -> f TCState
Lens' TCState a
Getter TCState a
l TCMT m a -> TCMT m () -> TCMT m a
forall a b. TCMT m a -> TCMT m b -> TCMT m a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ASetter' TCState a -> (a -> a) -> TCMT m ()
forall (m :: * -> *) a.
MonadTCState m =>
ASetter' TCState a -> (a -> a) -> m ()
modifyingTC ASetter' TCState a
Lens' TCState a
l a -> a
f) (ASetter' TCState a -> a -> TCMT m ()
forall (m :: * -> *) a.
MonadTCState m =>
ASetter' TCState a -> a -> m ()
setTCLens ASetter' TCState a
Lens' TCState a
l); {-# INLINE locallyTCState #-}

  getSessionState :: TCMT m SessionState
getSessionState = do
    mv <- (TCState -> Atomic SessionState) -> TCMT m (Atomic SessionState)
forall (m :: * -> *) a. ReadTCState m => (TCState -> a) -> m a
getsTC (PersistentTCState -> Atomic SessionState
stPersistentSession (PersistentTCState -> Atomic SessionState)
-> (TCState -> PersistentTCState) -> TCState -> Atomic SessionState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TCState -> PersistentTCState
stPersistentState)
    readAtomic mv

instance MonadBlock TCM where
  {-# inline patternViolation #-}
  patternViolation :: forall a. Blocker -> TCM a
patternViolation Blocker
b = TCErr -> TCMT IO a
forall a. TCErr -> TCMT IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Blocker -> TCErr
PatternErr Blocker
b)
  {-# INLINE catchPatternErr #-}
  catchPatternErr :: forall a. (Blocker -> TCM a) -> TCM a -> TCM a
catchPatternErr = \Blocker -> TCM a
handle TCM a
v ->
       TCM a -> (TCErr -> TCM a) -> TCM a
forall a. TCM a -> (TCErr -> TCM a) -> TCM a
catchError_ TCM a
v \case
            -- Not putting s (which should really be the what's already there) makes things go
            -- a lot slower (+20% total time on standard library). How is that possible??
            -- The problem is most likely that there are internal catchErrors which forgets the
            -- state. catchError should preserve the state on pattern violations.
           PatternErr Blocker
u -> Blocker -> TCM a
handle Blocker
u
           TCErr
err -> TCErr -> TCM a
forall a. TCErr -> TCMT IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError TCErr
err

instance MonadError TCErr TCM where
  {-# INLINE throwError #-}
  throwError :: forall a. TCErr -> TCMT IO a
throwError = IO a -> TCMT IO a
forall a. IO a -> TCMT IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO a -> TCMT IO a) -> (TCErr -> IO a) -> TCErr -> TCMT IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TCErr -> IO a
forall e a. (HasCallStack, Exception e) => e -> IO a
E.throwIO
  {-# INLINE catchError #-}
  catchError :: forall a. TCM a -> (TCErr -> TCM a) -> TCM a
catchError TCM a
m TCErr -> TCM a
h = (IORef TCState -> TCEnv -> IO a) -> TCM a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM \IORef TCState
r TCEnv
e -> do  -- now we are in the monad m
    oldState <- IO TCState -> IO TCState
forall a. IO a -> IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO TCState -> IO TCState) -> IO TCState -> IO TCState
forall a b. (a -> b) -> a -> b
$ IORef TCState -> IO TCState
forall a. IORef a -> IO a
Strict.readIORef IORef TCState
r
    unTCM m r e `E.catch` \TCErr
err -> do
      -- Reset the state, but do not forget changes to the persistent
      -- component. Not for pattern violations.
      case TCErr
err of
        PatternErr{} -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        TCErr
_            -> do
          newState <- IORef TCState -> IO TCState
forall a. IORef a -> IO a
Strict.readIORef IORef TCState
r
          Strict.writeIORef r oldState { stPersistentState = stPersistentState newState }
      TCM a -> IORef TCState -> TCEnv -> IO a
forall (m :: * -> *) a. TCMT m a -> IORef TCState -> TCEnv -> m a
unTCM (TCErr -> TCM a
h TCErr
err) IORef TCState
r TCEnv
e

-- | Like 'catchError', but resets the state completely before running the handler.
--   This means it also loses changes to the 'stPersistentState'.
--
--   The intended use is to catch internal errors during debug printing.
--   In debug printing, we are not expecting state changes.
instance CatchImpossible TCM where
  catchImpossibleJust :: forall b a.
(Impossible -> Maybe b) -> TCM a -> (b -> TCM a) -> TCM a
catchImpossibleJust Impossible -> Maybe b
f TCM a
m b -> TCM a
h = (IORef TCState -> TCEnv -> IO a) -> TCM a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM ((IORef TCState -> TCEnv -> IO a) -> TCM a)
-> (IORef TCState -> TCEnv -> IO a) -> TCM a
forall a b. (a -> b) -> a -> b
$ \ IORef TCState
r TCEnv
e -> do
    -- save the state
    s <- IORef TCState -> IO TCState
forall a. IORef a -> IO a
Strict.readIORef IORef TCState
r
    catchImpossibleJust f (unTCM m r e) $ \ b
err -> do
      IORef TCState -> TCState -> IO ()
forall a. IORef a -> a -> IO ()
Strict.writeIORef IORef TCState
r TCState
s
      TCM a -> IORef TCState -> TCEnv -> IO a
forall (m :: * -> *) a. TCMT m a -> IORef TCState -> TCEnv -> m a
unTCM (b -> TCM a
h b
err) IORef TCState
r TCEnv
e

instance MonadIO m => MonadReduce (TCMT m) where
  liftReduce :: forall a. ReduceM a -> TCMT m a
liftReduce = TCM a -> TCMT m a
forall a. TCM a -> TCMT m a
forall (tcm :: * -> *) a. MonadTCM tcm => TCM a -> tcm a
liftTCM (TCM a -> TCMT m a)
-> (ReduceM a -> TCM a) -> ReduceM a -> TCMT m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ReduceM a -> TCM a
forall a. ReduceM a -> TCM a
runReduceM; {-# INLINE liftReduce #-}

instance (IsString a, MonadIO m) => IsString (TCMT m a) where
  fromString :: String -> TCMT m a
fromString String
s = a -> TCMT m a
forall a. a -> TCMT m a
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> a
forall a. IsString a => String -> a
fromString String
s)

-- | Strict (non-shortcut) semigroup.
--
--   Note that there might be a lazy alternative, e.g.,
--   for TCM All we might want 'Mikan.Utils.Monad.and2M' as concatenation,
--   to shortcut conjunction in case we already have 'False'.
--
instance {-# OVERLAPPABLE #-} (MonadIO m, Semigroup a) => Semigroup (TCMT m a) where
  <> :: TCMT m a -> TCMT m a -> TCMT m a
(<>) = (a -> a -> a) -> TCMT m a -> TCMT m a -> TCMT m a
forall a b c. (a -> b -> c) -> TCMT m a -> TCMT m b -> TCMT m c
forall (f :: * -> *) a b c.
Applicative f =>
(a -> b -> c) -> f a -> f b -> f c
liftA2 a -> a -> a
forall a. Semigroup a => a -> a -> a
(<>)

-- | Strict (non-shortcut) monoid.
instance {-# OVERLAPPABLE #-} (MonadIO m, Monoid a) => Monoid (TCMT m a) where
  mempty :: TCMT m a
mempty  = a -> TCMT m a
forall a. a -> TCMT m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
forall a. Monoid a => a
mempty
  mappend :: TCMT m a -> TCMT m a -> TCMT m a
mappend = TCMT m a -> TCMT m a -> TCMT m a
forall a. Semigroup a => a -> a -> a
(<>)
  mconcat :: [TCMT m a] -> TCMT m a
mconcat = [a] -> a
forall a. Monoid a => [a] -> a
mconcat ([a] -> a) -> ([TCMT m a] -> TCMT m [a]) -> [TCMT m a] -> TCMT m a
forall (m :: * -> *) b c a.
Functor m =>
(b -> c) -> (a -> m b) -> a -> m c
<.> [TCMT m a] -> TCMT m [a]
forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
forall (m :: * -> *) a. Monad m => [m a] -> m [a]
sequence

instance {-# OVERLAPPABLE #-} (MonadIO m, Null a) => Null (TCMT m a) where
  empty :: TCMT m a
empty = a -> TCMT m a
forall a. a -> TCMT m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
forall a. Null a => a
empty
  null :: TCMT m a -> Bool
null  = TCMT m a -> Bool
forall a. HasCallStack => a
__IMPOSSIBLE__

{-# INLINE catchError_ #-}
-- | Preserve the state of the failing computation.
catchError_ :: TCM a -> (TCErr -> TCM a) -> TCM a
catchError_ :: forall a. TCM a -> (TCErr -> TCM a) -> TCM a
catchError_ TCM a
m TCErr -> TCM a
h = (IORef TCState -> TCEnv -> IO a) -> TCM a
forall (m :: * -> *) a. (IORef TCState -> TCEnv -> m a) -> TCMT m a
TCM \IORef TCState
r TCEnv
e ->
  TCM a -> IORef TCState -> TCEnv -> IO a
forall (m :: * -> *) a. TCMT m a -> IORef TCState -> TCEnv -> m a
unTCM TCM a
m IORef TCState
r TCEnv
e
  IO a -> (TCErr -> IO a) -> IO a
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`E.catch` \TCErr
err -> TCM a -> IORef TCState -> TCEnv -> IO a
forall (m :: * -> *) a. TCMT m a -> IORef TCState -> TCEnv -> m a
unTCM (TCErr -> TCM a
h TCErr
err) IORef TCState
r TCEnv
e

{-# INLINE finally_ #-}
-- | Execute a finalizer even when an exception is thrown.
--   Does not catch any errors.
--   In case both the regular computation and the finalizer
--   throw an exception, the one of the finalizer is propagated.
finally_ :: TCM a -> TCM b -> TCM a
finally_ :: forall a b. TCM a -> TCM b -> TCM a
finally_ TCM a
m TCM b
f = do
    x <- TCM a
m TCM a -> (TCErr -> TCM a) -> TCM a
forall a. TCM a -> (TCErr -> TCM a) -> TCM a
`catchError_` \ TCErr
err -> TCM b
f TCM b -> TCM a -> TCM a
forall a b. TCMT IO a -> TCMT IO b -> TCMT IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> TCErr -> TCM a
forall a. TCErr -> TCMT IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError TCErr
err
    _ <- f
    return x

-- | Embedding a TCM computation.

class ( Applicative tcm, MonadIO tcm
      , MonadTCEnv tcm
      , MonadTCState tcm
      , HasOptions tcm
      ) => MonadTCM tcm where
    liftTCM :: TCM a -> tcm a

    default liftTCM :: (MonadTCM m, MonadTrans t, tcm ~ t m) => TCM a -> tcm a
    liftTCM = m a -> tcm a
m a -> t m a
forall (m :: * -> *) a. Monad m => m a -> t m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (m a -> tcm a) -> (TCM a -> m a) -> TCM a -> tcm a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TCM a -> m a
forall a. TCM a -> m a
forall (tcm :: * -> *) a. MonadTCM tcm => TCM a -> tcm a
liftTCM
    {-# INLINE liftTCM #-}

{-# RULES "liftTCM/id" liftTCM = id #-}
instance MonadIO m => MonadTCM (TCMT m) where
    liftTCM :: forall a. TCM a -> TCMT m a
liftTCM = (forall a. IO a -> m a) -> TCMT IO a -> TCMT m a
forall (m :: * -> *) (n :: * -> *) a.
(forall a. m a -> n a) -> TCMT m a -> TCMT n a
mapTCMT IO a -> m a
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO
    {-# INLINE liftTCM #-}

instance MonadTCM tcm => MonadTCM (ChangeT tcm)
instance MonadTCM tcm => MonadTCM (ExceptT err tcm)
instance MonadTCM tcm => MonadTCM (IdentityT tcm)
instance MonadTCM tcm => MonadTCM (ListT tcm)
instance MonadTCM tcm => MonadTCM (MaybeT tcm)
instance MonadTCM tcm => MonadTCM (ReaderT r tcm)
instance MonadTCM tcm => MonadTCM (StateT s tcm)
instance (Monoid w, MonadTCM tcm) => MonadTCM (WriterT w tcm)
instance MonadTCM tcm => MonadTCM (Strict.ReaderT r tcm)
instance MonadTCM tcm => MonadTCM (Strict.StateT s tcm)
instance (Monoid w, MonadTCM tcm) => MonadTCM (Strict.WriterT w tcm)

-- | We store benchmark statistics in an IORef.
--   This enables benchmarking pure computation, see
--   "Agda.Benchmarking".
instance MonadBench TCM where
  type BenchPhase TCM = Phase
  getBenchmark :: TCM (Benchmark (BenchPhase (TCMT IO)))
getBenchmark = IO (Benchmark (BenchPhase (TCMT IO)))
-> TCM (Benchmark (BenchPhase (TCMT IO)))
forall a. IO a -> TCMT IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Benchmark (BenchPhase (TCMT IO)))
 -> TCM (Benchmark (BenchPhase (TCMT IO))))
-> IO (Benchmark (BenchPhase (TCMT IO)))
-> TCM (Benchmark (BenchPhase (TCMT IO)))
forall a b. (a -> b) -> a -> b
$ IO (Benchmark (BenchPhase IO))
IO (Benchmark (BenchPhase (TCMT IO)))
forall (m :: * -> *). MonadBench m => m (Benchmark (BenchPhase m))
getBenchmark
  putBenchmark :: Benchmark (BenchPhase (TCMT IO)) -> TCMT IO ()
putBenchmark = IO () -> TCMT IO ()
forall a. IO a -> TCMT IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> TCMT IO ())
-> (Benchmark Phase -> IO ()) -> Benchmark Phase -> TCMT IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Benchmark (BenchPhase IO) -> IO ()
Benchmark Phase -> IO ()
forall (m :: * -> *).
MonadBench m =>
Benchmark (BenchPhase m) -> m ()
putBenchmark
  finally :: forall a b. TCM a -> TCM b -> TCM a
finally = TCM b -> TCM c -> TCM b
forall a b. TCM a -> TCM b -> TCM a
finally_

instance Null (TCM Doc) where
  empty :: TCM Doc
empty = Doc -> TCM Doc
forall a. a -> TCMT IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Doc
forall a. Null a => a
empty
  null :: TCM Doc -> Bool
null = TCM Doc -> Bool
forall a. HasCallStack => a
__IMPOSSIBLE__

-- | Running the type checking monad (most general form).
{-# SPECIALIZE runTCM :: TCEnv -> TCState -> TCM a -> IO (a, TCState) #-}
runTCM :: MonadIO m => TCEnv -> TCState -> TCMT m a -> m (a, TCState)
runTCM :: forall (m :: * -> *) a.
MonadIO m =>
TCEnv -> TCState -> TCMT m a -> m (a, TCState)
runTCM TCEnv
e TCState
s TCMT m a
m = do
  r <- IO (IORef TCState) -> m (IORef TCState)
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (IORef TCState) -> m (IORef TCState))
-> IO (IORef TCState) -> m (IORef TCState)
forall a b. (a -> b) -> a -> b
$ TCState -> IO (IORef TCState)
forall a. a -> IO (IORef a)
Strict.newIORef TCState
s
  a <- unTCM m r e
  s <- liftIO $ Strict.readIORef r
  return (a, s)

-- | Running the type checking monad on toplevel (with initial state).
runTCMTop :: TCM a -> IO (Either TCErr a)
runTCMTop :: forall a. TCM a -> IO (Either TCErr a)
runTCMTop TCM a
m = (a -> Either TCErr a
forall a b. b -> Either a b
Right (a -> Either TCErr a) -> IO a -> IO (Either TCErr a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TCM a -> IO a
forall (m :: * -> *) a. MonadIO m => TCMT m a -> m a
runTCMTop' TCM a
m) IO (Either TCErr a)
-> (TCErr -> IO (Either TCErr a)) -> IO (Either TCErr a)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`E.catch` (Either TCErr a -> IO (Either TCErr a)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either TCErr a -> IO (Either TCErr a))
-> (TCErr -> Either TCErr a) -> TCErr -> IO (Either TCErr a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TCErr -> Either TCErr a
forall a b. a -> Either a b
Left)

runTCMTop' :: MonadIO m => TCMT m a -> m a
runTCMTop' :: forall (m :: * -> *) a. MonadIO m => TCMT m a -> m a
runTCMTop' TCMT m a
m = do
  r <- IO (IORef TCState) -> m (IORef TCState)
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (IORef TCState) -> m (IORef TCState))
-> IO (IORef TCState) -> m (IORef TCState)
forall a b. (a -> b) -> a -> b
$ TCState -> IO (IORef TCState)
forall a. a -> IO (IORef a)
Strict.newIORef (TCState -> IO (IORef TCState)) -> IO TCState -> IO (IORef TCState)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< IO TCState
initStateIO
  unTCM m r initEnv

-- | 'runSafeTCM' runs a safe 'TCM' action (a 'TCM' action which
--   cannot fail, except that it might raise 'IOException's) in the
--   initial environment.

runSafeTCM :: TCM a -> TCState -> IO (a, TCState)
runSafeTCM :: forall a. TCM a -> TCState -> IO (a, TCState)
runSafeTCM TCM a
m TCState
st =
  TCEnv -> TCState -> TCM a -> IO (a, TCState)
forall (m :: * -> *) a.
MonadIO m =>
TCEnv -> TCState -> TCMT m a -> m (a, TCState)
runTCM TCEnv
initEnv TCState
st TCM a
m IO (a, TCState) -> (TCErr -> IO (a, TCState)) -> IO (a, TCState)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`E.catch` \(TCErr
e :: TCErr) -> case TCErr
e of
    IOException Maybe TCState
_ Range
_ IOException
err -> IOException -> IO (a, TCState)
forall e a. (HasCallStack, Exception e) => e -> IO a
E.throwIO IOException
err
    TCErr
_                   -> IO (a, TCState)
forall a. HasCallStack => a
__IMPOSSIBLE__

-- | Runs the computation in a separate thread, with a /copy/ of the
-- 'TCState' of the calling thread.
--
-- Modifications of the 'TCState' performed by the detached computation
-- (e.g. creation of metas) are invisible to the parent thread, and to
-- any of its siblings. They will be "discarded" when the thread
-- finishes.
-- It is thus important to ensure that any results returned out-of-band
-- by the child thread are valid in an arbitrary TC state.
--
-- The detached thread has read-write, synchronised access to the
-- 'SessionState'.

forkTCM :: TCM () -> TCM ()
forkTCM :: TCMT IO () -> TCMT IO ()
forkTCM TCMT IO ()
m = do
  s <- TCMT IO TCState
forall (m :: * -> *). MonadTCState m => m TCState
getTC
  e <- askTC
  liftIO $ void $ forkIO $ void $ runTCM e s m

----------------------------------------------------------------------------------------------------
-- * Interaction Callback
----------------------------------------------------------------------------------------------------

-- | Callback fuction to call when there is a response
--   to give to the interactive frontend.
--
--   Note that the response is given in pieces and incrementally,
--   so the user can have timely response even during long computations.
--
--   Typical 'InteractionOutputCallback' functions:
--
--    * Convert the response into a 'String' representation and
--      print it on standard output
--      (suitable for inter-process communication).
--
--    * Put the response into a mutable variable stored in the
--      closure of the 'InteractionOutputCallback' function.
--      (suitable for intra-process communication).

type InteractionOutputCallback = Response_boot TCErr TCWarning WarningsAndNonFatalErrors -> TCM ()

-- | The default 'InteractionOutputCallback' function prints certain
-- things to stdout (other things generate internal errors).

defaultInteractionOutputCallback :: InteractionOutputCallback
defaultInteractionOutputCallback :: InteractionOutputCallback
defaultInteractionOutputCallback = \case
  Resp_RunningInfo Int
_ DocTree
msg    -> do
    DocTree -> TCMT IO ()
forall (m :: * -> *). (MonadIO m, HasOptions m) => DocTree -> m ()
putDocTreeLn DocTree
msg
    IO () -> TCMT IO ()
forall a. IO a -> TCMT IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> TCMT IO ()) -> IO () -> TCMT IO ()
forall a b. (a -> b) -> a -> b
$ Handle -> IO ()
hFlush Handle
stdout
  Resp_HighlightingInfo {}  -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_Status {}            -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_JumpToError {}       -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_InteractionPoints {} -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_GiveAction {}        -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_MakeCase {}          -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_SolveAll {}          -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_Mimer {}             -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_DisplayInfo {}       -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_ClearRunningInfo {}  -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_ClearHighlighting {} -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_DoneAborting {}      -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__
  Resp_DoneExiting {}       -> TCMT IO ()
forall a. HasCallStack => a
__IMPOSSIBLE__

----------------------------------------------------------------------------------------------------
-- * Names for generated definitions
----------------------------------------------------------------------------------------------------

-- | Base name for patterns in telescopes
patternInTeleName :: ShortText
patternInTeleName :: ShortText
patternInTeleName = ShortText
".patternInTele"

-- | Base name for extended lambda patterns
extendedLambdaName :: ShortText
extendedLambdaName :: ShortText
extendedLambdaName = ShortText
".extendedlambda"

-- | Check whether we have an definition from an extended lambda.
isExtendedLambdaName :: A.QName -> Bool
isExtendedLambdaName :: QName -> Bool
isExtendedLambdaName = (ShortText
extendedLambdaName ShortText -> ShortText -> Bool
`TS.isPrefixOf`) (ShortText -> Bool) -> (QName -> ShortText) -> QName -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Name -> ShortText
A.nameToArgName (Name -> ShortText) -> (QName -> Name) -> QName -> ShortText
forall b c a. (b -> c) -> (a -> b) -> a -> c
. QName -> Name
qnameName

-- | Name of absurdLambda definitions.
absurdLambdaName :: ShortText
absurdLambdaName :: ShortText
absurdLambdaName = ShortText
".absurdlambda"

-- | Check whether we have an definition from an absurd lambda.
isAbsurdLambdaName :: QName -> Bool
isAbsurdLambdaName :: QName -> Bool
isAbsurdLambdaName = (ShortText
absurdLambdaName ShortText -> ShortText -> Bool
forall a. Eq a => a -> a -> Bool
==) (ShortText -> Bool) -> (QName -> ShortText) -> QName -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Name -> ShortText
A.nameToArgName (Name -> ShortText) -> (QName -> Name) -> QName -> ShortText
forall b c a. (b -> c) -> (a -> b) -> a -> c
. QName -> Name
qnameName

-- | Name for telescope (record) of generalized variables.
generalizeRecordName :: ShortText
generalizeRecordName :: ShortText
generalizeRecordName = ShortText
".GeneralizeTel"

-- | Name for the record constructor for the generalized variables.
generalizeConstructorName :: ShortText
generalizeConstructorName :: ShortText
generalizeConstructorName = ShortText
".mkGeneralizeTel"

-- | Base name for generalized variable projections.
generalizedFieldName :: ShortText
generalizedFieldName :: ShortText
generalizedFieldName = ShortText
".generalizedField-"

-- | Check whether we have a generalized variable field.
getGeneralizedFieldName :: A.QName -> Maybe ShortText
getGeneralizedFieldName :: QName -> Maybe ShortText
getGeneralizedFieldName = ShortText -> ShortText -> Maybe ShortText
TS.stripPrefix ShortText
generalizedFieldName (ShortText -> Maybe ShortText)
-> (QName -> ShortText) -> QName -> Maybe ShortText
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Name -> ShortText
A.nameToArgName (Name -> ShortText) -> (QName -> Name) -> QName -> ShortText
forall b c a. (b -> c) -> (a -> b) -> a -> c
. QName -> Name
qnameName

----------------------------------------------------------------------------------------------------
-- * KillRange instances
----------------------------------------------------------------------------------------------------

instance KillRange Signature where
  killRange :: KillRangeT Signature
killRange (Sig Sections
secs Definitions
defs InstanceTable
inst) = (Sections -> Definitions -> InstanceTable -> Signature)
-> Sections -> Definitions -> InstanceTable -> Signature
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Sections -> Definitions -> InstanceTable -> Signature
Sig Sections
secs Definitions
defs InstanceTable
inst

instance KillRange InstanceTable where
  killRange :: InstanceTable -> InstanceTable
killRange (InstanceTable DiscrimTree QName
tree Map QName Int
count) = (DiscrimTree QName -> Map QName Int -> InstanceTable)
-> DiscrimTree QName -> Map QName Int -> InstanceTable
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN DiscrimTree QName -> Map QName Int -> InstanceTable
InstanceTable DiscrimTree QName
tree Map QName Int
count

instance KillRange Sections where
  killRange :: KillRangeT Sections
killRange = (Section -> Section) -> KillRangeT Sections
forall a b. (a -> b) -> Map ModuleName a -> Map ModuleName b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Section -> Section
forall a. KillRange a => KillRangeT a
killRange

instance KillRange Definitions where
  killRange :: KillRangeT Definitions
killRange = (Definition -> Definition) -> KillRangeT Definitions
forall a b. (a -> b) -> HashMap QName a -> HashMap QName b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Definition -> Definition
forall a. KillRange a => KillRangeT a
killRange

instance KillRange Section where
  killRange :: Section -> Section
killRange (Section Telescope
tel) = (Telescope -> Section) -> Telescope -> Section
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Telescope -> Section
Section Telescope
tel

instance KillRange InstanceInfo where
  killRange :: KillRangeT InstanceInfo
  killRange :: KillRangeT InstanceInfo
killRange (InstanceInfo QName
a OverlapMode
b) = (QName -> OverlapMode -> InstanceInfo)
-> QName -> OverlapMode -> InstanceInfo
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN QName -> OverlapMode -> InstanceInfo
InstanceInfo QName
a OverlapMode
b

instance KillRange WithFunInfo where
  killRange :: KillRangeT WithFunInfo
killRange = \case
    WithFunInfo
NotWithFunction -> WithFunInfo
NotWithFunction
    WithFunInfo QName
parent Telescope
delta1 Int
args -> (QName -> Telescope -> Int -> WithFunInfo)
-> QName -> Telescope -> Int -> WithFunInfo
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN QName -> Telescope -> Int -> WithFunInfo
WithFunInfo QName
parent Telescope
delta1 Int
args

instance KillRange Definition where
  killRange :: Definition -> Definition
killRange (Defn ArgInfo
ai QName
name Type
t [Polarity]
pols [Occurrence]
occs [Maybe Name]
gpars [LocalDisplayForm]
displ MutualId
mut CompiledRepresentation
compiled Maybe InstanceInfo
inst Maybe QName
copy Bool
nc Bool
inj Bool
copat Blocked_
blk Bool
hasmetas Defn
def) =
    (ArgInfo
 -> QName
 -> Type
 -> [Polarity]
 -> [Occurrence]
 -> [Maybe Name]
 -> [LocalDisplayForm]
 -> MutualId
 -> CompiledRepresentation
 -> Maybe InstanceInfo
 -> Maybe QName
 -> Bool
 -> Bool
 -> Bool
 -> Blocked_
 -> Bool
 -> Defn
 -> Definition)
-> ArgInfo
-> QName
-> Type
-> [Polarity]
-> [Occurrence]
-> [Maybe Name]
-> [LocalDisplayForm]
-> MutualId
-> CompiledRepresentation
-> Maybe InstanceInfo
-> Maybe QName
-> Bool
-> Bool
-> Bool
-> Blocked_
-> Bool
-> Defn
-> Definition
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN ArgInfo
-> QName
-> Type
-> [Polarity]
-> [Occurrence]
-> [Maybe Name]
-> [LocalDisplayForm]
-> MutualId
-> CompiledRepresentation
-> Maybe InstanceInfo
-> Maybe QName
-> Bool
-> Bool
-> Bool
-> Blocked_
-> Bool
-> Defn
-> Definition
Defn ArgInfo
ai QName
name Type
t [Polarity]
pols [Occurrence]
occs [Maybe Name]
gpars [LocalDisplayForm]
displ MutualId
mut CompiledRepresentation
compiled Maybe InstanceInfo
inst Maybe QName
copy Bool
nc Bool
inj Bool
copat Blocked_
blk Bool
hasmetas Defn
def
    -- TODO clarify: Keep the range in the defName field?

instance KillRange NumGeneralizableArgs where
  killRange :: KillRangeT NumGeneralizableArgs
killRange = KillRangeT NumGeneralizableArgs
forall a. a -> a
id

instance KillRange CompiledRepresentation where
  killRange :: KillRangeT CompiledRepresentation
killRange = KillRangeT CompiledRepresentation
forall a. a -> a
id

instance KillRange EtaEquality where
  killRange :: KillRangeT EtaEquality
killRange = KillRangeT EtaEquality
forall a. a -> a
id

instance KillRange System where
  killRange :: System -> System
killRange (System Telescope
tel [(Face, Term)]
sys) = Telescope -> [(Face, Term)] -> System
System (KillRangeT Telescope
forall a. KillRange a => KillRangeT a
killRange Telescope
tel) (KillRangeT [(Face, Term)]
forall a. KillRange a => KillRangeT a
killRange [(Face, Term)]
sys)

instance KillRange ExtLamInfo where
  killRange :: ExtLamInfo -> ExtLamInfo
killRange (ExtLamInfo ModuleName
m Bool
b Maybe System
sys) = (ModuleName -> Bool -> Maybe System -> ExtLamInfo)
-> ModuleName -> Bool -> Maybe System -> ExtLamInfo
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN ModuleName -> Bool -> Maybe System -> ExtLamInfo
ExtLamInfo ModuleName
m Bool
b Maybe System
sys

instance KillRange FunctionFlag where
  killRange :: FunctionFlag -> FunctionFlag
killRange = FunctionFlag -> FunctionFlag
forall a. a -> a
id

instance KillRange CompKit where
  killRange :: CompKit -> CompKit
killRange = CompKit -> CompKit
forall a. a -> a
id

instance KillRange ProjectionLikenessMissing where
  killRange :: ProjectionLikenessMissing -> ProjectionLikenessMissing
killRange = ProjectionLikenessMissing -> ProjectionLikenessMissing
forall a. a -> a
id

instance KillRange BuiltinSort where
  killRange :: KillRangeT BuiltinSort
killRange = KillRangeT BuiltinSort
forall a. a -> a
id

instance KillRange Defn where
  killRange :: KillRangeT Defn
killRange Defn
def =
    case Defn
def of
      Axiom Bool
a -> Bool -> Defn
Axiom Bool
a
      DataOrRecSig Int
n -> Int -> Defn
DataOrRecSig Int
n
      GeneralizableVar NumGeneralizableArgs
a -> NumGeneralizableArgs -> Defn
GeneralizableVar NumGeneralizableArgs
a
      AbstractDefn{} -> Defn
forall a. HasCallStack => a
__IMPOSSIBLE__ -- only returned by 'getConstInfo'!
      Function [Clause]
a Maybe CompiledClauses
b Maybe SplitTree
c [Clause]
d FunctionInverse
e Maybe [QName]
f Either ProjectionLikenessMissing Projection
g SmallSet FunctionFlag
h Maybe Bool
i Maybe ExtLamInfo
j WithFunInfo
k Maybe QName
l IsOpaque
m ->
        ([Clause]
 -> Maybe CompiledClauses
 -> Maybe SplitTree
 -> [Clause]
 -> FunctionInverse
 -> Maybe [QName]
 -> Either ProjectionLikenessMissing Projection
 -> SmallSet FunctionFlag
 -> Maybe Bool
 -> Maybe ExtLamInfo
 -> WithFunInfo
 -> Maybe QName
 -> IsOpaque
 -> Defn)
-> [Clause]
-> Maybe CompiledClauses
-> Maybe SplitTree
-> [Clause]
-> FunctionInverse
-> Maybe [QName]
-> Either ProjectionLikenessMissing Projection
-> SmallSet FunctionFlag
-> Maybe Bool
-> Maybe ExtLamInfo
-> WithFunInfo
-> Maybe QName
-> IsOpaque
-> Defn
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN [Clause]
-> Maybe CompiledClauses
-> Maybe SplitTree
-> [Clause]
-> FunctionInverse
-> Maybe [QName]
-> Either ProjectionLikenessMissing Projection
-> SmallSet FunctionFlag
-> Maybe Bool
-> Maybe ExtLamInfo
-> WithFunInfo
-> Maybe QName
-> IsOpaque
-> Defn
Function [Clause]
a Maybe CompiledClauses
b Maybe SplitTree
c [Clause]
d FunctionInverse
e Maybe [QName]
f Either ProjectionLikenessMissing Projection
g SmallSet FunctionFlag
h Maybe Bool
i Maybe ExtLamInfo
j WithFunInfo
k Maybe QName
l IsOpaque
m
      Datatype Int
a Int
b Maybe Clause
c [QName]
d Sort
e Maybe [QName]
f PositivityCheck
g IsAbstract
h [QName]
i Maybe QName
j Maybe QName
k -> (Int
 -> Int
 -> Maybe Clause
 -> [QName]
 -> Sort
 -> Maybe [QName]
 -> PositivityCheck
 -> IsAbstract
 -> [QName]
 -> Maybe QName
 -> Maybe QName
 -> Defn)
-> Int
-> Int
-> Maybe Clause
-> [QName]
-> Sort
-> Maybe [QName]
-> PositivityCheck
-> IsAbstract
-> [QName]
-> Maybe QName
-> Maybe QName
-> Defn
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Int
-> Int
-> Maybe Clause
-> [QName]
-> Sort
-> Maybe [QName]
-> PositivityCheck
-> IsAbstract
-> [QName]
-> Maybe QName
-> Maybe QName
-> Defn
Datatype Int
a Int
b Maybe Clause
c [QName]
d Sort
e Maybe [QName]
f PositivityCheck
g IsAbstract
h [QName]
i Maybe QName
j Maybe QName
k
      Record Int
a Maybe Clause
b ConHead
c Bool
d [Dom QName]
e Telescope
f Maybe [QName]
g PositivityCheck
h EtaEquality
i PatternOrCopattern
j Maybe Induction
k Maybe Bool
l IsAbstract
m CompKit
n -> (Int
 -> Maybe Clause
 -> ConHead
 -> Bool
 -> [Dom QName]
 -> Telescope
 -> Maybe [QName]
 -> PositivityCheck
 -> EtaEquality
 -> PatternOrCopattern
 -> Maybe Induction
 -> Maybe Bool
 -> IsAbstract
 -> CompKit
 -> Defn)
-> Int
-> Maybe Clause
-> ConHead
-> Bool
-> [Dom QName]
-> Telescope
-> Maybe [QName]
-> PositivityCheck
-> EtaEquality
-> PatternOrCopattern
-> Maybe Induction
-> Maybe Bool
-> IsAbstract
-> CompKit
-> Defn
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Int
-> Maybe Clause
-> ConHead
-> Bool
-> [Dom QName]
-> Telescope
-> Maybe [QName]
-> PositivityCheck
-> EtaEquality
-> PatternOrCopattern
-> Maybe Induction
-> Maybe Bool
-> IsAbstract
-> CompKit
-> Defn
Record Int
a Maybe Clause
b ConHead
c Bool
d [Dom QName]
e Telescope
f Maybe [QName]
g PositivityCheck
h EtaEquality
i PatternOrCopattern
j Maybe Induction
k Maybe Bool
l IsAbstract
m CompKit
n
      Constructor Int
a Int
b ConHead
c QName
d IsAbstract
e CompKit
f Maybe [QName]
g [IsForced]
h Bool
i  -> (Int
 -> Int
 -> ConHead
 -> QName
 -> IsAbstract
 -> CompKit
 -> Maybe [QName]
 -> [IsForced]
 -> Bool
 -> Defn)
-> Int
-> Int
-> ConHead
-> QName
-> IsAbstract
-> CompKit
-> Maybe [QName]
-> [IsForced]
-> Bool
-> Defn
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Int
-> Int
-> ConHead
-> QName
-> IsAbstract
-> CompKit
-> Maybe [QName]
-> [IsForced]
-> Bool
-> Defn
Constructor Int
a Int
b ConHead
c QName
d IsAbstract
e CompKit
f Maybe [QName]
g [IsForced]
h Bool
i
      Primitive IsAbstract
a PrimitiveId
b [Clause]
c FunctionInverse
d Maybe CompiledClauses
e IsOpaque
f          -> (IsAbstract
 -> PrimitiveId
 -> [Clause]
 -> FunctionInverse
 -> Maybe CompiledClauses
 -> IsOpaque
 -> Defn)
-> IsAbstract
-> PrimitiveId
-> [Clause]
-> FunctionInverse
-> Maybe CompiledClauses
-> IsOpaque
-> Defn
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN IsAbstract
-> PrimitiveId
-> [Clause]
-> FunctionInverse
-> Maybe CompiledClauses
-> IsOpaque
-> Defn
Primitive IsAbstract
a PrimitiveId
b [Clause]
c FunctionInverse
d Maybe CompiledClauses
e IsOpaque
f
      PrimitiveSort BuiltinSort
a Sort
b              -> (BuiltinSort -> Sort -> Defn) -> BuiltinSort -> Sort -> Defn
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN BuiltinSort -> Sort -> Defn
PrimitiveSort BuiltinSort
a Sort
b

instance KillRange MutualId where
  killRange :: MutualId -> MutualId
killRange = MutualId -> MutualId
forall a. a -> a
id

instance KillRange c => KillRange (FunctionInverse' c) where
  killRange :: KillRangeT (FunctionInverse' c)
killRange FunctionInverse' c
NotInjective = FunctionInverse' c
forall c. FunctionInverse' c
NotInjective
  killRange (Inverse InversionMap c
m)  = InversionMap c -> FunctionInverse' c
forall c. InversionMap c -> FunctionInverse' c
Inverse (InversionMap c -> FunctionInverse' c)
-> InversionMap c -> FunctionInverse' c
forall a b. (a -> b) -> a -> b
$ KillRangeT (InversionMap c)
forall k v. (KillRange k, KillRange v) => KillRangeT (Map k v)
killRangeMap InversionMap c
m

instance KillRange TermHead where
  killRange :: TermHead -> TermHead
killRange TermHead
SortHead     = TermHead
SortHead
  killRange TermHead
PiHead       = TermHead
PiHead
  killRange (ConsHead QName
q) = QName -> TermHead
ConsHead (QName -> TermHead) -> QName -> TermHead
forall a b. (a -> b) -> a -> b
$ KillRangeT QName
forall a. KillRange a => KillRangeT a
killRange QName
q
  killRange h :: TermHead
h@VarHead{}  = TermHead
h
  killRange TermHead
UnknownHead  = TermHead
UnknownHead

instance KillRange Projection where
  killRange :: KillRangeT Projection
killRange (Projection Maybe QName
a QName
b Arg QName
c Int
d ProjLams
e) = (Maybe QName
 -> QName -> Arg QName -> Int -> ProjLams -> Projection)
-> Maybe QName
-> QName
-> Arg QName
-> Int
-> ProjLams
-> Projection
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Maybe QName -> QName -> Arg QName -> Int -> ProjLams -> Projection
Projection Maybe QName
a QName
b Arg QName
c Int
d ProjLams
e

instance KillRange ProjLams where
  killRange :: KillRangeT ProjLams
killRange = KillRangeT ProjLams
forall a. a -> a
id

instance KillRange a => KillRange (Open a) where
  killRange :: KillRangeT (Open a)
killRange = (a -> a) -> KillRangeT (Open a)
forall a b. (a -> b) -> Open a -> Open b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> a
forall a. KillRange a => KillRangeT a
killRange

instance KillRange DisplayForm where
  killRange :: KillRangeT DisplayForm
killRange (Display Int
n [Elim]
es DisplayTerm
dt) = (Int -> [Elim] -> DisplayTerm -> DisplayForm)
-> Int -> [Elim] -> DisplayTerm -> DisplayForm
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Int -> [Elim] -> DisplayTerm -> DisplayForm
Display Int
n [Elim]
es DisplayTerm
dt

instance KillRange Polarity where
  killRange :: KillRangeT Polarity
killRange = KillRangeT Polarity
forall a. a -> a
id

instance KillRange IsForced where
  killRange :: KillRangeT IsForced
killRange = KillRangeT IsForced
forall a. a -> a
id

instance KillRange DoGeneralize where
  killRange :: DoGeneralize -> DoGeneralize
killRange = DoGeneralize -> DoGeneralize
forall a. a -> a
id

instance KillRange DisplayTerm where
  killRange :: KillRangeT DisplayTerm
killRange DisplayTerm
dt =
    case DisplayTerm
dt of
      DWithApp DisplayTerm
dt List1 DisplayTerm
dts [Elim]
es -> (DisplayTerm -> List1 DisplayTerm -> [Elim] -> DisplayTerm)
-> DisplayTerm -> List1 DisplayTerm -> [Elim] -> DisplayTerm
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN DisplayTerm -> List1 DisplayTerm -> [Elim] -> DisplayTerm
DWithApp DisplayTerm
dt List1 DisplayTerm
dts [Elim]
es
      DCon ConHead
q ConInfo
ci [Arg DisplayTerm]
dts      -> (ConHead -> ConInfo -> [Arg DisplayTerm] -> DisplayTerm)
-> ConHead -> ConInfo -> [Arg DisplayTerm] -> DisplayTerm
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN ConHead -> ConInfo -> [Arg DisplayTerm] -> DisplayTerm
DCon ConHead
q ConInfo
ci [Arg DisplayTerm]
dts
      DDef QName
q [Elim' DisplayTerm]
dts         -> (QName -> [Elim' DisplayTerm] -> DisplayTerm)
-> QName -> [Elim' DisplayTerm] -> DisplayTerm
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN QName -> [Elim' DisplayTerm] -> DisplayTerm
DDef QName
q [Elim' DisplayTerm]
dts
      DDot' Term
v [Elim]
es         -> (Term -> [Elim] -> DisplayTerm) -> Term -> [Elim] -> DisplayTerm
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Term -> [Elim] -> DisplayTerm
DDot' Term
v [Elim]
es
      DTerm' Term
v [Elim]
es        -> (Term -> [Elim] -> DisplayTerm) -> Term -> [Elim] -> DisplayTerm
forall t (b :: Bool).
(KILLRANGE t b, IsBase t ~ b, All KillRange (Domains t)) =>
t -> t
killRangeN Term -> [Elim] -> DisplayTerm
DTerm' Term
v [Elim]
es

instance KillRange (Closure a) where
  killRange :: KillRangeT (Closure a)
killRange = KillRangeT (Closure a)
forall a. a -> a
id

----------------------------------------------------------------------------------------------------
-- NFData instances
----------------------------------------------------------------------------------------------------

instance NFData NumGeneralizableArgs where
  rnf :: NumGeneralizableArgs -> ()
rnf (SomeGeneralizableArgs Int
_) = ()

instance NFData TCErr where
  rnf :: TCErr -> ()
rnf (TypeError CallStack
a TCState
b Closure SomeDiagnostic
c)   = CallStack -> ()
forall a. NFData a => a -> ()
rnf CallStack
a () -> () -> ()
forall a b. a -> b -> b
`seq` TCState -> ()
forall a. NFData a => a -> ()
rnf TCState
b () -> () -> ()
forall a b. a -> b -> b
`seq` Closure SomeDiagnostic -> ()
forall a. NFData a => a -> ()
rnf Closure SomeDiagnostic
c
  rnf (ParserError ParseError
a)     = ParseError -> ()
forall a. NFData a => a -> ()
rnf ParseError
a
  rnf (GenericException String
a)= String -> ()
forall a. NFData a => a -> ()
rnf String
a
  rnf (IOException Maybe TCState
a Range
b IOException
c) = Maybe TCState -> ()
forall a. NFData a => a -> ()
rnf Maybe TCState
a () -> () -> ()
forall a b. a -> b -> b
`seq` Range -> ()
forall a. NFData a => a -> ()
rnf Range
b () -> () -> ()
forall a b. a -> b -> b
`seq` Bool -> ()
forall a. NFData a => a -> ()
rnf (IOException
c IOException -> IOException -> Bool
forall a. Eq a => a -> a -> Bool
== IOException
c)
                            -- At the time of writing there is no
                            -- NFData instance for E.IOException.
  rnf (PatternErr Blocker
a)      = Blocker -> ()
forall a. NFData a => a -> ()
rnf Blocker
a

-- | This instance could be optimised, some things are guaranteed to
-- be forced.

instance NFData PreScopeState

-- | This instance could be optimised, some things are guaranteed to
-- be forced.

instance NFData PostNamesCheckpoints
instance NFData PostMetaState
instance NFData PostColdState
instance NFData PostScopeState
instance NFData TCState
instance NFData DisambiguatedName
instance NFData MutualBlock
instance NFData OpaqueBlock
instance NFData (BiMap RawTopLevelModuleName ModuleNameHash)
instance NFData PersistentTCState
instance NFData LoadedFileCache
instance NFData TypeCheckAction
instance NFData ModuleCheckMode
instance NFData ModuleInfo
instance NFData ForeignCode
instance NFData Interface
instance NFData a => NFData (Closure a)
instance NFData ProblemConstraint
instance NFData Constraint
instance NFData Signature
instance NFData InstanceTable
instance NFData Comparison
instance NFData CompareAs
instance NFData a => NFData (Open a)
instance NFData a => NFData (Judgement a)
instance NFData DoGeneralize
instance NFData GeneralizedValue
instance NFData MetaVariable
instance NFData Listener
instance NFData MetaInstantiation
instance NFData Instantiation
instance NFData RemoteMetaVariable
instance NFData Frozen
instance NFData PrincipalArgTypeMetas
instance NFData RunMetaOccursCheck
instance NFData MetaInfo
instance NFData InteractionPoint
instance NFData InteractionPoints
instance NFData Overapplied
instance NFData t => NFData (IPBoundary' t)
instance NFData IPClause
instance NFData DisplayForm
instance NFData DisplayTerm
instance NFData InstanceInfo
instance NFData Definition
instance NFData WithFunInfo
instance NFData Polarity
instance NFData IsForced
instance NFData Projection
instance NFData ProjLams
instance NFData CompilerPragma
instance NFData System
instance NFData ExtLamInfo
instance NFData EtaEquality
instance NFData FunctionFlag
instance NFData CompKit
instance NFData AxiomData
instance NFData DataOrRecSigData
instance NFData ProjectionLikenessMissing
instance NFData FunctionData
instance NFData DatatypeData
instance NFData RecordData
instance NFData ConstructorData
instance NFData PrimitiveData
instance NFData PrimitiveSortData
instance NFData Defn
instance NFData Simplification
instance NFData AllowedReduction
instance NFData ReduceDefs
instance NFData c => NFData (FunctionInverse' c)
instance NFData TermHead
instance NFData Call
instance NFData BuiltinSort
instance NFData pf => NFData (Builtin pf)
instance NFData HighlightingLevel
instance NFData HighlightingMethod
instance NFData TCContext
instance NFData ColdEnv
instance NFData TCEnv
instance NFData LetBinding
instance NFData UnquoteFlags
instance NFData AbstractMode
instance NFData ExpandHidden
instance NFData CandidateKind
instance NFData Candidate
instance NFData Warning
instance NFData UnsolvedWarning
instance NFData RecordFieldWarning
instance NFData a => NFData (TCWarning' a)
instance NFData CallInfo
instance NFData TerminationError
instance NFData NegativeUnification
instance NFData TypeError
instance NFData ClashingName
instance NFData InvalidFileNameReason
instance NFData LHSOrPatSyn
instance NFData InductionAndEta
instance NFData MissingTypeSignatureInfo
instance NFData WhyNotAHaskellType
instance NFData IsAmbiguous
instance NFData CannotQuote
instance NFData ConstructorDisambiguationData
instance NFData Statistics
instance NFData UnusedImportsState
instance NFData OpenedModule
instance NFData IsAxiom
instance NFData SessionState
instance NFData ReadFile
instance NFData ReadFileCache
instance NFData UserWarningInfo
instance NFData WithAppHead

instance NFData PrimFun where
  rnf :: PrimFun -> ()
rnf (PrimFun QName
a Int
b [Occurrence]
c Args -> Int -> ReduceM (Reduced MaybeReducedArgs Term)
_fun) =
    QName -> ()
forall a. NFData a => a -> ()
rnf QName
a () -> () -> ()
forall a b. a -> b -> b
`seq` Int -> ()
forall a. NFData a => a -> ()
rnf Int
b () -> () -> ()
forall a b. a -> b -> b
`seq` [Occurrence] -> ()
forall a. NFData a => a -> ()
rnf [Occurrence]
c

instance NFData TypeCheckingProblem where
  rnf :: TypeCheckingProblem -> ()
rnf = \case
    CheckExpr Comparison
a Expr
b Type
c -> (Comparison, Expr, Type) -> ()
forall a. NFData a => a -> ()
rnf (Comparison
a, Expr
b, Type
c)
    CheckArgs Comparison
a ExpandHidden
b Expr
c Args
d Type
e Type
f ArgsCheckState CheckedTarget -> TCM Term
_fun -> (Comparison, ExpandHidden, Expr, Args, Type, Type) -> ()
forall a. NFData a => a -> ()
rnf (Comparison
a, ExpandHidden
b, Expr
c, Args
d, Type
e, Type
f)
    CheckProjAppToKnownPrincipalArg Comparison
a Expr
b ProjOrigin
c AmbiguousQName
d Expr
e Args
f Type
g Int
h Term
i Type
j PrincipalArgTypeMetas
k -> (Comparison, Expr, ProjOrigin, AmbiguousQName, Expr,
 (Args, Type, Int, Term, Type, PrincipalArgTypeMetas))
-> ()
forall a. NFData a => a -> ()
rnf (Comparison
a, Expr
b, ProjOrigin
c, AmbiguousQName
d, Expr
e, (Args
f, Type
g, Int
h, Term
i, Type
j, PrincipalArgTypeMetas
k))
    CheckWithApp Comparison
a Type
b WithAppHead
c QName
d [Elim]
e List1 Expr
f -> (Comparison, Type, WithAppHead, QName, [Elim], List1 Expr) -> ()
forall a. NFData a => a -> ()
rnf (Comparison
a, Type
b, WithAppHead
c, QName
d, [Elim]
e, List1 Expr
f)
    CheckWithAppHead Comparison
a Type
b Expr
c Term
d List1 Expr
e -> (Comparison, Type, Expr, Term, List1 Expr) -> ()
forall a. NFData a => a -> ()
rnf (Comparison
a, Type
b, Expr
c, Term
d, List1 Expr
e)
    DisambiguateConstructor ConstructorDisambiguationData
a ConHead -> TCM Term
_fun -> ConstructorDisambiguationData -> ()
forall a. NFData a => a -> ()
rnf ConstructorDisambiguationData
a
    DoQuoteTerm Comparison
a Term
b Type
c -> (Comparison, Term, Type) -> ()
forall a. NFData a => a -> ()
rnf (Comparison
a, Term
b, Type
c)