1{-# LANGUAGE CPP #-} 2-- {-# LANGUAGE UndecidableInstances #-} -- ghc >= 8.2, GeneralizedNewtypeDeriving MonadTransControl BlockT 3 4module Agda.TypeChecking.Monad.Base 5 ( module Agda.TypeChecking.Monad.Base 6 , HasOptions (..) 7 ) where 8 9import Prelude hiding (null) 10 11import Control.Applicative hiding (empty) 12import qualified Control.Concurrent as C 13import Control.DeepSeq 14import qualified Control.Exception as E 15 16import qualified Control.Monad.Fail as Fail 17 18import Control.Monad.Except 19import Control.Monad.State 20import Control.Monad.Reader 21import Control.Monad.Writer hiding ((<>)) 22import Control.Monad.Trans ( MonadTrans(..), lift ) 23import Control.Monad.Trans.Control ( MonadTransControl(..), liftThrough ) 24import Control.Monad.Trans.Identity 25import Control.Monad.Trans.Maybe 26 27import Control.Parallel ( pseq ) 28 29import Data.Array (Ix) 30import Data.Function 31import Data.Int 32import Data.IntMap (IntMap) 33import qualified Data.IntMap as IntMap 34import qualified Data.List as List 35import Data.Maybe 36import Data.Map (Map) 37import qualified Data.Map as Map -- hiding (singleton, null, empty) 38import Data.Sequence (Seq) 39import Data.Set (Set) 40import qualified Data.Set as Set -- hiding (singleton, null, empty) 41import Data.HashMap.Strict (HashMap) 42import qualified Data.HashMap.Strict as HMap 43import Data.Semigroup ( Semigroup, (<>)) --, Any(..) ) 44import Data.Data (Data) 45import Data.String 46import Data.Text (Text) 47import qualified Data.Text as T 48import qualified Data.Text.Lazy as TL 49 50import Data.IORef 51 52import GHC.Generics (Generic) 53 54import Agda.Benchmarking (Benchmark, Phase) 55 56import Agda.Syntax.Concrete (TopLevelModuleName) 57import Agda.Syntax.Common 58import qualified Agda.Syntax.Concrete as C 59import Agda.Syntax.Concrete.Definitions 60 (NiceDeclaration, DeclarationWarning, dwWarning, declarationWarningName) 61import qualified Agda.Syntax.Abstract as A 62import Agda.Syntax.Internal as I 63import Agda.Syntax.Internal.MetaVars 64import Agda.Syntax.Internal.Generic (TermLike(..)) 65import Agda.Syntax.Parser (ParseWarning) 66import Agda.Syntax.Parser.Monad (parseWarningName) 67import Agda.Syntax.Treeless (Compiled) 68import Agda.Syntax.Notation 69import Agda.Syntax.Position 70import Agda.Syntax.Scope.Base 71import qualified Agda.Syntax.Info as Info 72 73import Agda.TypeChecking.CompiledClause 74import Agda.TypeChecking.Coverage.SplitTree 75import Agda.TypeChecking.Positivity.Occurrence 76import Agda.TypeChecking.Free.Lazy (Free(freeVars'), underBinder', underBinder) 77 78-- Args, defined in Agda.Syntax.Treeless and exported from Agda.Compiler.Backend 79-- conflicts with Args, defined in Agda.Syntax.Internal and also imported here. 80-- This only matters when interpreted in ghci, which sees all of the module's 81-- exported symbols, not just the ones defined in the `.hs-boot`. See the 82-- comment in ../../Compiler/Backend.hs-boot 83import {-# SOURCE #-} Agda.Compiler.Backend hiding (Args) 84 85import Agda.Interaction.Options 86import Agda.Interaction.Options.Warnings 87import {-# SOURCE #-} Agda.Interaction.Response 88 (InteractionOutputCallback, defaultInteractionOutputCallback) 89import Agda.Interaction.Highlighting.Precise 90 (HighlightingInfo, NameKind) 91import Agda.Interaction.Library 92 93import Agda.Utils.Benchmark (MonadBench(..)) 94import Agda.Utils.BiMap (BiMap, HasTag(..)) 95import qualified Agda.Utils.BiMap as BiMap 96import Agda.Utils.CallStack ( CallStack, HasCallStack, withCallerCallStack ) 97import Agda.Utils.FileName 98import Agda.Utils.Functor 99import Agda.Utils.Hash 100import Agda.Utils.Lens 101import Agda.Utils.List 102import Agda.Utils.ListT 103import Agda.Utils.List1 (List1, pattern (:|)) 104import Agda.Utils.List2 (List2, pattern List2) 105import qualified Agda.Utils.List1 as List1 106import qualified Agda.Utils.Maybe.Strict as Strict 107import Agda.Utils.Monad 108import Agda.Utils.Null 109import Agda.Utils.Permutation 110import Agda.Utils.Pretty 111import Agda.Utils.Singleton 112import Agda.Utils.SmallSet (SmallSet) 113import qualified Agda.Utils.SmallSet as SmallSet 114import Agda.Utils.Update 115import Agda.Utils.WithDefault ( collapseDefault ) 116 117import Agda.Utils.Impossible 118 119--------------------------------------------------------------------------- 120-- * Type checking state 121--------------------------------------------------------------------------- 122 123data TCState = TCSt 124 { stPreScopeState :: !PreScopeState 125 -- ^ The state which is frozen after scope checking. 126 , stPostScopeState :: !PostScopeState 127 -- ^ The state which is modified after scope checking. 128 , stPersistentState :: !PersistentTCState 129 -- ^ State which is forever, like a diamond. 130 } 131 deriving Generic 132 133class Monad m => ReadTCState m where 134 getTCState :: m TCState 135 locallyTCState :: Lens' a TCState -> (a -> a) -> m b -> m b 136 137 withTCState :: (TCState -> TCState) -> m a -> m a 138 withTCState = locallyTCState id 139 140 default getTCState :: (MonadTrans t, ReadTCState n, t n ~ m) => m TCState 141 getTCState = lift getTCState 142 143 default locallyTCState 144 :: (MonadTransControl t, ReadTCState n, t n ~ m) 145 => Lens' a TCState -> (a -> a) -> m b -> m b 146 locallyTCState l = liftThrough . locallyTCState l 147 148instance ReadTCState m => ReadTCState (ListT m) where 149 locallyTCState l = mapListT . locallyTCState l 150 151instance ReadTCState m => ReadTCState (ChangeT m) 152instance ReadTCState m => ReadTCState (ExceptT err m) 153instance ReadTCState m => ReadTCState (IdentityT m) 154instance ReadTCState m => ReadTCState (MaybeT m) 155instance ReadTCState m => ReadTCState (ReaderT r m) 156instance ReadTCState m => ReadTCState (StateT s m) 157instance (Monoid w, ReadTCState m) => ReadTCState (WriterT w m) 158 159 160instance Show TCState where 161 show _ = "TCSt{}" 162 163data PreScopeState = PreScopeState 164 { stPreTokens :: !HighlightingInfo 165 -- ^ Highlighting info for tokens and Happy parser warnings (but 166 -- not for those tokens/warnings for which highlighting exists in 167 -- 'stPostSyntaxInfo'). 168 , stPreImports :: !Signature -- XX populated by scope checker 169 -- ^ Imported declared identifiers. 170 -- Those most not be serialized! 171 , stPreImportedModules :: !(Set ModuleName) -- imports logic 172 , stPreModuleToSource :: !ModuleToSource -- imports 173 , stPreVisitedModules :: !VisitedModules -- imports 174 , stPreScope :: !ScopeInfo 175 -- generated by scope checker, current file: 176 -- which modules you have, public definitions, current file, maps concrete names to abstract names. 177 , stPrePatternSyns :: !A.PatternSynDefns 178 -- ^ Pattern synonyms of the current file. Serialized. 179 , stPrePatternSynImports :: !A.PatternSynDefns 180 -- ^ Imported pattern synonyms. Must not be serialized! 181 , stPreGeneralizedVars :: !(Strict.Maybe (Set QName)) 182 -- ^ Collected generalizable variables; used during scope checking of terms 183 , stPrePragmaOptions :: !PragmaOptions 184 -- ^ Options applying to the current file. @OPTIONS@ 185 -- pragmas only affect this field. 186 , stPreImportedBuiltins :: !(BuiltinThings PrimFun) 187 , stPreImportedDisplayForms :: !DisplayForms 188 -- ^ Display forms added by someone else to imported identifiers 189 , stPreImportedInstanceDefs :: !InstanceTable 190 , stPreForeignCode :: !(Map BackendName [ForeignCode]) 191 -- ^ @{-\# FOREIGN \#-}@ code that should be included in the compiled output. 192 -- Does not include code for imported modules. 193 , stPreFreshInteractionId :: !InteractionId 194 , stPreImportedUserWarnings :: !(Map A.QName Text) 195 -- ^ Imported @UserWarning@s, not to be stored in the @Interface@ 196 , stPreLocalUserWarnings :: !(Map A.QName Text) 197 -- ^ Locally defined @UserWarning@s, to be stored in the @Interface@ 198 , stPreWarningOnImport :: !(Strict.Maybe Text) 199 -- ^ Whether the current module should raise a warning when opened 200 , stPreImportedPartialDefs :: !(Set QName) 201 -- ^ Imported partial definitions, not to be stored in the @Interface@ 202 , stPreProjectConfigs :: !(Map FilePath ProjectConfig) 203 -- ^ Map from directories to paths of closest enclosing .agda-lib 204 -- files (or @Nothing@ if there are none). 205 , stPreAgdaLibFiles :: !(Map FilePath AgdaLibFile) 206 -- ^ Contents of .agda-lib files that have already been parsed. 207 } 208 deriving Generic 209 210-- | Name disambiguation for the sake of highlighting. 211data DisambiguatedName = DisambiguatedName NameKind A.QName 212 deriving Generic 213type DisambiguatedNames = IntMap DisambiguatedName 214 215type ConcreteNames = Map Name [C.Name] 216 217data PostScopeState = PostScopeState 218 { stPostSyntaxInfo :: !HighlightingInfo 219 -- ^ Highlighting info. 220 , stPostDisambiguatedNames :: !DisambiguatedNames 221 -- ^ Disambiguation carried out by the type checker. 222 -- Maps position of first name character to disambiguated @'A.QName'@ 223 -- for each @'A.AmbiguousQName'@ already passed by the type checker. 224 , stPostMetaStore :: !MetaStore 225 , stPostInteractionPoints :: !InteractionPoints -- scope checker first 226 , stPostAwakeConstraints :: !Constraints 227 , stPostSleepingConstraints :: !Constraints 228 , stPostDirty :: !Bool -- local 229 -- ^ Dirty when a constraint is added, used to prevent pointer update. 230 -- Currently unused. 231 , stPostOccursCheckDefs :: !(Set QName) -- local 232 -- ^ Definitions to be considered during occurs check. 233 -- Initialized to the current mutual block before the check. 234 -- During occurs check, we remove definitions from this set 235 -- as soon we have checked them. 236 , stPostSignature :: !Signature 237 -- ^ Declared identifiers of the current file. 238 -- These will be serialized after successful type checking. 239 , stPostModuleCheckpoints :: !(Map ModuleName CheckpointId) 240 -- ^ For each module remember the checkpoint corresponding to the orignal 241 -- context of the module parameters. 242 , stPostImportsDisplayForms :: !DisplayForms 243 -- ^ Display forms we add for imported identifiers 244 , stPostCurrentModule :: !(Strict.Maybe ModuleName) 245 -- ^ The current module is available after it has been type 246 -- checked. 247 , stPostInstanceDefs :: !TempInstanceTable 248 , stPostConcreteNames :: !ConcreteNames 249 -- ^ Map keeping track of concrete names assigned to each abstract name 250 -- (can be more than one name in case the first one is shadowed) 251 , stPostUsedNames :: !(Map RawName [RawName]) 252 -- ^ Map keeping track for each name root (= name w/o numeric 253 -- suffixes) what names with the same root have been used during a 254 -- TC computation. This information is used to build the 255 -- @ShadowingNames@ map. 256 , stPostShadowingNames :: !(Map Name [RawName]) 257 -- ^ Map keeping track for each (abstract) name the list of all 258 -- (raw) names that it could maybe be shadowed by. 259 , stPostStatistics :: !Statistics 260 -- ^ Counters to collect various statistics about meta variables etc. 261 -- Only for current file. 262 , stPostTCWarnings :: ![TCWarning] 263 , stPostMutualBlocks :: !(Map MutualId MutualBlock) 264 , stPostLocalBuiltins :: !(BuiltinThings PrimFun) 265 , stPostFreshMetaId :: !MetaId 266 , stPostFreshMutualId :: !MutualId 267 , stPostFreshProblemId :: !ProblemId 268 , stPostFreshCheckpointId :: !CheckpointId 269 , stPostFreshInt :: !Int 270 , stPostFreshNameId :: !NameId 271 , stPostAreWeCaching :: !Bool 272 , stPostPostponeInstanceSearch :: !Bool 273 , stPostConsideringInstance :: !Bool 274 , stPostInstantiateBlocking :: !Bool 275 -- ^ Should we instantiate away blocking metas? 276 -- This can produce ill-typed terms but they are often more readable. See issue #3606. 277 -- Best set to True only for calls to pretty*/reify to limit unwanted reductions. 278 , stPostLocalPartialDefs :: !(Set QName) 279 -- ^ Local partial definitions, to be stored in the @Interface@ 280 } 281 deriving (Generic) 282 283-- | A mutual block of names in the signature. 284data MutualBlock = MutualBlock 285 { mutualInfo :: Info.MutualInfo 286 -- ^ The original info of the mutual block. 287 , mutualNames :: Set QName 288 } deriving (Show, Eq, Generic) 289 290instance Null MutualBlock where 291 empty = MutualBlock empty empty 292 293-- | A part of the state which is not reverted when an error is thrown 294-- or the state is reset. 295data PersistentTCState = PersistentTCSt 296 { stDecodedModules :: !DecodedModules 297 , stPersistentOptions :: CommandLineOptions 298 , stInteractionOutputCallback :: InteractionOutputCallback 299 -- ^ Callback function to call when there is a response 300 -- to give to the interactive frontend. 301 -- See the documentation of 'InteractionOutputCallback'. 302 , stBenchmark :: !Benchmark 303 -- ^ Structure to track how much CPU time was spent on which Agda phase. 304 -- Needs to be a strict field to avoid space leaks! 305 , stAccumStatistics :: !Statistics 306 -- ^ Should be strict field. 307 , stPersistLoadedFileCache :: !(Strict.Maybe LoadedFileCache) 308 -- ^ Cached typechecking state from the last loaded file. 309 -- Should be @Nothing@ when checking imports. 310 , stPersistBackends :: [Backend] 311 -- ^ Current backends with their options 312 } 313 deriving Generic 314 315data LoadedFileCache = LoadedFileCache 316 { lfcCached :: !CachedTypeCheckLog 317 , lfcCurrent :: !CurrentTypeCheckLog 318 } 319 deriving Generic 320 321-- | A log of what the type checker does and states after the action is 322-- completed. The cached version is stored first executed action first. 323type CachedTypeCheckLog = [(TypeCheckAction, PostScopeState)] 324 325-- | Like 'CachedTypeCheckLog', but storing the log for an ongoing type 326-- checking of a module. Stored in reverse order (last performed action 327-- first). 328type CurrentTypeCheckLog = [(TypeCheckAction, PostScopeState)] 329 330-- | A complete log for a module will look like this: 331-- 332-- * 'Pragmas' 333-- 334-- * 'EnterSection', entering the main module. 335-- 336-- * 'Decl'/'EnterSection'/'LeaveSection', for declarations and nested 337-- modules 338-- 339-- * 'LeaveSection', leaving the main module. 340data TypeCheckAction 341 = EnterSection !ModuleName !A.Telescope 342 | LeaveSection !ModuleName 343 | Decl !A.Declaration 344 -- ^ Never a Section or ScopeDecl 345 | Pragmas !PragmaOptions 346 deriving (Generic) 347 348-- | Empty persistent state. 349 350initPersistentState :: PersistentTCState 351initPersistentState = PersistentTCSt 352 { stPersistentOptions = defaultOptions 353 , stDecodedModules = Map.empty 354 , stInteractionOutputCallback = defaultInteractionOutputCallback 355 , stBenchmark = empty 356 , stAccumStatistics = Map.empty 357 , stPersistLoadedFileCache = empty 358 , stPersistBackends = [] 359 } 360 361-- | Empty state of type checker. 362 363initPreScopeState :: PreScopeState 364initPreScopeState = PreScopeState 365 { stPreTokens = mempty 366 , stPreImports = emptySignature 367 , stPreImportedModules = Set.empty 368 , stPreModuleToSource = Map.empty 369 , stPreVisitedModules = Map.empty 370 , stPreScope = emptyScopeInfo 371 , stPrePatternSyns = Map.empty 372 , stPrePatternSynImports = Map.empty 373 , stPreGeneralizedVars = mempty 374 , stPrePragmaOptions = defaultInteractionOptions 375 , stPreImportedBuiltins = Map.empty 376 , stPreImportedDisplayForms = HMap.empty 377 , stPreImportedInstanceDefs = Map.empty 378 , stPreForeignCode = Map.empty 379 , stPreFreshInteractionId = 0 380 , stPreImportedUserWarnings = Map.empty 381 , stPreLocalUserWarnings = Map.empty 382 , stPreWarningOnImport = empty 383 , stPreImportedPartialDefs = Set.empty 384 , stPreProjectConfigs = Map.empty 385 , stPreAgdaLibFiles = Map.empty 386 } 387 388initPostScopeState :: PostScopeState 389initPostScopeState = PostScopeState 390 { stPostSyntaxInfo = mempty 391 , stPostDisambiguatedNames = IntMap.empty 392 , stPostMetaStore = IntMap.empty 393 , stPostInteractionPoints = empty 394 , stPostAwakeConstraints = [] 395 , stPostSleepingConstraints = [] 396 , stPostDirty = False 397 , stPostOccursCheckDefs = Set.empty 398 , stPostSignature = emptySignature 399 , stPostModuleCheckpoints = Map.empty 400 , stPostImportsDisplayForms = HMap.empty 401 , stPostCurrentModule = empty 402 , stPostInstanceDefs = (Map.empty , Set.empty) 403 , stPostConcreteNames = Map.empty 404 , stPostUsedNames = Map.empty 405 , stPostShadowingNames = Map.empty 406 , stPostStatistics = Map.empty 407 , stPostTCWarnings = [] 408 , stPostMutualBlocks = Map.empty 409 , stPostLocalBuiltins = Map.empty 410 , stPostFreshMetaId = 0 411 , stPostFreshMutualId = 0 412 , stPostFreshProblemId = 1 413 , stPostFreshCheckpointId = 1 414 , stPostFreshInt = 0 415 , stPostFreshNameId = NameId 0 noModuleNameHash 416 , stPostAreWeCaching = False 417 , stPostPostponeInstanceSearch = False 418 , stPostConsideringInstance = False 419 , stPostInstantiateBlocking = False 420 , stPostLocalPartialDefs = Set.empty 421 } 422 423initState :: TCState 424initState = TCSt 425 { stPreScopeState = initPreScopeState 426 , stPostScopeState = initPostScopeState 427 , stPersistentState = initPersistentState 428 } 429 430-- * st-prefixed lenses 431------------------------------------------------------------------------ 432 433stTokens :: Lens' HighlightingInfo TCState 434stTokens f s = 435 f (stPreTokens (stPreScopeState s)) <&> 436 \x -> s {stPreScopeState = (stPreScopeState s) {stPreTokens = x}} 437 438stImports :: Lens' Signature TCState 439stImports f s = 440 f (stPreImports (stPreScopeState s)) <&> 441 \x -> s {stPreScopeState = (stPreScopeState s) {stPreImports = x}} 442 443stImportedModules :: Lens' (Set ModuleName) TCState 444stImportedModules f s = 445 f (stPreImportedModules (stPreScopeState s)) <&> 446 \x -> s {stPreScopeState = (stPreScopeState s) {stPreImportedModules = x}} 447 448stModuleToSource :: Lens' ModuleToSource TCState 449stModuleToSource f s = 450 f (stPreModuleToSource (stPreScopeState s)) <&> 451 \x -> s {stPreScopeState = (stPreScopeState s) {stPreModuleToSource = x}} 452 453stVisitedModules :: Lens' VisitedModules TCState 454stVisitedModules f s = 455 f (stPreVisitedModules (stPreScopeState s)) <&> 456 \x -> s {stPreScopeState = (stPreScopeState s) {stPreVisitedModules = x}} 457 458stScope :: Lens' ScopeInfo TCState 459stScope f s = 460 f (stPreScope (stPreScopeState s)) <&> 461 \x -> s {stPreScopeState = (stPreScopeState s) {stPreScope = x}} 462 463stPatternSyns :: Lens' A.PatternSynDefns TCState 464stPatternSyns f s = 465 f (stPrePatternSyns (stPreScopeState s)) <&> 466 \x -> s {stPreScopeState = (stPreScopeState s) {stPrePatternSyns = x}} 467 468stPatternSynImports :: Lens' A.PatternSynDefns TCState 469stPatternSynImports f s = 470 f (stPrePatternSynImports (stPreScopeState s)) <&> 471 \x -> s {stPreScopeState = (stPreScopeState s) {stPrePatternSynImports = x}} 472 473stGeneralizedVars :: Lens' (Maybe (Set QName)) TCState 474stGeneralizedVars f s = 475 f (Strict.toLazy $ stPreGeneralizedVars (stPreScopeState s)) <&> 476 \x -> s {stPreScopeState = (stPreScopeState s) {stPreGeneralizedVars = Strict.toStrict x}} 477 478stPragmaOptions :: Lens' PragmaOptions TCState 479stPragmaOptions f s = 480 f (stPrePragmaOptions (stPreScopeState s)) <&> 481 \x -> s {stPreScopeState = (stPreScopeState s) {stPrePragmaOptions = x}} 482 483stImportedBuiltins :: Lens' (BuiltinThings PrimFun) TCState 484stImportedBuiltins f s = 485 f (stPreImportedBuiltins (stPreScopeState s)) <&> 486 \x -> s {stPreScopeState = (stPreScopeState s) {stPreImportedBuiltins = x}} 487 488stForeignCode :: Lens' (Map BackendName [ForeignCode]) TCState 489stForeignCode f s = 490 f (stPreForeignCode (stPreScopeState s)) <&> 491 \x -> s {stPreScopeState = (stPreScopeState s) {stPreForeignCode = x}} 492 493stFreshInteractionId :: Lens' InteractionId TCState 494stFreshInteractionId f s = 495 f (stPreFreshInteractionId (stPreScopeState s)) <&> 496 \x -> s {stPreScopeState = (stPreScopeState s) {stPreFreshInteractionId = x}} 497 498stImportedUserWarnings :: Lens' (Map A.QName Text) TCState 499stImportedUserWarnings f s = 500 f (stPreImportedUserWarnings (stPreScopeState s)) <&> 501 \ x -> s {stPreScopeState = (stPreScopeState s) {stPreImportedUserWarnings = x}} 502 503stLocalUserWarnings :: Lens' (Map A.QName Text) TCState 504stLocalUserWarnings f s = 505 f (stPreLocalUserWarnings (stPreScopeState s)) <&> 506 \ x -> s {stPreScopeState = (stPreScopeState s) {stPreLocalUserWarnings = x}} 507 508getUserWarnings :: ReadTCState m => m (Map A.QName Text) 509getUserWarnings = do 510 iuw <- useR stImportedUserWarnings 511 luw <- useR stLocalUserWarnings 512 return $ iuw `Map.union` luw 513 514stWarningOnImport :: Lens' (Maybe Text) TCState 515stWarningOnImport f s = 516 f (Strict.toLazy $ stPreWarningOnImport (stPreScopeState s)) <&> 517 \ x -> s {stPreScopeState = (stPreScopeState s) {stPreWarningOnImport = Strict.toStrict x}} 518 519stImportedPartialDefs :: Lens' (Set QName) TCState 520stImportedPartialDefs f s = 521 f (stPreImportedPartialDefs (stPreScopeState s)) <&> 522 \ x -> s {stPreScopeState = (stPreScopeState s) {stPreImportedPartialDefs = x}} 523 524stLocalPartialDefs :: Lens' (Set QName) TCState 525stLocalPartialDefs f s = 526 f (stPostLocalPartialDefs (stPostScopeState s)) <&> 527 \ x -> s {stPostScopeState = (stPostScopeState s) {stPostLocalPartialDefs = x}} 528 529getPartialDefs :: ReadTCState m => m (Set QName) 530getPartialDefs = do 531 ipd <- useR stImportedPartialDefs 532 lpd <- useR stLocalPartialDefs 533 return $ ipd `Set.union` lpd 534 535stLoadedFileCache :: Lens' (Maybe LoadedFileCache) TCState 536stLoadedFileCache f s = 537 f (Strict.toLazy $ stPersistLoadedFileCache (stPersistentState s)) <&> 538 \x -> s {stPersistentState = (stPersistentState s) {stPersistLoadedFileCache = Strict.toStrict x}} 539 540stBackends :: Lens' [Backend] TCState 541stBackends f s = 542 f (stPersistBackends (stPersistentState s)) <&> 543 \x -> s {stPersistentState = (stPersistentState s) {stPersistBackends = x}} 544 545stProjectConfigs :: Lens' (Map FilePath ProjectConfig) TCState 546stProjectConfigs f s = 547 f (stPreProjectConfigs (stPreScopeState s)) <&> 548 \ x -> s {stPreScopeState = (stPreScopeState s) {stPreProjectConfigs = x}} 549 550stAgdaLibFiles :: Lens' (Map FilePath AgdaLibFile) TCState 551stAgdaLibFiles f s = 552 f (stPreAgdaLibFiles (stPreScopeState s)) <&> 553 \ x -> s {stPreScopeState = (stPreScopeState s) {stPreAgdaLibFiles = x}} 554 555stFreshNameId :: Lens' NameId TCState 556stFreshNameId f s = 557 f (stPostFreshNameId (stPostScopeState s)) <&> 558 \x -> s {stPostScopeState = (stPostScopeState s) {stPostFreshNameId = x}} 559 560stSyntaxInfo :: Lens' HighlightingInfo TCState 561stSyntaxInfo f s = 562 f (stPostSyntaxInfo (stPostScopeState s)) <&> 563 \x -> s {stPostScopeState = (stPostScopeState s) {stPostSyntaxInfo = x}} 564 565stDisambiguatedNames :: Lens' DisambiguatedNames TCState 566stDisambiguatedNames f s = 567 f (stPostDisambiguatedNames (stPostScopeState s)) <&> 568 \x -> s {stPostScopeState = (stPostScopeState s) {stPostDisambiguatedNames = x}} 569 570stMetaStore :: Lens' MetaStore TCState 571stMetaStore f s = 572 f (stPostMetaStore (stPostScopeState s)) <&> 573 \x -> s {stPostScopeState = (stPostScopeState s) {stPostMetaStore = x}} 574 575stInteractionPoints :: Lens' InteractionPoints TCState 576stInteractionPoints f s = 577 f (stPostInteractionPoints (stPostScopeState s)) <&> 578 \x -> s {stPostScopeState = (stPostScopeState s) {stPostInteractionPoints = x}} 579 580stAwakeConstraints :: Lens' Constraints TCState 581stAwakeConstraints f s = 582 f (stPostAwakeConstraints (stPostScopeState s)) <&> 583 \x -> s {stPostScopeState = (stPostScopeState s) {stPostAwakeConstraints = x}} 584 585stSleepingConstraints :: Lens' Constraints TCState 586stSleepingConstraints f s = 587 f (stPostSleepingConstraints (stPostScopeState s)) <&> 588 \x -> s {stPostScopeState = (stPostScopeState s) {stPostSleepingConstraints = x}} 589 590stDirty :: Lens' Bool TCState 591stDirty f s = 592 f (stPostDirty (stPostScopeState s)) <&> 593 \x -> s {stPostScopeState = (stPostScopeState s) {stPostDirty = x}} 594 595stOccursCheckDefs :: Lens' (Set QName) TCState 596stOccursCheckDefs f s = 597 f (stPostOccursCheckDefs (stPostScopeState s)) <&> 598 \x -> s {stPostScopeState = (stPostScopeState s) {stPostOccursCheckDefs = x}} 599 600stSignature :: Lens' Signature TCState 601stSignature f s = 602 f (stPostSignature (stPostScopeState s)) <&> 603 \x -> s {stPostScopeState = (stPostScopeState s) {stPostSignature = x}} 604 605stModuleCheckpoints :: Lens' (Map ModuleName CheckpointId) TCState 606stModuleCheckpoints f s = 607 f (stPostModuleCheckpoints (stPostScopeState s)) <&> 608 \x -> s {stPostScopeState = (stPostScopeState s) {stPostModuleCheckpoints = x}} 609 610stImportsDisplayForms :: Lens' DisplayForms TCState 611stImportsDisplayForms f s = 612 f (stPostImportsDisplayForms (stPostScopeState s)) <&> 613 \x -> s {stPostScopeState = (stPostScopeState s) {stPostImportsDisplayForms = x}} 614 615stImportedDisplayForms :: Lens' DisplayForms TCState 616stImportedDisplayForms f s = 617 f (stPreImportedDisplayForms (stPreScopeState s)) <&> 618 \x -> s {stPreScopeState = (stPreScopeState s) {stPreImportedDisplayForms = x}} 619 620stCurrentModule :: Lens' (Maybe ModuleName) TCState 621stCurrentModule f s = 622 f (Strict.toLazy $ stPostCurrentModule (stPostScopeState s)) <&> 623 \x -> s {stPostScopeState = (stPostScopeState s) {stPostCurrentModule = Strict.toStrict x}} 624 625stImportedInstanceDefs :: Lens' InstanceTable TCState 626stImportedInstanceDefs f s = 627 f (stPreImportedInstanceDefs (stPreScopeState s)) <&> 628 \x -> s {stPreScopeState = (stPreScopeState s) {stPreImportedInstanceDefs = x}} 629 630stInstanceDefs :: Lens' TempInstanceTable TCState 631stInstanceDefs f s = 632 f (stPostInstanceDefs (stPostScopeState s)) <&> 633 \x -> s {stPostScopeState = (stPostScopeState s) {stPostInstanceDefs = x}} 634 635stConcreteNames :: Lens' ConcreteNames TCState 636stConcreteNames f s = 637 f (stPostConcreteNames (stPostScopeState s)) <&> 638 \x -> s {stPostScopeState = (stPostScopeState s) {stPostConcreteNames = x}} 639 640stUsedNames :: Lens' (Map RawName [RawName]) TCState 641stUsedNames f s = 642 f (stPostUsedNames (stPostScopeState s)) <&> 643 \x -> s {stPostScopeState = (stPostScopeState s) {stPostUsedNames = x}} 644 645stShadowingNames :: Lens' (Map Name [RawName]) TCState 646stShadowingNames f s = 647 f (stPostShadowingNames (stPostScopeState s)) <&> 648 \x -> s {stPostScopeState = (stPostScopeState s) {stPostShadowingNames = x}} 649 650stStatistics :: Lens' Statistics TCState 651stStatistics f s = 652 f (stPostStatistics (stPostScopeState s)) <&> 653 \x -> s {stPostScopeState = (stPostScopeState s) {stPostStatistics = x}} 654 655stTCWarnings :: Lens' [TCWarning] TCState 656stTCWarnings f s = 657 f (stPostTCWarnings (stPostScopeState s)) <&> 658 \x -> s {stPostScopeState = (stPostScopeState s) {stPostTCWarnings = x}} 659 660stMutualBlocks :: Lens' (Map MutualId MutualBlock) TCState 661stMutualBlocks f s = 662 f (stPostMutualBlocks (stPostScopeState s)) <&> 663 \x -> s {stPostScopeState = (stPostScopeState s) {stPostMutualBlocks = x}} 664 665stLocalBuiltins :: Lens' (BuiltinThings PrimFun) TCState 666stLocalBuiltins f s = 667 f (stPostLocalBuiltins (stPostScopeState s)) <&> 668 \x -> s {stPostScopeState = (stPostScopeState s) {stPostLocalBuiltins = x}} 669 670stFreshMetaId :: Lens' MetaId TCState 671stFreshMetaId f s = 672 f (stPostFreshMetaId (stPostScopeState s)) <&> 673 \x -> s {stPostScopeState = (stPostScopeState s) {stPostFreshMetaId = x}} 674 675stFreshMutualId :: Lens' MutualId TCState 676stFreshMutualId f s = 677 f (stPostFreshMutualId (stPostScopeState s)) <&> 678 \x -> s {stPostScopeState = (stPostScopeState s) {stPostFreshMutualId = x}} 679 680stFreshProblemId :: Lens' ProblemId TCState 681stFreshProblemId f s = 682 f (stPostFreshProblemId (stPostScopeState s)) <&> 683 \x -> s {stPostScopeState = (stPostScopeState s) {stPostFreshProblemId = x}} 684 685stFreshCheckpointId :: Lens' CheckpointId TCState 686stFreshCheckpointId f s = 687 f (stPostFreshCheckpointId (stPostScopeState s)) <&> 688 \x -> s {stPostScopeState = (stPostScopeState s) {stPostFreshCheckpointId = x}} 689 690stFreshInt :: Lens' Int TCState 691stFreshInt f s = 692 f (stPostFreshInt (stPostScopeState s)) <&> 693 \x -> s {stPostScopeState = (stPostScopeState s) {stPostFreshInt = x}} 694 695-- use @areWeCaching@ from the Caching module instead. 696stAreWeCaching :: Lens' Bool TCState 697stAreWeCaching f s = 698 f (stPostAreWeCaching (stPostScopeState s)) <&> 699 \x -> s {stPostScopeState = (stPostScopeState s) {stPostAreWeCaching = x}} 700 701stPostponeInstanceSearch :: Lens' Bool TCState 702stPostponeInstanceSearch f s = 703 f (stPostPostponeInstanceSearch (stPostScopeState s)) <&> 704 \x -> s {stPostScopeState = (stPostScopeState s) {stPostPostponeInstanceSearch = x}} 705 706stConsideringInstance :: Lens' Bool TCState 707stConsideringInstance f s = 708 f (stPostConsideringInstance (stPostScopeState s)) <&> 709 \x -> s {stPostScopeState = (stPostScopeState s) {stPostConsideringInstance = x}} 710 711stInstantiateBlocking :: Lens' Bool TCState 712stInstantiateBlocking f s = 713 f (stPostInstantiateBlocking (stPostScopeState s)) <&> 714 \x -> s {stPostScopeState = (stPostScopeState s) {stPostInstantiateBlocking = x}} 715 716stBuiltinThings :: TCState -> BuiltinThings PrimFun 717stBuiltinThings s = (s^.stLocalBuiltins) `Map.union` (s^.stImportedBuiltins) 718 719 720-- * Fresh things 721------------------------------------------------------------------------ 722 723class Enum i => HasFresh i where 724 freshLens :: Lens' i TCState 725 nextFresh' :: i -> i 726 nextFresh' = succ 727 728nextFresh :: HasFresh i => TCState -> (i, TCState) 729nextFresh s = 730 let !c = s^.freshLens 731 in (c, set freshLens (nextFresh' c) s) 732 733class Monad m => MonadFresh i m where 734 fresh :: m i 735 736 default fresh :: (MonadTrans t, MonadFresh i n, t n ~ m) => m i 737 fresh = lift fresh 738 739instance MonadFresh i m => MonadFresh i (ReaderT r m) 740instance MonadFresh i m => MonadFresh i (StateT s m) 741instance MonadFresh i m => MonadFresh i (ListT m) 742instance MonadFresh i m => MonadFresh i (IdentityT m) 743 744instance HasFresh i => MonadFresh i TCM where 745 fresh = do 746 !s <- getTC 747 let (!c , !s') = nextFresh s 748 putTC s' 749 return c 750 751instance HasFresh MetaId where 752 freshLens = stFreshMetaId 753 754instance HasFresh MutualId where 755 freshLens = stFreshMutualId 756 757instance HasFresh InteractionId where 758 freshLens = stFreshInteractionId 759 760instance HasFresh NameId where 761 freshLens = stFreshNameId 762 -- nextFresh increments the current fresh name by 2 so @NameId@s used 763 -- before caching starts do not overlap with the ones used after. 764 nextFresh' = succ . succ 765 766instance HasFresh Int where 767 freshLens = stFreshInt 768 769instance HasFresh ProblemId where 770 freshLens = stFreshProblemId 771 772newtype CheckpointId = CheckpointId Int 773 deriving (Data, Eq, Ord, Enum, Real, Integral, Num, NFData) 774 775instance Show CheckpointId where 776 show (CheckpointId n) = show n 777 778instance Pretty CheckpointId where 779 pretty (CheckpointId n) = pretty n 780 781instance HasFresh CheckpointId where 782 freshLens = stFreshCheckpointId 783 784freshName :: MonadFresh NameId m => Range -> String -> m Name 785freshName r s = do 786 i <- fresh 787 return $ mkName r i s 788 789freshNoName :: MonadFresh NameId m => Range -> m Name 790freshNoName r = 791 do i <- fresh 792 return $ makeName i (C.NoName noRange i) r noFixity' False 793 794freshNoName_ :: MonadFresh NameId m => m Name 795freshNoName_ = freshNoName noRange 796 797freshRecordName :: MonadFresh NameId m => m Name 798freshRecordName = do 799 i <- fresh 800 return $ makeName i (C.setNotInScope $ C.simpleName "r") noRange noFixity' True 801 802-- | Create a fresh name from @a@. 803class FreshName a where 804 freshName_ :: MonadFresh NameId m => a -> m Name 805 806instance FreshName (Range, String) where 807 freshName_ = uncurry freshName 808 809instance FreshName String where 810 freshName_ = freshName noRange 811 812instance FreshName Range where 813 freshName_ = freshNoName 814 815instance FreshName () where 816 freshName_ () = freshNoName_ 817 818--------------------------------------------------------------------------- 819-- ** Managing file names 820--------------------------------------------------------------------------- 821 822-- | Maps top-level module names to the corresponding source file 823-- names. 824 825type ModuleToSource = Map TopLevelModuleName AbsolutePath 826 827-- | Maps source file names to the corresponding top-level module 828-- names. 829 830type SourceToModule = Map AbsolutePath TopLevelModuleName 831 832-- | Creates a 'SourceToModule' map based on 'stModuleToSource'. 833-- 834-- O(n log n). 835-- 836-- For a single reverse lookup in 'stModuleToSource', 837-- rather use 'lookupModuleFromSourse'. 838 839sourceToModule :: TCM SourceToModule 840sourceToModule = 841 Map.fromList 842 . List.map (\(m, f) -> (f, m)) 843 . Map.toList 844 <$> useTC stModuleToSource 845 846-- | Lookup an 'AbsolutePath' in 'sourceToModule'. 847-- 848-- O(n). 849 850lookupModuleFromSource :: ReadTCState m => AbsolutePath -> m (Maybe TopLevelModuleName) 851lookupModuleFromSource f = 852 fmap fst . List.find ((f ==) . snd) . Map.toList <$> useR stModuleToSource 853 854 855--------------------------------------------------------------------------- 856-- ** Associating concrete names to an abstract name 857--------------------------------------------------------------------------- 858 859-- | A monad that has read and write access to the stConcreteNames 860-- part of the TCState. Basically, this is a synonym for `MonadState 861-- ConcreteNames m` (which cannot be used directly because of the 862-- limitations of Haskell's typeclass system). 863class Monad m => MonadStConcreteNames m where 864 runStConcreteNames :: StateT ConcreteNames m a -> m a 865 866 useConcreteNames :: m ConcreteNames 867 useConcreteNames = runStConcreteNames get 868 869 modifyConcreteNames :: (ConcreteNames -> ConcreteNames) -> m () 870 modifyConcreteNames = runStConcreteNames . modify 871 872instance MonadStConcreteNames TCM where 873 runStConcreteNames m = stateTCLensM stConcreteNames $ runStateT m 874 875instance MonadStConcreteNames m => MonadStConcreteNames (IdentityT m) where 876 runStConcreteNames m = IdentityT $ runStConcreteNames $ StateT $ runIdentityT . runStateT m 877 878instance MonadStConcreteNames m => MonadStConcreteNames (ReaderT r m) where 879 runStConcreteNames m = ReaderT $ runStConcreteNames . StateT . flip (runReaderT . runStateT m) 880 881instance MonadStConcreteNames m => MonadStConcreteNames (StateT s m) where 882 runStConcreteNames m = StateT $ \s -> runStConcreteNames $ StateT $ \ns -> do 883 ((x,ns'),s') <- runStateT (runStateT m ns) s 884 return ((x,s'),ns') 885 886--------------------------------------------------------------------------- 887-- ** Interface 888--------------------------------------------------------------------------- 889 890 891-- | Distinguishes between type-checked and scope-checked interfaces 892-- when stored in the map of `VisitedModules`. 893data ModuleCheckMode 894 = ModuleScopeChecked 895 | ModuleTypeChecked 896 deriving (Eq, Ord, Bounded, Enum, Show, Generic) 897 898 899data ModuleInfo = ModuleInfo 900 { miInterface :: Interface 901 , miWarnings :: [TCWarning] 902 -- ^ Warnings were encountered when the module was type checked. 903 -- These might include warnings not stored in the interface itself, 904 -- specifically unsolved interaction metas. 905 -- See "Agda.Interaction.Imports" 906 , miPrimitive :: Bool 907 -- ^ 'True' if the module is a primitive module, which should always 908 -- be importable. 909 , miMode :: ModuleCheckMode 910 -- ^ The `ModuleCheckMode` used to create the `Interface` 911 } 912 deriving Generic 913 914-- Note that the use of 'C.TopLevelModuleName' here is a potential 915-- performance problem, because these names do not contain unique 916-- identifiers. 917 918type VisitedModules = Map C.TopLevelModuleName ModuleInfo 919type DecodedModules = Map C.TopLevelModuleName ModuleInfo 920 921data ForeignCode = ForeignCode Range String 922 deriving (Show, Generic) 923 924data Interface = Interface 925 { iSourceHash :: Hash 926 -- ^ Hash of the source code. 927 , iSource :: TL.Text 928 -- ^ The source code. The source code is stored so that the HTML 929 -- and LaTeX backends can generate their output without having to 930 -- re-read the (possibly out of date) source code. 931 , iFileType :: FileType 932 -- ^ Source file type, determined from the file extension 933 , iImportedModules :: [(ModuleName, Hash)] 934 -- ^ Imported modules and their hashes. 935 , iModuleName :: ModuleName 936 -- ^ Module name of this interface. 937 , iScope :: Map ModuleName Scope 938 -- ^ Scope defined by this module. 939 -- 940 -- Andreas, AIM XX: Too avoid duplicate serialization, this field is 941 -- not serialized, so if you deserialize an interface, @iScope@ 942 -- will be empty. 943 -- But 'constructIScope' constructs 'iScope' from 'iInsideScope'. 944 , iInsideScope :: ScopeInfo 945 -- ^ Scope after we loaded this interface. 946 -- Used in 'Agda.Interaction.BasicOps.AtTopLevel' 947 -- and 'Agda.Interaction.CommandLine.interactionLoop'. 948 , iSignature :: Signature 949 , iDisplayForms :: DisplayForms 950 -- ^ Display forms added for imported identifiers. 951 , iUserWarnings :: Map A.QName Text 952 -- ^ User warnings for imported identifiers 953 , iImportWarning :: Maybe Text 954 -- ^ Whether this module should raise a warning when imported 955 , iBuiltin :: BuiltinThings (String, QName) 956 , iForeignCode :: Map BackendName [ForeignCode] 957 , iHighlighting :: HighlightingInfo 958 , iDefaultPragmaOptions :: [OptionsPragma] 959 -- ^ Pragma options set in library files. 960 , iFilePragmaOptions :: [OptionsPragma] 961 -- ^ Pragma options set in the file. 962 , iOptionsUsed :: PragmaOptions 963 -- ^ Options/features used when checking the file (can be different 964 -- from options set directly in the file). 965 , iPatternSyns :: A.PatternSynDefns 966 , iWarnings :: [TCWarning] 967 , iPartialDefs :: Set QName 968 } 969 deriving (Show, Generic) 970 971instance Pretty Interface where 972 pretty (Interface 973 sourceH source fileT importedM moduleN scope insideS signature 974 display userwarn importwarn builtin foreignCode highlighting 975 libPragmaO filePragmaO 976 oUsed patternS warnings partialdefs) = 977 978 hang "Interface" 2 $ vcat 979 [ "source hash:" <+> (pretty . show) sourceH 980 , "source:" $$ nest 2 (text $ TL.unpack source) 981 , "file type:" <+> (pretty . show) fileT 982 , "imported modules:" <+> (pretty . show) importedM 983 , "module name:" <+> pretty moduleN 984 , "scope:" <+> (pretty . show) scope 985 , "inside scope:" <+> (pretty . show) insideS 986 , "signature:" <+> (pretty . show) signature 987 , "display:" <+> (pretty . show) display 988 , "user warnings:" <+> (pretty . show) userwarn 989 , "import warning:" <+> (pretty . show) importwarn 990 , "builtin:" <+> (pretty . show) builtin 991 , "Foreign code:" <+> (pretty . show) foreignCode 992 , "highlighting:" <+> (pretty . show) highlighting 993 , "library pragma options:" <+> (pretty . show) libPragmaO 994 , "file pragma options:" <+> (pretty . show) filePragmaO 995 , "options used:" <+> (pretty . show) oUsed 996 , "pattern syns:" <+> (pretty . show) patternS 997 , "warnings:" <+> (pretty . show) warnings 998 , "partial definitions:" <+> (pretty . show) partialdefs 999 ] 1000 1001-- | Combines the source hash and the (full) hashes of the imported modules. 1002iFullHash :: Interface -> Hash 1003iFullHash i = combineHashes $ iSourceHash i : List.map snd (iImportedModules i) 1004 1005--------------------------------------------------------------------------- 1006-- ** Closure 1007--------------------------------------------------------------------------- 1008 1009data Closure a = Closure 1010 { clSignature :: Signature 1011 , clEnv :: TCEnv 1012 , clScope :: ScopeInfo 1013 , clModuleCheckpoints :: Map ModuleName CheckpointId 1014 , clValue :: a 1015 } 1016 deriving (Functor, Foldable, Generic) 1017 1018instance Show a => Show (Closure a) where 1019 show cl = "Closure { clValue = " ++ show (clValue cl) ++ " }" 1020 1021instance HasRange a => HasRange (Closure a) where 1022 getRange = getRange . clValue 1023 1024class LensClosure a b | b -> a where 1025 lensClosure :: Lens' (Closure a) b 1026 1027instance LensClosure a (Closure a) where 1028 lensClosure = id 1029 1030instance LensTCEnv (Closure a) where 1031 lensTCEnv f cl = (f $! clEnv cl) <&> \ env -> cl { clEnv = env } 1032 1033buildClosure :: (MonadTCEnv m, ReadTCState m) => a -> m (Closure a) 1034buildClosure x = do 1035 env <- askTC 1036 sig <- useR stSignature 1037 scope <- useR stScope 1038 cps <- useR stModuleCheckpoints 1039 return $ Closure sig env scope cps x 1040 1041--------------------------------------------------------------------------- 1042-- ** Constraints 1043--------------------------------------------------------------------------- 1044 1045type Constraints = [ProblemConstraint] 1046 1047data ProblemConstraint = PConstr 1048 { constraintProblems :: Set ProblemId 1049 , constraintUnblocker :: Blocker 1050 , theConstraint :: Closure Constraint 1051 } 1052 deriving (Show, Generic) 1053 1054instance HasRange ProblemConstraint where 1055 getRange = getRange . theConstraint 1056 1057data Constraint 1058 = ValueCmp Comparison CompareAs Term Term 1059 | ValueCmpOnFace Comparison Term Type Term Term 1060 | ElimCmp [Polarity] [IsForced] Type Term [Elim] [Elim] 1061 | SortCmp Comparison Sort Sort 1062 | LevelCmp Comparison Level Level 1063-- | ShortCut MetaId Term Type 1064-- -- ^ A delayed instantiation. Replaces @ValueCmp@ in 'postponeTypeCheckingProblem'. 1065 | HasBiggerSort Sort 1066 | HasPTSRule (Dom Type) (Abs Sort) 1067 | CheckMetaInst MetaId 1068 | UnBlock MetaId 1069 -- ^ Meta created for a term blocked by a postponed type checking problem or unsolved 1070 -- constraints. The 'MetaInstantiation' for the meta (when unsolved) is either 'BlockedConst' 1071 -- or 'PostponedTypeCheckingProblem'. 1072 | IsEmpty Range Type 1073 -- ^ The range is the one of the absurd pattern. 1074 | CheckSizeLtSat Term 1075 -- ^ Check that the 'Term' is either not a SIZELT or a non-empty SIZELT. 1076 | FindInstance MetaId (Maybe [Candidate]) 1077 -- ^ the first argument is the instance argument and the second one is the list of candidates 1078 -- (or Nothing if we haven’t determined the list of candidates yet) 1079 | CheckFunDef Delayed A.DefInfo QName [A.Clause] TCErr 1080 -- ^ Last argument is the error causing us to postpone. 1081 | UnquoteTactic Term Term Type -- ^ First argument is computation and the others are hole and goal type 1082 | CheckLockedVars Term Type (Arg Term) Type -- ^ @CheckLockedVars t ty lk lk_ty@ with @t : ty@, @lk : lk_ty@ and @t lk@ well-typed. 1083 | UsableAtModality Modality Term -- ^ is the term usable at the given modality? 1084 deriving (Show, Generic) 1085 1086instance HasRange Constraint where 1087 getRange (IsEmpty r t) = r 1088 getRange _ = noRange 1089{- no Range instances for Term, Type, Elm, Tele, Sort, Level, MetaId 1090 getRange (ValueCmp cmp a u v) = getRange (a,u,v) 1091 getRange (ElimCmp pol a v es es') = getRange (a,v,es,es') 1092 getRange (TelCmp a b cmp tel tel') = getRange (a,b,tel,tel') 1093 getRange (SortCmp cmp s s') = getRange (s,s') 1094 getRange (LevelCmp cmp l l') = getRange (l,l') 1095 getRange (UnBlock x) = getRange x 1096 getRange (FindInstance x cands) = getRange x 1097-} 1098 1099instance Free Constraint where 1100 freeVars' c = 1101 case c of 1102 ValueCmp _ t u v -> freeVars' (t, (u, v)) 1103 ValueCmpOnFace _ p t u v -> freeVars' (p, (t, (u, v))) 1104 ElimCmp _ _ t u es es' -> freeVars' ((t, u), (es, es')) 1105 SortCmp _ s s' -> freeVars' (s, s') 1106 LevelCmp _ l l' -> freeVars' (l, l') 1107 UnBlock _ -> mempty 1108 IsEmpty _ t -> freeVars' t 1109 CheckSizeLtSat u -> freeVars' u 1110 FindInstance _ cs -> freeVars' cs 1111 CheckFunDef{} -> mempty 1112 HasBiggerSort s -> freeVars' s 1113 HasPTSRule a s -> freeVars' (a , s) 1114 CheckLockedVars a b c d -> freeVars' ((a,b),(c,d)) 1115 UnquoteTactic t h g -> freeVars' (t, (h, g)) 1116 CheckMetaInst m -> mempty 1117 UsableAtModality mod t -> freeVars' t 1118 1119instance TermLike Constraint where 1120 foldTerm f = \case 1121 ValueCmp _ t u v -> foldTerm f (t, u, v) 1122 ValueCmpOnFace _ p t u v -> foldTerm f (p, t, u, v) 1123 ElimCmp _ _ t u es es' -> foldTerm f (t, u, es, es') 1124 LevelCmp _ l l' -> foldTerm f (Level l, Level l') -- Note wrapping as term, to ensure f gets to act on l and l' 1125 IsEmpty _ t -> foldTerm f t 1126 CheckSizeLtSat u -> foldTerm f u 1127 UnquoteTactic t h g -> foldTerm f (t, h, g) 1128 SortCmp _ s1 s2 -> foldTerm f (Sort s1, Sort s2) -- Same as LevelCmp case 1129 UnBlock _ -> mempty 1130 CheckLockedVars a b c d -> foldTerm f (a, b, c, d) 1131 FindInstance _ _ -> mempty 1132 CheckFunDef{} -> mempty 1133 HasBiggerSort s -> foldTerm f s 1134 HasPTSRule a s -> foldTerm f (a, Sort <$> s) 1135 CheckMetaInst m -> mempty 1136 UsableAtModality m t -> foldTerm f t 1137 1138 traverseTermM f c = __IMPOSSIBLE__ -- Not yet implemented 1139 1140instance AllMetas Constraint 1141 1142data Comparison = CmpEq | CmpLeq 1143 deriving (Eq, Data, Show, Generic) 1144 1145instance Pretty Comparison where 1146 pretty CmpEq = "=" 1147 pretty CmpLeq = "=<" 1148 1149-- | An extension of 'Comparison' to @>=@. 1150data CompareDirection = DirEq | DirLeq | DirGeq 1151 deriving (Eq, Show) 1152 1153instance Pretty CompareDirection where 1154 pretty = text . \case 1155 DirEq -> "=" 1156 DirLeq -> "=<" 1157 DirGeq -> ">=" 1158 1159-- | Embed 'Comparison' into 'CompareDirection'. 1160fromCmp :: Comparison -> CompareDirection 1161fromCmp CmpEq = DirEq 1162fromCmp CmpLeq = DirLeq 1163 1164-- | Flip the direction of comparison. 1165flipCmp :: CompareDirection -> CompareDirection 1166flipCmp DirEq = DirEq 1167flipCmp DirLeq = DirGeq 1168flipCmp DirGeq = DirLeq 1169 1170-- | Turn a 'Comparison' function into a 'CompareDirection' function. 1171-- 1172-- Property: @dirToCmp f (fromCmp cmp) = f cmp@ 1173dirToCmp :: (Comparison -> a -> a -> c) -> CompareDirection -> a -> a -> c 1174dirToCmp cont DirEq = cont CmpEq 1175dirToCmp cont DirLeq = cont CmpLeq 1176dirToCmp cont DirGeq = flip $ cont CmpLeq 1177 1178-- | We can either compare two terms at a given type, or compare two 1179-- types without knowing (or caring about) their sorts. 1180data CompareAs 1181 = AsTermsOf Type -- ^ @Type@ should not be @Size@. 1182 -- But currently, we do not rely on this invariant. 1183 | AsSizes -- ^ Replaces @AsTermsOf Size@. 1184 | AsTypes 1185 deriving (Data, Show, Generic) 1186 1187instance Free CompareAs where 1188 freeVars' (AsTermsOf a) = freeVars' a 1189 freeVars' AsSizes = mempty 1190 freeVars' AsTypes = mempty 1191 1192instance TermLike CompareAs where 1193 foldTerm f (AsTermsOf a) = foldTerm f a 1194 foldTerm f AsSizes = mempty 1195 foldTerm f AsTypes = mempty 1196 1197 traverseTermM f = \case 1198 AsTermsOf a -> AsTermsOf <$> traverseTermM f a 1199 AsSizes -> return AsSizes 1200 AsTypes -> return AsTypes 1201 1202instance AllMetas CompareAs 1203 1204--------------------------------------------------------------------------- 1205-- * Open things 1206--------------------------------------------------------------------------- 1207 1208-- | A thing tagged with the context it came from. Also keeps the substitution from previous 1209-- checkpoints. This lets us handle the case when an open thing was created in a context that we 1210-- have since exited. Remember which module it's from to make sure we don't get confused by 1211-- checkpoints from other files. 1212data Open a = OpenThing { openThingCheckpoint :: CheckpointId 1213 , openThingCheckpointMap :: Map CheckpointId Substitution 1214 , openThingModule :: ModuleNameHash 1215 , openThing :: a } 1216 deriving (Show, Functor, Foldable, Traversable, Generic) 1217 1218instance Decoration Open where 1219 traverseF f (OpenThing cp env m x) = OpenThing cp env m <$> f x 1220 1221instance Pretty a => Pretty (Open a) where 1222 prettyPrec p (OpenThing cp env _ x) = mparens (p > 9) $ 1223 "OpenThing" <+> pretty cp <+> pretty (Map.toList env) <?> prettyPrec 10 x 1224 1225--------------------------------------------------------------------------- 1226-- * Judgements 1227-- 1228-- Used exclusively for typing of meta variables. 1229--------------------------------------------------------------------------- 1230 1231-- | Parametrized since it is used without MetaId when creating a new meta. 1232data Judgement a 1233 = HasType 1234 { jMetaId :: a 1235 , jComparison :: Comparison -- ^ are we checking (@CmpLeq@) or inferring (@CmpEq@) the type? 1236 , jMetaType :: Type 1237 } 1238 | IsSort 1239 { jMetaId :: a 1240 , jMetaType :: Type -- Andreas, 2011-04-26: type needed for higher-order sort metas 1241 } 1242 deriving Generic 1243 1244instance Pretty a => Pretty (Judgement a) where 1245 pretty (HasType a cmp t) = hsep [ pretty a, ":" , pretty t ] 1246 pretty (IsSort a t) = hsep [ pretty a, ":sort", pretty t ] 1247 1248----------------------------------------------------------------------------- 1249-- ** Generalizable variables 1250----------------------------------------------------------------------------- 1251 1252data DoGeneralize 1253 = YesGeneralizeVar -- ^ Generalize because it is a generalizable variable. 1254 | YesGeneralizeMeta -- ^ Generalize because it is a metavariable and 1255 -- we're currently checking the type of a generalizable variable 1256 -- (this should get the default modality). 1257 | NoGeneralize -- ^ Don't generalize. 1258 deriving (Eq, Ord, Show, Data, Generic) 1259 1260-- | The value of a generalizable variable. This is created to be a 1261-- generalizable meta before checking the type to be generalized. 1262data GeneralizedValue = GeneralizedValue 1263 { genvalCheckpoint :: CheckpointId 1264 , genvalTerm :: Term 1265 , genvalType :: Type 1266 } deriving (Show, Data, Generic) 1267 1268--------------------------------------------------------------------------- 1269-- ** Meta variables 1270--------------------------------------------------------------------------- 1271 1272data MetaVariable = 1273 MetaVar { mvInfo :: MetaInfo 1274 , mvPriority :: MetaPriority -- ^ some metavariables are more eager to be instantiated 1275 , mvPermutation :: Permutation 1276 -- ^ a metavariable doesn't have to depend on all variables 1277 -- in the context, this "permutation" will throw away the 1278 -- ones it does not depend on 1279 , mvJudgement :: Judgement MetaId 1280 , mvInstantiation :: MetaInstantiation 1281 , mvListeners :: Set Listener -- ^ meta variables scheduled for eta-expansion but blocked by this one 1282 , mvFrozen :: Frozen -- ^ are we past the point where we can instantiate this meta variable? 1283 , mvTwin :: Maybe MetaId -- ^ @Just m@ means this meta will be equated to @m@ when the latter is unblocked. See @blockedTermOnProblem@. 1284 } 1285 deriving Generic 1286 1287data Listener = EtaExpand MetaId 1288 | CheckConstraint Nat ProblemConstraint 1289 deriving Generic 1290 1291instance Eq Listener where 1292 EtaExpand x == EtaExpand y = x == y 1293 CheckConstraint x _ == CheckConstraint y _ = x == y 1294 _ == _ = False 1295 1296instance Ord Listener where 1297 EtaExpand x `compare` EtaExpand y = x `compare` y 1298 CheckConstraint x _ `compare` CheckConstraint y _ = x `compare` y 1299 EtaExpand{} `compare` CheckConstraint{} = LT 1300 CheckConstraint{} `compare` EtaExpand{} = GT 1301 1302-- | Frozen meta variable cannot be instantiated by unification. 1303-- This serves to prevent the completion of a definition by its use 1304-- outside of the current block. 1305-- (See issues 118, 288, 399). 1306data Frozen 1307 = Frozen -- ^ Do not instantiate. 1308 | Instantiable 1309 deriving (Eq, Show, Generic) 1310 1311data MetaInstantiation 1312 = InstV [Arg String] Term -- ^ solved by term (abstracted over some free variables) 1313 | Open -- ^ unsolved 1314 | OpenInstance -- ^ open, to be instantiated by instance search 1315 | BlockedConst Term -- ^ solution blocked by unsolved constraints 1316 | PostponedTypeCheckingProblem (Closure TypeCheckingProblem) 1317 deriving Generic 1318 1319-- | Solving a 'CheckArgs' constraint may or may not check the target type. If 1320-- it did, it returns a handle to any unsolved constraints. 1321data CheckedTarget = CheckedTarget (Maybe ProblemId) 1322 | NotCheckedTarget 1323 1324data PrincipalArgTypeMetas = PrincipalArgTypeMetas 1325 { patmMetas :: Args -- ^ metas created for hidden and instance arguments 1326 -- in the principal argument's type 1327 , patmRemainder :: Type -- ^ principal argument's type, stripped of hidden and 1328 -- instance arguments 1329 } 1330 deriving Generic 1331 1332data TypeCheckingProblem 1333 = CheckExpr Comparison A.Expr Type 1334 | CheckArgs Comparison ExpandHidden Range [NamedArg A.Expr] Type Type (ArgsCheckState CheckedTarget -> TCM Term) 1335 | CheckProjAppToKnownPrincipalArg Comparison A.Expr ProjOrigin (List1 QName) A.Args Type Int Term Type PrincipalArgTypeMetas 1336 | CheckLambda Comparison (Arg (List1 (WithHiding Name), Maybe Type)) A.Expr Type 1337 -- ^ @(λ (xs : t₀) → e) : t@ 1338 -- This is not an instance of 'CheckExpr' as the domain type 1339 -- has already been checked. 1340 -- For example, when checking 1341 -- @(λ (x y : Fin _) → e) : (x : Fin n) → ?@ 1342 -- we want to postpone @(λ (y : Fin n) → e) : ?@ where @Fin n@ 1343 -- is a 'Type' rather than an 'A.Expr'. 1344 | DoQuoteTerm Comparison Term Type -- ^ Quote the given term and check type against `Term` 1345 deriving Generic 1346 1347instance Show MetaInstantiation where 1348 show (InstV tel t) = "InstV " ++ show tel ++ " (" ++ show t ++ ")" 1349 show Open = "Open" 1350 show OpenInstance = "OpenInstance" 1351 show (BlockedConst t) = "BlockedConst (" ++ show t ++ ")" 1352 show (PostponedTypeCheckingProblem{}) = "PostponedTypeCheckingProblem (...)" 1353 1354-- | Meta variable priority: 1355-- When we have an equation between meta-variables, which one 1356-- should be instantiated? 1357-- 1358-- Higher value means higher priority to be instantiated. 1359newtype MetaPriority = MetaPriority Int 1360 deriving (Eq, Ord, Show, NFData) 1361 1362data RunMetaOccursCheck 1363 = RunMetaOccursCheck 1364 | DontRunMetaOccursCheck 1365 deriving (Eq, Ord, Show, Generic) 1366 1367-- | @MetaInfo@ is cloned from one meta to the next during pruning. 1368data MetaInfo = MetaInfo 1369 { miClosRange :: Closure Range -- TODO: Not so nice. But we want both to have the environment of the meta (Closure) and its range. 1370 , miModality :: Modality -- ^ Instantiable with irrelevant/erased solution? 1371 , miMetaOccursCheck :: RunMetaOccursCheck -- ^ Run the extended occurs check that goes in definitions? 1372 , miNameSuggestion :: MetaNameSuggestion 1373 -- ^ Used for printing. 1374 -- @Just x@ if meta-variable comes from omitted argument with name @x@. 1375 , miGeneralizable :: Arg DoGeneralize 1376 -- ^ Should this meta be generalized if unsolved? If so, at what ArgInfo? 1377 } 1378 deriving Generic 1379 1380instance LensModality MetaInfo where 1381 getModality = miModality 1382 setModality mod mi = mi { miModality = mod } 1383 mapModality f mi = mi { miModality = f $ miModality mi } 1384 1385instance LensQuantity MetaInfo where 1386 getQuantity = getQuantity . getModality 1387 mapQuantity f = mapModality (mapQuantity f) 1388 1389-- | Name suggestion for meta variable. Empty string means no suggestion. 1390type MetaNameSuggestion = String 1391 1392-- | For printing, we couple a meta with its name suggestion. 1393data NamedMeta = NamedMeta 1394 { nmSuggestion :: MetaNameSuggestion 1395 , nmid :: MetaId 1396 } 1397 1398instance Pretty NamedMeta where 1399 pretty (NamedMeta "" x) = pretty x 1400 pretty (NamedMeta "_" x) = pretty x 1401 pretty (NamedMeta s x) = text $ "_" ++ s ++ prettyShow x 1402 1403type MetaStore = IntMap MetaVariable 1404 1405instance HasRange MetaInfo where 1406 getRange = clValue . miClosRange 1407 1408instance HasRange MetaVariable where 1409 getRange m = getRange $ getMetaInfo m 1410 1411instance SetRange MetaInfo where 1412 setRange r m = m { miClosRange = (miClosRange m) { clValue = r }} 1413 1414instance SetRange MetaVariable where 1415 setRange r m = m { mvInfo = setRange r (mvInfo m) } 1416 1417instance LensModality MetaVariable where 1418 getModality = getModality . mvInfo 1419 setModality mod mv = mv { mvInfo = setModality mod $ mvInfo mv } 1420 mapModality f mv = mv { mvInfo = mapModality f $ mvInfo mv } 1421 1422instance LensQuantity MetaVariable where 1423 getQuantity = getQuantity . getModality 1424 mapQuantity f = mapModality (mapQuantity f) 1425 1426normalMetaPriority :: MetaPriority 1427normalMetaPriority = MetaPriority 0 1428 1429lowMetaPriority :: MetaPriority 1430lowMetaPriority = MetaPriority (-10) 1431 1432highMetaPriority :: MetaPriority 1433highMetaPriority = MetaPriority 10 1434 1435getMetaInfo :: MetaVariable -> Closure Range 1436getMetaInfo = miClosRange . mvInfo 1437 1438getMetaScope :: MetaVariable -> ScopeInfo 1439getMetaScope m = clScope $ getMetaInfo m 1440 1441getMetaEnv :: MetaVariable -> TCEnv 1442getMetaEnv m = clEnv $ getMetaInfo m 1443 1444getMetaSig :: MetaVariable -> Signature 1445getMetaSig m = clSignature $ getMetaInfo m 1446 1447getMetaRelevance :: MetaVariable -> Relevance 1448getMetaRelevance = getRelevance . getModality 1449 1450getMetaModality :: MetaVariable -> Modality 1451getMetaModality = getModality 1452 1453-- Lenses 1454 1455metaFrozen :: Lens' Frozen MetaVariable 1456metaFrozen f mv = f (mvFrozen mv) <&> \ x -> mv { mvFrozen = x } 1457 1458_mvInfo :: Lens' MetaInfo MetaVariable 1459_mvInfo f mv = (f $! mvInfo mv) <&> \ mi -> mv { mvInfo = mi } 1460 1461-- Lenses onto Closure Range 1462 1463instance LensClosure Range MetaInfo where 1464 lensClosure f mi = (f $! miClosRange mi) <&> \ cl -> mi { miClosRange = cl } 1465 1466instance LensClosure Range MetaVariable where 1467 lensClosure = _mvInfo . lensClosure 1468 1469-- Lenses onto IsAbstract 1470 1471instance LensIsAbstract TCEnv where 1472 lensIsAbstract f env = 1473 -- Andreas, 2019-08-19 1474 -- Using $! to prevent space leaks like #1829. 1475 -- This can crash when trying to get IsAbstract from IgnoreAbstractMode. 1476 (f $! fromMaybe __IMPOSSIBLE__ (aModeToDef $ envAbstractMode env)) 1477 <&> \ a -> env { envAbstractMode = aDefToMode a } 1478 1479instance LensIsAbstract (Closure a) where 1480 lensIsAbstract = lensTCEnv . lensIsAbstract 1481 1482instance LensIsAbstract MetaInfo where 1483 lensIsAbstract = lensClosure . lensIsAbstract 1484 1485--------------------------------------------------------------------------- 1486-- ** Interaction meta variables 1487--------------------------------------------------------------------------- 1488 1489-- | Interaction points are created by the scope checker who sets the range. 1490-- The meta variable is created by the type checker and then hooked up to the 1491-- interaction point. 1492data InteractionPoint = InteractionPoint 1493 { ipRange :: Range -- ^ The position of the interaction point. 1494 , ipMeta :: Maybe MetaId -- ^ The meta variable, if any, holding the type etc. 1495 , ipSolved:: Bool -- ^ Has this interaction point already been solved? 1496 , ipClause:: IPClause 1497 -- ^ The clause of the interaction point (if any). 1498 -- Used for case splitting. 1499 } 1500 deriving Generic 1501 1502instance Eq InteractionPoint where (==) = (==) `on` ipMeta 1503 1504instance HasTag InteractionPoint where 1505 type Tag InteractionPoint = MetaId 1506 tag = ipMeta 1507 1508-- | Data structure managing the interaction points. 1509-- 1510-- We never remove interaction points from this map, only set their 1511-- 'ipSolved' to @True@. (Issue #2368) 1512type InteractionPoints = BiMap InteractionId InteractionPoint 1513 1514-- | Flag to indicate whether the meta is overapplied in the 1515-- constraint. A meta is overapplied if it has more arguments than 1516-- the size of the telescope in its creation environment 1517-- (as stored in MetaInfo). 1518data Overapplied = Overapplied | NotOverapplied 1519 deriving (Eq, Show, Data, Generic) 1520 1521-- | Datatype representing a single boundary condition: 1522-- x_0 = u_0, ... ,x_n = u_n ⊢ t = ?n es 1523data IPBoundary' t = IPBoundary 1524 { ipbEquations :: [(t,t)] -- ^ [x_0 = u_0, ... ,x_n = u_n] 1525 , ipbValue :: t -- ^ @t@ 1526 , ipbMetaApp :: t -- ^ @?n es@ 1527 , ipbOverapplied :: Overapplied -- ^ Is @?n@ overapplied in @?n es@ ? 1528 } 1529 deriving (Show, Data, Functor, Foldable, Traversable, Generic) 1530 1531type IPBoundary = IPBoundary' Term 1532 1533-- | Which clause is an interaction point located in? 1534data IPClause = IPClause 1535 { ipcQName :: QName -- ^ The name of the function. 1536 , ipcClauseNo :: Int -- ^ The number of the clause of this function. 1537 , ipcType :: Type -- ^ The type of the function 1538 , ipcWithSub :: Maybe Substitution -- ^ Module parameter substitution 1539 , ipcClause :: A.SpineClause -- ^ The original AST clause. 1540 , ipcClosure :: Closure () -- ^ Environment for rechecking the clause. 1541 , ipcBoundary :: [Closure IPBoundary] -- ^ The boundary imposed by the LHS. 1542 } 1543 | IPNoClause -- ^ The interaction point is not in the rhs of a clause. 1544 deriving (Generic) 1545 1546instance Eq IPClause where 1547 IPNoClause == IPNoClause = True 1548 IPClause x i _ _ _ _ _ == IPClause x' i' _ _ _ _ _ = x == x' && i == i' 1549 _ == _ = False 1550 1551--------------------------------------------------------------------------- 1552-- ** Signature 1553--------------------------------------------------------------------------- 1554 1555data Signature = Sig 1556 { _sigSections :: Sections 1557 , _sigDefinitions :: Definitions 1558 , _sigRewriteRules:: RewriteRuleMap -- ^ The rewrite rules defined in this file. 1559 } 1560 deriving (Show, Generic) 1561 1562sigSections :: Lens' Sections Signature 1563sigSections f s = 1564 f (_sigSections s) <&> 1565 \x -> s {_sigSections = x} 1566 1567sigDefinitions :: Lens' Definitions Signature 1568sigDefinitions f s = 1569 f (_sigDefinitions s) <&> 1570 \x -> s {_sigDefinitions = x} 1571 1572sigRewriteRules :: Lens' RewriteRuleMap Signature 1573sigRewriteRules f s = 1574 f (_sigRewriteRules s) <&> 1575 \x -> s {_sigRewriteRules = x} 1576 1577type Sections = Map ModuleName Section 1578type Definitions = HashMap QName Definition 1579type RewriteRuleMap = HashMap QName RewriteRules 1580type DisplayForms = HashMap QName [LocalDisplayForm] 1581 1582newtype Section = Section { _secTelescope :: Telescope } 1583 deriving (Data, Show, NFData) 1584 1585instance Pretty Section where 1586 pretty = pretty . _secTelescope 1587 1588secTelescope :: Lens' Telescope Section 1589secTelescope f s = 1590 f (_secTelescope s) <&> 1591 \x -> s {_secTelescope = x} 1592 1593emptySignature :: Signature 1594emptySignature = Sig Map.empty HMap.empty HMap.empty 1595 1596-- | A @DisplayForm@ is in essence a rewrite rule @q ts --> dt@ for a defined symbol (could be a 1597-- constructor as well) @q@. The right hand side is a 'DisplayTerm' which is used to 'reify' to a 1598-- more readable 'Abstract.Syntax'. 1599-- 1600-- The patterns @ts@ are just terms, but the first @dfPatternVars@ variables are pattern variables 1601-- that matches any term. 1602data DisplayForm = Display 1603 { dfPatternVars :: Nat 1604 -- ^ Number @n@ of pattern variables in 'dfPats'. 1605 , dfPats :: Elims 1606 -- ^ Left hand side patterns, the @n@ first free variables are pattern variables, 1607 -- any variables above @n@ are fixed and only match that particular variable. This 1608 -- happens when you have display forms inside parameterised modules that match on the module 1609 -- parameters. The 'ArgInfo' is ignored in these patterns. 1610 , dfRHS :: DisplayTerm 1611 -- ^ Right hand side. 1612 } 1613 deriving (Data, Show, Generic) 1614 1615type LocalDisplayForm = Open DisplayForm 1616 1617-- | A structured presentation of a 'Term' for reification into 1618-- 'Abstract.Syntax'. 1619data DisplayTerm 1620 = DWithApp DisplayTerm [DisplayTerm] Elims 1621 -- ^ @(f vs | ws) es@. 1622 -- The first 'DisplayTerm' is the parent function @f@ with its args @vs@. 1623 -- The list of 'DisplayTerm's are the with expressions @ws@. 1624 -- The 'Elims' are additional arguments @es@ 1625 -- (possible in case the with-application is of function type) 1626 -- or projections (if it is of record type). 1627 | DCon ConHead ConInfo [Arg DisplayTerm] 1628 -- ^ @c vs@. 1629 | DDef QName [Elim' DisplayTerm] 1630 -- ^ @d vs@. 1631 | DDot Term 1632 -- ^ @.v@. 1633 | DTerm Term 1634 -- ^ @v@. 1635 deriving (Data, Show, Generic) 1636 1637instance Free DisplayForm where 1638 freeVars' (Display n ps t) = underBinder (freeVars' ps) `mappend` underBinder' n (freeVars' t) 1639 1640instance Free DisplayTerm where 1641 freeVars' (DWithApp t ws es) = freeVars' (t, (ws, es)) 1642 freeVars' (DCon _ _ vs) = freeVars' vs 1643 freeVars' (DDef _ es) = freeVars' es 1644 freeVars' (DDot v) = freeVars' v 1645 freeVars' (DTerm v) = freeVars' v 1646 1647instance Pretty DisplayTerm where 1648 prettyPrec p v = 1649 case v of 1650 DTerm v -> prettyPrec p v 1651 DDot v -> "." <> prettyPrec 10 v 1652 DDef f es -> pretty f `pApp` es 1653 DCon c _ vs -> pretty (conName c) `pApp` map Apply vs 1654 DWithApp h ws es -> 1655 mparens (p > 0) 1656 (sep [ pretty h 1657 , nest 2 $ fsep [ "|" <+> pretty w | w <- ws ] ]) 1658 `pApp` es 1659 where 1660 pApp :: Pretty el => Doc -> [el] -> Doc 1661 pApp d els = mparens (not (null els) && p > 9) $ 1662 sep [d, nest 2 $ fsep (map (prettyPrec 10) els)] 1663 1664instance Pretty DisplayForm where 1665 prettyPrec p (Display fv lhs rhs) = mparens (p > 9) $ 1666 "Display" <?> fsep [ pshow fv, prettyPrec 10 lhs, prettyPrec 10 rhs ] 1667 1668-- | By default, we have no display form. 1669defaultDisplayForm :: QName -> [LocalDisplayForm] 1670defaultDisplayForm c = [] 1671 1672-- | Non-linear (non-constructor) first-order pattern. 1673data NLPat 1674 = PVar !Int [Arg Int] 1675 -- ^ Matches anything (modulo non-linearity) that only contains bound 1676 -- variables that occur in the given arguments. 1677 | PDef QName PElims 1678 -- ^ Matches @f es@ 1679 | PLam ArgInfo (Abs NLPat) 1680 -- ^ Matches @λ x → t@ 1681 | PPi (Dom NLPType) (Abs NLPType) 1682 -- ^ Matches @(x : A) → B@ 1683 | PSort NLPSort 1684 -- ^ Matches a sort of the given shape. 1685 | PBoundVar {-# UNPACK #-} !Int PElims 1686 -- ^ Matches @x es@ where x is a lambda-bound variable 1687 | PTerm Term 1688 -- ^ Matches the term modulo β (ideally βη). 1689 deriving (Data, Show, Generic) 1690type PElims = [Elim' NLPat] 1691 1692data NLPType = NLPType 1693 { nlpTypeSort :: NLPSort 1694 , nlpTypeUnEl :: NLPat 1695 } deriving (Data, Show, Generic) 1696 1697data NLPSort 1698 = PType NLPat 1699 | PProp NLPat 1700 | PInf IsFibrant Integer 1701 | PSizeUniv 1702 | PLockUniv 1703 deriving (Data, Show, Generic) 1704 1705type RewriteRules = [RewriteRule] 1706 1707-- | Rewrite rules can be added independently from function clauses. 1708data RewriteRule = RewriteRule 1709 { rewName :: QName -- ^ Name of rewrite rule @q : Γ → f ps ≡ rhs@ 1710 -- where @≡@ is the rewrite relation. 1711 , rewContext :: Telescope -- ^ @Γ@. 1712 , rewHead :: QName -- ^ @f@. 1713 , rewPats :: PElims -- ^ @Γ ⊢ f ps : t@. 1714 , rewRHS :: Term -- ^ @Γ ⊢ rhs : t@. 1715 , rewType :: Type -- ^ @Γ ⊢ t@. 1716 , rewFromClause :: Bool -- ^ Was this rewrite rule created from a clause in the definition of the function? 1717 } 1718 deriving (Data, Show, Generic) 1719 1720data Definition = Defn 1721 { defArgInfo :: ArgInfo -- ^ Hiding should not be used. 1722 , defName :: QName -- ^ The canonical name, used e.g. in compilation. 1723 , defType :: Type -- ^ Type of the lifted definition. 1724 , defPolarity :: [Polarity] 1725 -- ^ Variance information on arguments of the definition. 1726 -- Does not include info for dropped parameters to 1727 -- projection(-like) functions and constructors. 1728 , defArgOccurrences :: [Occurrence] 1729 -- ^ Positivity information on arguments of the definition. 1730 -- Does not include info for dropped parameters to 1731 -- projection(-like) functions and constructors. 1732 1733 -- Sometimes Agda looks up 'Occurrence's in these lists based on 1734 -- their position, so one might consider replacing the list 1735 -- with, say, an 'IntMap'. However, presumably these lists tend 1736 -- to be short, in which case 'IntMap's could be slower than 1737 -- lists. For instance, at one point the longest list 1738 -- encountered for the standard library (in serialised 1739 -- interfaces) had length 27. Distribution: 1740 -- 1741 -- Length, number of lists 1742 -- ----------------------- 1743 -- 1744 -- 0, 2444 1745 -- 1, 721 1746 -- 2, 433 1747 -- 3, 668 1748 -- 4, 602 1749 -- 5, 624 1750 -- 6, 626 1751 -- 7, 484 1752 -- 8, 375 1753 -- 9, 264 1754 -- 10, 305 1755 -- 11, 188 1756 -- 12, 171 1757 -- 13, 108 1758 -- 14, 84 1759 -- 15, 80 1760 -- 16, 38 1761 -- 17, 23 1762 -- 18, 16 1763 -- 19, 8 1764 -- 20, 7 1765 -- 21, 5 1766 -- 22, 2 1767 -- 23, 3 1768 -- 27, 1 1769 1770 , defArgGeneralizable :: NumGeneralizableArgs 1771 -- ^ How many arguments should be generalised. 1772 , defGeneralizedParams :: [Maybe Name] 1773 -- ^ Gives the name of the (bound variable) parameter for named generalized 1774 -- parameters. This is needed to bring it into scope when type checking 1775 -- the data/record definition corresponding to a type with generalized 1776 -- parameters. 1777 , defDisplay :: [LocalDisplayForm] 1778 , defMutual :: MutualId 1779 , defCompiledRep :: CompiledRepresentation 1780 , defInstance :: Maybe QName 1781 -- ^ @Just q@ when this definition is an instance of class q 1782 , defCopy :: Bool 1783 -- ^ Has this function been created by a module 1784 -- instantiation? 1785 , defMatchable :: Set QName 1786 -- ^ The set of symbols with rewrite rules that match against this symbol 1787 , defNoCompilation :: Bool 1788 -- ^ should compilers skip this? Used for e.g. cubical's comp 1789 , defInjective :: Bool 1790 -- ^ Should the def be treated as injective by the pattern matching unifier? 1791 , defCopatternLHS :: Bool 1792 -- ^ Is this a function defined by copatterns? 1793 , defBlocked :: Blocked_ 1794 -- ^ What blocking tag to use when we cannot reduce this def? 1795 -- Used when checking a function definition is blocked on a meta 1796 -- in the type. 1797 , theDef :: Defn 1798 } 1799 deriving (Show, Generic) 1800 1801instance LensArgInfo Definition where 1802 getArgInfo = defArgInfo 1803 mapArgInfo f def = def { defArgInfo = f $ defArgInfo def } 1804 1805instance LensModality Definition where 1806instance LensQuantity Definition where 1807instance LensRelevance Definition where 1808 1809data NumGeneralizableArgs 1810 = NoGeneralizableArgs 1811 | SomeGeneralizableArgs !Int 1812 -- ^ When lambda-lifting new args are generalizable if 1813 -- 'SomeGeneralizableArgs', also when the number is zero. 1814 deriving (Data, Show) 1815 1816theDefLens :: Lens' Defn Definition 1817theDefLens f d = f (theDef d) <&> \ df -> d { theDef = df } 1818 1819-- | Create a definition with sensible defaults. 1820defaultDefn :: ArgInfo -> QName -> Type -> Defn -> Definition 1821defaultDefn info x t def = Defn 1822 { defArgInfo = info 1823 , defName = x 1824 , defType = t 1825 , defPolarity = [] 1826 , defArgOccurrences = [] 1827 , defArgGeneralizable = NoGeneralizableArgs 1828 , defGeneralizedParams = [] 1829 , defDisplay = defaultDisplayForm x 1830 , defMutual = 0 1831 , defCompiledRep = noCompiledRep 1832 , defInstance = Nothing 1833 , defCopy = False 1834 , defMatchable = Set.empty 1835 , defNoCompilation = False 1836 , defInjective = False 1837 , defCopatternLHS = False 1838 , defBlocked = NotBlocked ReallyNotBlocked () 1839 , theDef = def 1840 } 1841 1842-- | Polarity for equality and subtype checking. 1843data Polarity 1844 = Covariant -- ^ monotone 1845 | Contravariant -- ^ antitone 1846 | Invariant -- ^ no information (mixed variance) 1847 | Nonvariant -- ^ constant 1848 deriving (Data, Show, Eq, Generic) 1849 1850instance Pretty Polarity where 1851 pretty = text . \case 1852 Covariant -> "+" 1853 Contravariant -> "-" 1854 Invariant -> "*" 1855 Nonvariant -> "_" 1856 1857-- | Information about whether an argument is forced by the type of a function. 1858data IsForced 1859 = Forced 1860 | NotForced 1861 deriving (Data, Show, Eq, Generic) 1862 1863-- | The backends are responsible for parsing their own pragmas. 1864data CompilerPragma = CompilerPragma Range String 1865 deriving (Data, Show, Eq, Generic) 1866 1867instance HasRange CompilerPragma where 1868 getRange (CompilerPragma r _) = r 1869 1870type BackendName = String 1871 1872jsBackendName, ghcBackendName :: BackendName 1873jsBackendName = "JS" 1874ghcBackendName = "GHC" 1875 1876type CompiledRepresentation = Map BackendName [CompilerPragma] 1877 1878noCompiledRep :: CompiledRepresentation 1879noCompiledRep = Map.empty 1880 1881-- A face represented as a list of equality constraints. 1882-- (r,False) ↦ (r = i0) 1883-- (r,True ) ↦ (r = i1) 1884type Face = [(Term,Bool)] 1885 1886-- | An alternative representation of partial elements in a telescope: 1887-- Γ ⊢ λ Δ. [φ₁ u₁, ... , φₙ uₙ] : Δ → PartialP (∨_ᵢ φᵢ) T 1888-- see cubicaltt paper (however we do not store the type T). 1889data System = System 1890 { systemTel :: Telescope 1891 -- ^ the telescope Δ, binding vars for the clauses, Γ ⊢ Δ 1892 , systemClauses :: [(Face,Term)] 1893 -- ^ a system [φ₁ u₁, ... , φₙ uₙ] where Γ, Δ ⊢ φᵢ and Γ, Δ, φᵢ ⊢ uᵢ 1894 } deriving (Data, Show, Generic) 1895 1896-- | Additional information for extended lambdas. 1897data ExtLamInfo = ExtLamInfo 1898 { extLamModule :: ModuleName 1899 -- ^ For complicated reasons the scope checker decides the QName of a 1900 -- pattern lambda, and thus its module. We really need to decide the 1901 -- module during type checking though, since if the lambda appears in a 1902 -- refined context the module picked by the scope checker has very much 1903 -- the wrong parameters. 1904 , extLamAbsurd :: Bool 1905 -- ^ Was this definition created from an absurd lambda @λ ()@? 1906 , extLamSys :: !(Strict.Maybe System) 1907 } deriving (Data, Show, Generic) 1908 1909modifySystem :: (System -> System) -> ExtLamInfo -> ExtLamInfo 1910modifySystem f e = let !e' = e { extLamSys = f <$> extLamSys e } in e' 1911 1912-- | Additional information for projection 'Function's. 1913data Projection = Projection 1914 { projProper :: Maybe QName 1915 -- ^ @Nothing@ if only projection-like, @Just r@ if record projection. 1916 -- The @r@ is the name of the record type projected from. 1917 -- This field is updated by module application. 1918 , projOrig :: QName 1919 -- ^ The original projection name 1920 -- (current name could be from module application). 1921 , projFromType :: Arg QName 1922 -- ^ Type projected from. Original record type if @projProper = Just{}@. 1923 -- Also stores @ArgInfo@ of the principal argument. 1924 -- This field is unchanged by module application. 1925 , projIndex :: Int 1926 -- ^ Index of the record argument. 1927 -- Start counting with 1, because 0 means that 1928 -- it is already applied to the record value. 1929 -- This can happen in module instantiation, but 1930 -- then either the record value is @var 0@, or @funProjection == Nothing@. 1931 , projLams :: ProjLams 1932 -- ^ Term @t@ to be be applied to record parameters and record value. 1933 -- The parameters will be dropped. 1934 -- In case of a proper projection, a postfix projection application 1935 -- will be created: @t = \ pars r -> r .p@ 1936 -- (Invariant: the number of abstractions equals 'projIndex'.) 1937 -- In case of a projection-like function, just the function symbol 1938 -- is returned as 'Def': @t = \ pars -> f@. 1939 } deriving (Data, Show, Generic) 1940 1941-- | Abstractions to build projection function (dropping parameters). 1942newtype ProjLams = ProjLams { getProjLams :: [Arg ArgName] } 1943 deriving (Data, Show, Null, Generic) 1944 1945-- | Building the projection function (which drops the parameters). 1946projDropPars :: Projection -> ProjOrigin -> Term 1947-- Proper projections: 1948projDropPars (Projection Just{} d _ _ lams) o = 1949 case initLast $ getProjLams lams of 1950 Nothing -> Def d [] 1951 Just (pars, Arg i y) -> 1952 let core = Lam i $ Abs y $ Var 0 [Proj o d] in 1953 List.foldr (\ (Arg ai x) -> Lam ai . NoAbs x) core pars 1954-- Projection-like functions: 1955projDropPars (Projection Nothing d _ _ lams) o = 1956 List.foldr (\ (Arg ai x) -> Lam ai . NoAbs x) (Def d []) $ 1957 initWithDefault __IMPOSSIBLE__ $ getProjLams lams 1958 1959-- | The info of the principal (record) argument. 1960projArgInfo :: Projection -> ArgInfo 1961projArgInfo (Projection _ _ _ _ lams) = 1962 maybe __IMPOSSIBLE__ getArgInfo $ lastMaybe $ getProjLams lams 1963 1964-- | Should a record type admit eta-equality? 1965data EtaEquality 1966 = Specified { theEtaEquality :: !HasEta } -- ^ User specifed 'eta-equality' or 'no-eta-equality'. 1967 | Inferred { theEtaEquality :: !HasEta } -- ^ Positivity checker inferred whether eta is safe. 1968 deriving (Data, Show, Eq, Generic) 1969 1970instance PatternMatchingAllowed EtaEquality where 1971 patternMatchingAllowed = patternMatchingAllowed . theEtaEquality 1972 1973instance CopatternMatchingAllowed EtaEquality where 1974 copatternMatchingAllowed = copatternMatchingAllowed . theEtaEquality 1975 1976-- | Make sure we do not overwrite a user specification. 1977setEtaEquality :: EtaEquality -> HasEta -> EtaEquality 1978setEtaEquality e@Specified{} _ = e 1979setEtaEquality _ b = Inferred b 1980 1981data FunctionFlag 1982 = FunStatic -- ^ Should calls to this function be normalised at compile-time? 1983 | FunInline -- ^ Should calls to this function be inlined by the compiler? 1984 | FunMacro -- ^ Is this function a macro? 1985 deriving (Data, Eq, Ord, Enum, Show, Generic) 1986 1987data CompKit = CompKit 1988 { nameOfHComp :: Maybe QName 1989 , nameOfTransp :: Maybe QName 1990 } 1991 deriving (Data, Eq, Ord, Show, Generic) 1992 1993emptyCompKit :: CompKit 1994emptyCompKit = CompKit Nothing Nothing 1995 1996defaultAxiom :: Defn 1997defaultAxiom = Axiom False 1998 1999constTranspAxiom :: Defn 2000constTranspAxiom = Axiom True 2001 2002data Defn = Axiom -- ^ Postulate 2003 { axiomConstTransp :: Bool 2004 -- ^ Can transp for this postulate be constant? 2005 -- Set to @True@ for bultins like String. 2006 } 2007 | DataOrRecSig 2008 { datarecPars :: Int } 2009 -- ^ Data or record type signature that doesn't yet have a definition 2010 | GeneralizableVar -- ^ Generalizable variable (introduced in `generalize` block) 2011 | AbstractDefn Defn 2012 -- ^ Returned by 'getConstInfo' if definition is abstract. 2013 | Function 2014 { funClauses :: [Clause] 2015 , funCompiled :: Maybe CompiledClauses 2016 -- ^ 'Nothing' while function is still type-checked. 2017 -- @Just cc@ after type and coverage checking and 2018 -- translation to case trees. 2019 , funSplitTree :: Maybe SplitTree 2020 -- ^ The split tree constructed by the coverage 2021 -- checker. Needed to re-compile the clauses after 2022 -- forcing translation. 2023 , funTreeless :: Maybe Compiled 2024 -- ^ Intermediate representation for compiler backends. 2025 , funCovering :: [Clause] 2026 -- ^ Covering clauses computed by coverage checking. 2027 -- Erased by (IApply) confluence checking(?) 2028 , funInv :: FunctionInverse 2029 , funMutual :: Maybe [QName] 2030 -- ^ Mutually recursive functions, @data@s and @record@s. 2031 -- Does include this function. 2032 -- Empty list if not recursive. 2033 -- @Nothing@ if not yet computed (by positivity checker). 2034 , funAbstr :: IsAbstract 2035 , funDelayed :: Delayed 2036 -- ^ Are the clauses of this definition delayed? 2037 , funProjection :: Maybe Projection 2038 -- ^ Is it a record projection? 2039 -- If yes, then return the name of the record type and index of 2040 -- the record argument. Start counting with 1, because 0 means that 2041 -- it is already applied to the record. (Can happen in module 2042 -- instantiation.) This information is used in the termination 2043 -- checker. 2044 , funFlags :: Set FunctionFlag 2045 , funTerminates :: Maybe Bool 2046 -- ^ Has this function been termination checked? Did it pass? 2047 , funExtLam :: Maybe ExtLamInfo 2048 -- ^ Is this function generated from an extended lambda? 2049 -- If yes, then return the number of hidden and non-hidden lambda-lifted arguments 2050 , funWith :: Maybe QName 2051 -- ^ Is this a generated with-function? If yes, then what's the 2052 -- name of the parent function. 2053 } 2054 | Datatype 2055 { dataPars :: Nat -- ^ Number of parameters. 2056 , dataIxs :: Nat -- ^ Number of indices. 2057 , dataClause :: (Maybe Clause) -- ^ This might be in an instantiated module. 2058 , dataCons :: [QName] 2059 -- ^ Constructor names , ordered according to the order of their definition. 2060 , dataSort :: Sort 2061 , dataMutual :: Maybe [QName] 2062 -- ^ Mutually recursive functions, @data@s and @record@s. 2063 -- Does include this data type. 2064 -- Empty if not recursive. 2065 -- @Nothing@ if not yet computed (by positivity checker). 2066 , dataAbstr :: IsAbstract 2067 , dataPathCons :: [QName] -- ^ Path constructor names (subset of dataCons) 2068 } 2069 | Record 2070 { recPars :: Nat 2071 -- ^ Number of parameters. 2072 , recClause :: Maybe Clause 2073 -- ^ Was this record type created by a module application? 2074 -- If yes, the clause is its definition (linking back to the original record type). 2075 , recConHead :: ConHead 2076 -- ^ Constructor name and fields. 2077 , recNamedCon :: Bool 2078 -- ^ Does this record have a @constructor@? 2079 , recFields :: [Dom QName] 2080 -- ^ The record field names. 2081 , recTel :: Telescope 2082 -- ^ The record field telescope. (Includes record parameters.) 2083 -- Note: @TelV recTel _ == telView' recConType@. 2084 -- Thus, @recTel@ is redundant. 2085 , recMutual :: Maybe [QName] 2086 -- ^ Mutually recursive functions, @data@s and @record@s. 2087 -- Does include this record. 2088 -- Empty if not recursive. 2089 -- @Nothing@ if not yet computed (by positivity checker). 2090 , recEtaEquality' :: EtaEquality 2091 -- ^ Eta-expand at this record type? 2092 -- @False@ for unguarded recursive records and coinductive records 2093 -- unless the user specifies otherwise. 2094 , recPatternMatching :: PatternOrCopattern 2095 -- ^ In case eta-equality is off, do we allow pattern matching on the 2096 -- constructor or construction by copattern matching? 2097 -- Having both loses subject reduction, see issue #4560. 2098 -- After positivity checking, this field is obsolete, part of 'EtaEquality'. 2099 , recInduction :: Maybe Induction 2100 -- ^ 'Inductive' or 'CoInductive'? Matters only for recursive records. 2101 -- 'Nothing' means that the user did not specify it, which is an error 2102 -- for recursive records. 2103 , recAbstr :: IsAbstract 2104 , recComp :: CompKit 2105 } 2106 | Constructor 2107 { conPars :: Int -- ^ Number of parameters. 2108 , conArity :: Int -- ^ Number of arguments (excluding parameters). 2109 , conSrcCon :: ConHead -- ^ Name of (original) constructor and fields. (This might be in a module instance.) 2110 , conData :: QName -- ^ Name of datatype or record type. 2111 , conAbstr :: IsAbstract 2112 , conInd :: Induction -- ^ Inductive or coinductive? 2113 , conComp :: CompKit -- ^ Cubical composition. 2114 , conProj :: Maybe [QName] -- ^ Projections. 'Nothing' if not yet computed. 2115 , conForced :: [IsForced] 2116 -- ^ Which arguments are forced (i.e. determined by the type of the constructor)? 2117 -- Either this list is empty (if the forcing analysis isn't run), or its length is @conArity@. 2118 , conErased :: Maybe [Bool] 2119 -- ^ Which arguments are erased at runtime (computed during compilation to treeless)? 2120 -- 'True' means erased, 'False' means retained. 2121 -- 'Nothing' if no erasure analysis has been performed yet. 2122 -- The length of the list is @conArity@. 2123 } 2124 | Primitive -- ^ Primitive or builtin functions. 2125 { primAbstr :: IsAbstract 2126 , primName :: String 2127 , primClauses :: [Clause] 2128 -- ^ 'null' for primitive functions, @not null@ for builtin functions. 2129 , primInv :: FunctionInverse 2130 -- ^ Builtin functions can have inverses. For instance, natural number addition. 2131 , primCompiled :: Maybe CompiledClauses 2132 -- ^ 'Nothing' for primitive functions, 2133 -- @'Just' something@ for builtin functions. 2134 } 2135 | PrimitiveSort 2136 { primName :: String 2137 , primSort :: Sort 2138 } 2139 deriving (Data, Show, Generic) 2140 2141instance Pretty Definition where 2142 pretty Defn{..} = 2143 "Defn {" <?> vcat 2144 [ "defArgInfo =" <?> pshow defArgInfo 2145 , "defName =" <?> pretty defName 2146 , "defType =" <?> pretty defType 2147 , "defPolarity =" <?> pshow defPolarity 2148 , "defArgOccurrences =" <?> pshow defArgOccurrences 2149 , "defGeneralizedParams =" <?> pshow defGeneralizedParams 2150 , "defDisplay =" <?> pretty defDisplay 2151 , "defMutual =" <?> pshow defMutual 2152 , "defCompiledRep =" <?> pshow defCompiledRep 2153 , "defInstance =" <?> pshow defInstance 2154 , "defCopy =" <?> pshow defCopy 2155 , "defMatchable =" <?> pshow (Set.toList defMatchable) 2156 , "defInjective =" <?> pshow defInjective 2157 , "defCopatternLHS =" <?> pshow defCopatternLHS 2158 , "theDef =" <?> pretty theDef ] <+> "}" 2159 2160instance Pretty Defn where 2161 pretty Axiom{} = "Axiom" 2162 pretty (DataOrRecSig n) = "DataOrRecSig" <+> pretty n 2163 pretty GeneralizableVar{} = "GeneralizableVar" 2164 pretty (AbstractDefn def) = "AbstractDefn" <?> parens (pretty def) 2165 pretty Function{..} = 2166 "Function {" <?> vcat 2167 [ "funClauses =" <?> vcat (map pretty funClauses) 2168 , "funCompiled =" <?> pretty funCompiled 2169 , "funSplitTree =" <?> pretty funSplitTree 2170 , "funTreeless =" <?> pshow funTreeless 2171 , "funInv =" <?> pretty funInv 2172 , "funMutual =" <?> pshow funMutual 2173 , "funAbstr =" <?> pshow funAbstr 2174 , "funDelayed =" <?> pshow funDelayed 2175 , "funProjection =" <?> pretty funProjection 2176 , "funFlags =" <?> pshow funFlags 2177 , "funTerminates =" <?> pshow funTerminates 2178 , "funWith =" <?> pretty funWith ] <?> "}" 2179 pretty Datatype{..} = 2180 "Datatype {" <?> vcat 2181 [ "dataPars =" <?> pshow dataPars 2182 , "dataIxs =" <?> pshow dataIxs 2183 , "dataClause =" <?> pretty dataClause 2184 , "dataCons =" <?> pshow dataCons 2185 , "dataSort =" <?> pretty dataSort 2186 , "dataMutual =" <?> pshow dataMutual 2187 , "dataAbstr =" <?> pshow dataAbstr ] <?> "}" 2188 pretty Record{..} = 2189 "Record {" <?> vcat 2190 [ "recPars =" <?> pshow recPars 2191 , "recClause =" <?> pretty recClause 2192 , "recConHead =" <?> pretty recConHead 2193 , "recNamedCon =" <?> pretty recNamedCon 2194 , "recFields =" <?> pretty recFields 2195 , "recTel =" <?> pretty recTel 2196 , "recMutual =" <?> pshow recMutual 2197 , "recEtaEquality' =" <?> pshow recEtaEquality' 2198 , "recInduction =" <?> pshow recInduction 2199 , "recAbstr =" <?> pshow recAbstr ] <?> "}" 2200 pretty Constructor{..} = 2201 "Constructor {" <?> vcat 2202 [ "conPars =" <?> pshow conPars 2203 , "conArity =" <?> pshow conArity 2204 , "conSrcCon =" <?> pshow conSrcCon 2205 , "conData =" <?> pshow conData 2206 , "conAbstr =" <?> pshow conAbstr 2207 , "conInd =" <?> pshow conInd 2208 , "conErased =" <?> pshow conErased ] <?> "}" 2209 pretty Primitive{..} = 2210 "Primitive {" <?> vcat 2211 [ "primAbstr =" <?> pshow primAbstr 2212 , "primName =" <?> pshow primName 2213 , "primClauses =" <?> pshow primClauses 2214 , "primCompiled =" <?> pshow primCompiled ] <?> "}" 2215 pretty PrimitiveSort{..} = 2216 "PrimitiveSort {" <?> vcat 2217 [ "primName =" <?> pshow primName 2218 , "primSort =" <?> pshow primSort 2219 ] <?> "}" 2220 2221instance Pretty Projection where 2222 pretty Projection{..} = 2223 "Projection {" <?> vcat 2224 [ "projProper =" <?> pretty projProper 2225 , "projOrig =" <?> pretty projOrig 2226 , "projFromType =" <?> pretty projFromType 2227 , "projIndex =" <?> pshow projIndex 2228 , "projLams =" <?> pretty projLams 2229 ] 2230 2231instance Pretty c => Pretty (FunctionInverse' c) where 2232 pretty NotInjective = "NotInjective" 2233 pretty (Inverse inv) = "Inverse" <?> 2234 vcat [ pretty h <+> "->" <?> pretty cs 2235 | (h, cs) <- Map.toList inv ] 2236 2237instance Pretty ProjLams where 2238 pretty (ProjLams args) = pretty args 2239 2240-- | Is the record type recursive? 2241recRecursive :: Defn -> Bool 2242recRecursive (Record { recMutual = Just qs }) = not $ null qs 2243recRecursive _ = __IMPOSSIBLE__ 2244 2245recEtaEquality :: Defn -> HasEta 2246recEtaEquality = theEtaEquality . recEtaEquality' 2247 2248-- | A template for creating 'Function' definitions, with sensible defaults. 2249emptyFunction :: Defn 2250emptyFunction = Function 2251 { funClauses = [] 2252 , funCompiled = Nothing 2253 , funSplitTree = Nothing 2254 , funTreeless = Nothing 2255 , funInv = NotInjective 2256 , funMutual = Nothing 2257 , funAbstr = ConcreteDef 2258 , funDelayed = NotDelayed 2259 , funProjection = Nothing 2260 , funFlags = Set.empty 2261 , funTerminates = Nothing 2262 , funExtLam = Nothing 2263 , funWith = Nothing 2264 , funCovering = [] 2265 } 2266 2267funFlag :: FunctionFlag -> Lens' Bool Defn 2268funFlag flag f def@Function{ funFlags = flags } = 2269 f (Set.member flag flags) <&> 2270 \ b -> def{ funFlags = (if b then Set.insert else Set.delete) flag flags } 2271funFlag _ f def = f False $> def 2272 2273funStatic, funInline, funMacro :: Lens' Bool Defn 2274funStatic = funFlag FunStatic 2275funInline = funFlag FunInline 2276funMacro = funFlag FunMacro 2277 2278isMacro :: Defn -> Bool 2279isMacro = (^. funMacro) 2280 2281-- | Checking whether we are dealing with a function yet to be defined. 2282isEmptyFunction :: Defn -> Bool 2283isEmptyFunction def = 2284 case def of 2285 Function { funClauses = [] } -> True 2286 _ -> False 2287 2288isCopatternLHS :: [Clause] -> Bool 2289isCopatternLHS = List.any (List.any (isJust . A.isProjP) . namedClausePats) 2290 2291recCon :: Defn -> QName 2292recCon Record{ recConHead } = conName recConHead 2293recCon _ = __IMPOSSIBLE__ 2294 2295defIsRecord :: Defn -> Bool 2296defIsRecord Record{} = True 2297defIsRecord _ = False 2298 2299defIsDataOrRecord :: Defn -> Bool 2300defIsDataOrRecord Record{} = True 2301defIsDataOrRecord Datatype{} = True 2302defIsDataOrRecord _ = False 2303 2304defConstructors :: Defn -> [QName] 2305defConstructors Datatype{dataCons = cs} = cs 2306defConstructors Record{recConHead = c} = [conName c] 2307defConstructors _ = __IMPOSSIBLE__ 2308 2309newtype Fields = Fields [(C.Name, Type)] 2310 deriving Null 2311 2312-- | Did we encounter a simplifying reduction? 2313-- In terms of CIC, that would be a iota-reduction. 2314-- In terms of Agda, this is a constructor or literal 2315-- pattern that matched. 2316-- Just beta-reduction (substitution) or delta-reduction 2317-- (unfolding of definitions) does not count as simplifying? 2318 2319data Simplification = YesSimplification | NoSimplification 2320 deriving (Data, Eq, Show, Generic) 2321 2322instance Null Simplification where 2323 empty = NoSimplification 2324 null = (== NoSimplification) 2325 2326instance Semigroup Simplification where 2327 YesSimplification <> _ = YesSimplification 2328 NoSimplification <> s = s 2329 2330instance Monoid Simplification where 2331 mempty = NoSimplification 2332 mappend = (<>) 2333 2334data Reduced no yes 2335 = NoReduction no 2336 | YesReduction Simplification yes 2337 deriving Functor 2338 2339redReturn :: a -> ReduceM (Reduced a' a) 2340redReturn = return . YesReduction YesSimplification 2341 2342-- | Conceptually: @redBind m f k = either (return . Left . f) k =<< m@ 2343 2344redBind :: ReduceM (Reduced a a') -> (a -> b) -> 2345 (a' -> ReduceM (Reduced b b')) -> ReduceM (Reduced b b') 2346redBind ma f k = do 2347 r <- ma 2348 case r of 2349 NoReduction x -> return $ NoReduction $ f x 2350 YesReduction _ y -> k y 2351 2352-- | Three cases: 1. not reduced, 2. reduced, but blocked, 3. reduced, not blocked. 2353data IsReduced 2354 = NotReduced 2355 | Reduced (Blocked ()) 2356 2357data MaybeReduced a = MaybeRed 2358 { isReduced :: IsReduced 2359 , ignoreReduced :: a 2360 } 2361 deriving (Functor) 2362 2363instance IsProjElim e => IsProjElim (MaybeReduced e) where 2364 isProjElim = isProjElim . ignoreReduced 2365 2366type MaybeReducedArgs = [MaybeReduced (Arg Term)] 2367type MaybeReducedElims = [MaybeReduced Elim] 2368 2369notReduced :: a -> MaybeReduced a 2370notReduced x = MaybeRed NotReduced x 2371 2372reduced :: Blocked (Arg Term) -> MaybeReduced (Arg Term) 2373reduced b = MaybeRed (Reduced $ () <$ b) $ ignoreBlocking b 2374 2375-- | Controlling 'reduce'. 2376data AllowedReduction 2377 = ProjectionReductions -- ^ (Projection and) projection-like functions may be reduced. 2378 | InlineReductions -- ^ Functions marked INLINE may be reduced. 2379 | CopatternReductions -- ^ Copattern definitions may be reduced. 2380 | FunctionReductions -- ^ Non-recursive functions and primitives may be reduced. 2381 | RecursiveReductions -- ^ Even recursive functions may be reduced. 2382 | LevelReductions -- ^ Reduce @'Level'@ terms. 2383 | TypeLevelReductions -- ^ Allow @allReductions@ in types, even 2384 -- if not allowed at term level (used 2385 -- by confluence checker) 2386 | UnconfirmedReductions -- ^ Functions whose termination has not (yet) been confirmed. 2387 | NonTerminatingReductions -- ^ Functions that have failed termination checking. 2388 deriving (Show, Eq, Ord, Enum, Bounded, Ix, Data, Generic) 2389 2390type AllowedReductions = SmallSet AllowedReduction 2391 2392-- | Not quite all reductions (skip non-terminating reductions) 2393allReductions :: AllowedReductions 2394allReductions = SmallSet.delete NonTerminatingReductions reallyAllReductions 2395 2396reallyAllReductions :: AllowedReductions 2397reallyAllReductions = SmallSet.total 2398 2399data ReduceDefs 2400 = OnlyReduceDefs (Set QName) 2401 | DontReduceDefs (Set QName) 2402 deriving (Data, Generic) 2403 2404reduceAllDefs :: ReduceDefs 2405reduceAllDefs = DontReduceDefs empty 2406 2407locallyReduceDefs :: MonadTCEnv m => ReduceDefs -> m a -> m a 2408locallyReduceDefs = locallyTC eReduceDefs . const 2409 2410locallyReduceAllDefs :: MonadTCEnv m => m a -> m a 2411locallyReduceAllDefs = locallyReduceDefs reduceAllDefs 2412 2413shouldReduceDef :: (MonadTCEnv m) => QName -> m Bool 2414shouldReduceDef f = asksTC envReduceDefs <&> \case 2415 OnlyReduceDefs defs -> f `Set.member` defs 2416 DontReduceDefs defs -> not $ f `Set.member` defs 2417 2418instance Semigroup ReduceDefs where 2419 OnlyReduceDefs qs1 <> OnlyReduceDefs qs2 = OnlyReduceDefs $ Set.intersection qs1 qs2 2420 OnlyReduceDefs qs1 <> DontReduceDefs qs2 = OnlyReduceDefs $ Set.difference qs1 qs2 2421 DontReduceDefs qs1 <> OnlyReduceDefs qs2 = OnlyReduceDefs $ Set.difference qs2 qs1 2422 DontReduceDefs qs1 <> DontReduceDefs qs2 = DontReduceDefs $ Set.union qs1 qs2 2423 2424instance Monoid ReduceDefs where 2425 mempty = reduceAllDefs 2426 mappend = (<>) 2427 2428 2429locallyReconstructed :: MonadTCEnv m => m a -> m a 2430locallyReconstructed = locallyTC eReconstructed . const $ True 2431 2432isReconstructed :: (MonadTCEnv m) => m Bool 2433isReconstructed = asksTC envReconstructed 2434 2435-- | Primitives 2436 2437data PrimitiveImpl = PrimImpl Type PrimFun 2438 2439data PrimFun = PrimFun 2440 { primFunName :: QName 2441 , primFunArity :: Arity 2442 , primFunImplementation :: [Arg Term] -> Int -> ReduceM (Reduced MaybeReducedArgs Term) 2443 } 2444 deriving Generic 2445 2446primFun :: QName -> Arity -> ([Arg Term] -> ReduceM (Reduced MaybeReducedArgs Term)) -> PrimFun 2447primFun q ar imp = PrimFun q ar (\ args _ -> imp args) 2448 2449defClauses :: Definition -> [Clause] 2450defClauses Defn{theDef = Function{funClauses = cs}} = cs 2451defClauses Defn{theDef = Primitive{primClauses = cs}} = cs 2452defClauses Defn{theDef = Datatype{dataClause = Just c}} = [c] 2453defClauses Defn{theDef = Record{recClause = Just c}} = [c] 2454defClauses _ = [] 2455 2456defCompiled :: Definition -> Maybe CompiledClauses 2457defCompiled Defn{theDef = Function {funCompiled = mcc}} = mcc 2458defCompiled Defn{theDef = Primitive{primCompiled = mcc}} = mcc 2459defCompiled _ = Nothing 2460 2461defParameters :: Definition -> Maybe Nat 2462defParameters Defn{theDef = Datatype{dataPars = n}} = Just n 2463defParameters Defn{theDef = Record {recPars = n}} = Just n 2464defParameters _ = Nothing 2465 2466defInverse :: Definition -> FunctionInverse 2467defInverse Defn{theDef = Function { funInv = inv }} = inv 2468defInverse Defn{theDef = Primitive{ primInv = inv }} = inv 2469defInverse _ = NotInjective 2470 2471defCompilerPragmas :: BackendName -> Definition -> [CompilerPragma] 2472defCompilerPragmas b = reverse . fromMaybe [] . Map.lookup b . defCompiledRep 2473 -- reversed because we add new pragmas to the front of the list 2474 2475-- | Are the clauses of this definition delayed? 2476defDelayed :: Definition -> Delayed 2477defDelayed Defn{theDef = Function{funDelayed = d}} = d 2478defDelayed _ = NotDelayed 2479 2480-- | Has the definition failed the termination checker? 2481defNonterminating :: Definition -> Bool 2482defNonterminating Defn{theDef = Function{funTerminates = Just False}} = True 2483defNonterminating _ = False 2484 2485-- | Has the definition not termination checked or did the check fail? 2486defTerminationUnconfirmed :: Definition -> Bool 2487defTerminationUnconfirmed Defn{theDef = Function{funTerminates = Just True}} = False 2488defTerminationUnconfirmed Defn{theDef = Function{funTerminates = _ }} = True 2489defTerminationUnconfirmed _ = False 2490 2491defAbstract :: Definition -> IsAbstract 2492defAbstract d = case theDef d of 2493 Axiom{} -> ConcreteDef 2494 DataOrRecSig{} -> ConcreteDef 2495 GeneralizableVar{} -> ConcreteDef 2496 AbstractDefn{} -> AbstractDef 2497 Function{funAbstr = a} -> a 2498 Datatype{dataAbstr = a} -> a 2499 Record{recAbstr = a} -> a 2500 Constructor{conAbstr = a} -> a 2501 Primitive{primAbstr = a} -> a 2502 PrimitiveSort{} -> ConcreteDef 2503 2504defForced :: Definition -> [IsForced] 2505defForced d = case theDef d of 2506 Constructor{conForced = fs} -> fs 2507 Axiom{} -> [] 2508 DataOrRecSig{} -> [] 2509 GeneralizableVar{} -> [] 2510 AbstractDefn{} -> [] 2511 Function{} -> [] 2512 Datatype{} -> [] 2513 Record{} -> [] 2514 Primitive{} -> [] 2515 PrimitiveSort{} -> [] 2516 2517--------------------------------------------------------------------------- 2518-- ** Injectivity 2519--------------------------------------------------------------------------- 2520 2521type FunctionInverse = FunctionInverse' Clause 2522type InversionMap c = Map TermHead [c] 2523 2524data FunctionInverse' c 2525 = NotInjective 2526 | Inverse (InversionMap c) 2527 deriving (Data, Show, Functor, Generic) 2528 2529data TermHead = SortHead 2530 | PiHead 2531 | ConsHead QName 2532 | VarHead Nat 2533 | UnknownHead 2534 deriving (Data, Eq, Ord, Show, Generic) 2535 2536instance Pretty TermHead where 2537 pretty = \ case 2538 SortHead -> "SortHead" 2539 PiHead -> "PiHead" 2540 ConsHead q -> "ConsHead" <+> pretty q 2541 VarHead i -> text ("VarHead " ++ show i) 2542 UnknownHead -> "UnknownHead" 2543 2544--------------------------------------------------------------------------- 2545-- ** Mutual blocks 2546--------------------------------------------------------------------------- 2547 2548newtype MutualId = MutId Int32 2549 deriving (Data, Eq, Ord, Show, Num, Enum, NFData) 2550 2551--------------------------------------------------------------------------- 2552-- ** Statistics 2553--------------------------------------------------------------------------- 2554 2555type Statistics = Map String Integer 2556 2557--------------------------------------------------------------------------- 2558-- ** Trace 2559--------------------------------------------------------------------------- 2560 2561data Call 2562 = CheckClause Type A.SpineClause 2563 | CheckLHS A.SpineLHS 2564 | CheckPattern A.Pattern Telescope Type 2565 | CheckPatternLinearityType C.Name 2566 | CheckPatternLinearityValue C.Name 2567 | CheckLetBinding A.LetBinding 2568 | InferExpr A.Expr 2569 | CheckExprCall Comparison A.Expr Type 2570 | CheckDotPattern A.Expr Term 2571 | CheckProjection Range QName Type 2572 | IsTypeCall Comparison A.Expr Sort 2573 | IsType_ A.Expr 2574 | InferVar Name 2575 | InferDef QName 2576 | CheckArguments Range [NamedArg A.Expr] Type (Maybe Type) 2577 | CheckMetaSolution Range MetaId Type Term 2578 | CheckTargetType Range Type Type 2579 | CheckDataDef Range QName [A.LamBinding] [A.Constructor] 2580 | CheckRecDef Range QName [A.LamBinding] [A.Constructor] 2581 | CheckConstructor QName Telescope Sort A.Constructor 2582 | CheckConstructorFitsIn QName Type Sort 2583 | CheckFunDefCall Range QName [A.Clause] Bool 2584 -- ^ Highlight (interactively) if and only if the boolean is 'True'. 2585 | CheckPragma Range A.Pragma 2586 | CheckPrimitive Range QName A.Expr 2587 | CheckIsEmpty Range Type 2588 | CheckConfluence QName QName 2589 | CheckWithFunctionType Type 2590 | CheckSectionApplication Range ModuleName A.ModuleApplication 2591 | CheckNamedWhere ModuleName 2592 | ScopeCheckExpr C.Expr 2593 | ScopeCheckDeclaration NiceDeclaration 2594 | ScopeCheckLHS C.QName C.Pattern 2595 | NoHighlighting 2596 | ModuleContents -- ^ Interaction command: show module contents. 2597 | SetRange Range -- ^ used by 'setCurrentRange' 2598 deriving (Data, Generic) 2599 2600instance Pretty Call where 2601 pretty CheckClause{} = "CheckClause" 2602 pretty CheckLHS{} = "CheckLHS" 2603 pretty CheckPattern{} = "CheckPattern" 2604 pretty CheckPatternLinearityType{} = "CheckPatternLinearityType" 2605 pretty CheckPatternLinearityValue{} = "CheckPatternLinearityValue" 2606 pretty InferExpr{} = "InferExpr" 2607 pretty CheckExprCall{} = "CheckExprCall" 2608 pretty CheckLetBinding{} = "CheckLetBinding" 2609 pretty CheckProjection{} = "CheckProjection" 2610 pretty IsTypeCall{} = "IsTypeCall" 2611 pretty IsType_{} = "IsType_" 2612 pretty InferVar{} = "InferVar" 2613 pretty InferDef{} = "InferDef" 2614 pretty CheckArguments{} = "CheckArguments" 2615 pretty CheckMetaSolution{} = "CheckMetaSolution" 2616 pretty CheckTargetType{} = "CheckTargetType" 2617 pretty CheckDataDef{} = "CheckDataDef" 2618 pretty CheckRecDef{} = "CheckRecDef" 2619 pretty CheckConstructor{} = "CheckConstructor" 2620 pretty CheckConstructorFitsIn{} = "CheckConstructorFitsIn" 2621 pretty CheckFunDefCall{} = "CheckFunDefCall" 2622 pretty CheckPragma{} = "CheckPragma" 2623 pretty CheckPrimitive{} = "CheckPrimitive" 2624 pretty CheckWithFunctionType{} = "CheckWithFunctionType" 2625 pretty CheckNamedWhere{} = "CheckNamedWhere" 2626 pretty ScopeCheckExpr{} = "ScopeCheckExpr" 2627 pretty ScopeCheckDeclaration{} = "ScopeCheckDeclaration" 2628 pretty ScopeCheckLHS{} = "ScopeCheckLHS" 2629 pretty CheckDotPattern{} = "CheckDotPattern" 2630 pretty SetRange{} = "SetRange" 2631 pretty CheckSectionApplication{} = "CheckSectionApplication" 2632 pretty CheckIsEmpty{} = "CheckIsEmpty" 2633 pretty CheckConfluence{} = "CheckConfluence" 2634 pretty NoHighlighting{} = "NoHighlighting" 2635 pretty ModuleContents{} = "ModuleContents" 2636 2637instance HasRange Call where 2638 getRange (CheckClause _ c) = getRange c 2639 getRange (CheckLHS lhs) = getRange lhs 2640 getRange (CheckPattern p _ _) = getRange p 2641 getRange (CheckPatternLinearityType x) = getRange x 2642 getRange (CheckPatternLinearityValue x) = getRange x 2643 getRange (InferExpr e) = getRange e 2644 getRange (CheckExprCall _ e _) = getRange e 2645 getRange (CheckLetBinding b) = getRange b 2646 getRange (CheckProjection r _ _) = r 2647 getRange (IsTypeCall cmp e s) = getRange e 2648 getRange (IsType_ e) = getRange e 2649 getRange (InferVar x) = getRange x 2650 getRange (InferDef f) = getRange f 2651 getRange (CheckArguments r _ _ _) = r 2652 getRange (CheckMetaSolution r _ _ _) = r 2653 getRange (CheckTargetType r _ _) = r 2654 getRange (CheckDataDef i _ _ _) = getRange i 2655 getRange (CheckRecDef i _ _ _) = getRange i 2656 getRange (CheckConstructor _ _ _ c) = getRange c 2657 getRange (CheckConstructorFitsIn c _ _) = getRange c 2658 getRange (CheckFunDefCall i _ _ _) = getRange i 2659 getRange (CheckPragma r _) = r 2660 getRange (CheckPrimitive i _ _) = getRange i 2661 getRange CheckWithFunctionType{} = noRange 2662 getRange (CheckNamedWhere m) = getRange m 2663 getRange (ScopeCheckExpr e) = getRange e 2664 getRange (ScopeCheckDeclaration d) = getRange d 2665 getRange (ScopeCheckLHS _ p) = getRange p 2666 getRange (CheckDotPattern e _) = getRange e 2667 getRange (SetRange r) = r 2668 getRange (CheckSectionApplication r _ _) = r 2669 getRange (CheckIsEmpty r _) = r 2670 getRange (CheckConfluence rule1 rule2) = max (getRange rule1) (getRange rule2) 2671 getRange NoHighlighting = noRange 2672 getRange ModuleContents = noRange 2673 2674--------------------------------------------------------------------------- 2675-- ** Instance table 2676--------------------------------------------------------------------------- 2677 2678-- | The instance table is a @Map@ associating to every name of 2679-- record/data type/postulate its list of instances 2680type InstanceTable = Map QName (Set QName) 2681 2682-- | When typechecking something of the following form: 2683-- 2684-- instance 2685-- x : _ 2686-- x = y 2687-- 2688-- it's not yet known where to add @x@, so we add it to a list of 2689-- unresolved instances and we'll deal with it later. 2690type TempInstanceTable = (InstanceTable , Set QName) 2691 2692--------------------------------------------------------------------------- 2693-- ** Builtin things 2694--------------------------------------------------------------------------- 2695 2696data BuiltinDescriptor 2697 = BuiltinData (TCM Type) [String] 2698 | BuiltinDataCons (TCM Type) 2699 | BuiltinPrim String (Term -> TCM ()) 2700 | BuiltinSort String 2701 | BuiltinPostulate Relevance (TCM Type) 2702 | BuiltinUnknown (Maybe (TCM Type)) (Term -> Type -> TCM ()) 2703 -- ^ Builtin of any kind. 2704 -- Type can be checked (@Just t@) or inferred (@Nothing@). 2705 -- The second argument is the hook for the verification function. 2706 2707data BuiltinInfo = 2708 BuiltinInfo { builtinName :: String 2709 , builtinDesc :: BuiltinDescriptor } 2710 2711type BuiltinThings pf = Map String (Builtin pf) 2712 2713data Builtin pf 2714 = Builtin Term 2715 | Prim pf 2716 deriving (Show, Functor, Foldable, Traversable, Generic) 2717 2718--------------------------------------------------------------------------- 2719-- * Highlighting levels 2720--------------------------------------------------------------------------- 2721 2722-- | How much highlighting should be sent to the user interface? 2723 2724data HighlightingLevel 2725 = None 2726 | NonInteractive 2727 | Interactive 2728 -- ^ This includes both non-interactive highlighting and 2729 -- interactive highlighting of the expression that is currently 2730 -- being type-checked. 2731 deriving (Eq, Ord, Show, Read, Data, Generic) 2732 2733-- | How should highlighting be sent to the user interface? 2734 2735data HighlightingMethod 2736 = Direct 2737 -- ^ Via stdout. 2738 | Indirect 2739 -- ^ Both via files and via stdout. 2740 deriving (Eq, Show, Read, Data, Generic) 2741 2742-- | @ifTopLevelAndHighlightingLevelIs l b m@ runs @m@ when we're 2743-- type-checking the top-level module (or before we've started doing 2744-- this) and either the highlighting level is /at least/ @l@ or @b@ is 2745-- 'True'. 2746 2747ifTopLevelAndHighlightingLevelIsOr :: 2748 MonadTCEnv tcm => HighlightingLevel -> Bool -> tcm () -> tcm () 2749ifTopLevelAndHighlightingLevelIsOr l b m = do 2750 e <- askTC 2751 when (envHighlightingLevel e >= l || b) $ 2752 case (envImportPath e) of 2753 -- Below the main module. 2754 (_:_:_) -> pure () 2755 -- In or before the top-level module. 2756 _ -> m 2757 2758-- | @ifTopLevelAndHighlightingLevelIs l m@ runs @m@ when we're 2759-- type-checking the top-level module (or before we've started doing 2760-- this) and the highlighting level is /at least/ @l@. 2761 2762ifTopLevelAndHighlightingLevelIs :: 2763 MonadTCEnv tcm => HighlightingLevel -> tcm () -> tcm () 2764ifTopLevelAndHighlightingLevelIs l = 2765 ifTopLevelAndHighlightingLevelIsOr l False 2766 2767--------------------------------------------------------------------------- 2768-- * Type checking environment 2769--------------------------------------------------------------------------- 2770 2771data TCEnv = 2772 TCEnv { envContext :: Context 2773 , envLetBindings :: LetBindings 2774 , envCurrentModule :: ModuleName 2775 , envCurrentPath :: Maybe AbsolutePath 2776 -- ^ The path to the file that is currently being 2777 -- type-checked. 'Nothing' if we do not have a file 2778 -- (like in interactive mode see @CommandLine@). 2779 , envAnonymousModules :: [(ModuleName, Nat)] -- ^ anonymous modules and their number of free variables 2780 , envImportPath :: [C.TopLevelModuleName] 2781 -- ^ The module stack with the entry being the top-level module as 2782 -- Agda chases modules. It will be empty if there is no main 2783 -- module, will have a single entry for the top level module, or 2784 -- more when descending past the main module. This is used to 2785 -- detect import cycles and in some cases highlighting behavior. 2786 -- The level of a given module is not necessarily the same as the 2787 -- length, in the module dependency graph, of the shortest path 2788 -- from the top-level module; it depends on in which order Agda 2789 -- chooses to chase dependencies. 2790 , envMutualBlock :: Maybe MutualId -- ^ the current (if any) mutual block 2791 , envTerminationCheck :: TerminationCheck () -- ^ are we inside the scope of a termination pragma 2792 , envCoverageCheck :: CoverageCheck -- ^ are we inside the scope of a coverage pragma 2793 , envMakeCase :: Bool -- ^ are we inside a make-case (if so, ignore forcing analysis in unifier) 2794 , envSolvingConstraints :: Bool 2795 -- ^ Are we currently in the process of solving active constraints? 2796 , envCheckingWhere :: Bool 2797 -- ^ Have we stepped into the where-declarations of a clause? 2798 -- Everything under a @where@ will be checked with this flag on. 2799 , envWorkingOnTypes :: Bool 2800 -- ^ Are we working on types? Turned on by 'workOnTypes'. 2801 , envAssignMetas :: Bool 2802 -- ^ Are we allowed to assign metas? 2803 , envActiveProblems :: Set ProblemId 2804 , envAbstractMode :: AbstractMode 2805 -- ^ When checking the typesignature of a public definition 2806 -- or the body of a non-abstract definition this is true. 2807 -- To prevent information about abstract things leaking 2808 -- outside the module. 2809 , envModality :: Modality 2810 -- ^ 'Relevance' component: 2811 -- Are we checking an irrelevant argument? (=@Irrelevant@) 2812 -- Then top-level irrelevant declarations are enabled. 2813 -- Other value: @Relevant@, then only relevant decls. are available. 2814 -- 2815 -- 'Quantity' component: 2816 -- Are we checking a runtime-irrelevant thing? (='Quantity0') 2817 -- Then runtime-irrelevant things are usable. 2818 -- Other value: @Quantity1@, runtime relevant. 2819 -- @Quantityω@ is not allowed here, see Bob Atkey, LiCS 2018. 2820 , envSplitOnStrict :: Bool 2821 -- ^ Are we currently case-splitting on a strict 2822 -- datatype (i.e. in SSet)? If yes, the 2823 -- pattern-matching unifier will solve reflexive 2824 -- equations even --without-K. 2825 , envDisplayFormsEnabled :: Bool 2826 -- ^ Sometimes we want to disable display forms. 2827 , envRange :: Range 2828 , envHighlightingRange :: Range 2829 -- ^ Interactive highlighting uses this range rather 2830 -- than 'envRange'. 2831 , envClause :: IPClause 2832 -- ^ What is the current clause we are type-checking? 2833 -- Will be recorded in interaction points in this clause. 2834 , envCall :: Maybe (Closure Call) 2835 -- ^ what we're doing at the moment 2836 , envHighlightingLevel :: HighlightingLevel 2837 -- ^ Set to 'None' when imported modules are 2838 -- type-checked. 2839 , envHighlightingMethod :: HighlightingMethod 2840 , envExpandLast :: ExpandHidden 2841 -- ^ When type-checking an alias f=e, we do not want 2842 -- to insert hidden arguments in the end, because 2843 -- these will become unsolved metas. 2844 , envAppDef :: Maybe QName 2845 -- ^ We are reducing an application of this function. 2846 -- (For debugging of incomplete matches only.) 2847 , envSimplification :: Simplification 2848 -- ^ Did we encounter a simplification (proper match) 2849 -- during the current reduction process? 2850 , envAllowedReductions :: AllowedReductions 2851 , envReduceDefs :: ReduceDefs 2852 , envReconstructed :: Bool 2853 , envInjectivityDepth :: Int 2854 -- ^ Injectivity can cause non-termination for unsolvable contraints 2855 -- (#431, #3067). Keep a limit on the nesting depth of injectivity 2856 -- uses. 2857 , envCompareBlocked :: Bool 2858 -- ^ When @True@, the conversion checker will consider 2859 -- all term constructors as injective, including 2860 -- blocked function applications and metas. Warning: 2861 -- this should only be used when not assigning any 2862 -- metas (e.g. when @envAssignMetas@ is @False@ or 2863 -- when running @pureEqualTerms@) or else we get 2864 -- non-unique meta solutions. 2865 , envPrintDomainFreePi :: Bool 2866 -- ^ When @True@, types will be omitted from printed pi types if they 2867 -- can be inferred. 2868 , envPrintMetasBare :: Bool 2869 -- ^ When @True@, throw away meta numbers and meta elims. 2870 -- This is used for reifying terms for feeding into the 2871 -- user's source code, e.g., for the interaction tactics @solveAll@. 2872 , envInsideDotPattern :: Bool 2873 -- ^ Used by the scope checker to make sure that certain forms 2874 -- of expressions are not used inside dot patterns: extended 2875 -- lambdas and let-expressions. 2876 , envUnquoteFlags :: UnquoteFlags 2877 , envInstanceDepth :: !Int 2878 -- ^ Until we get a termination checker for instance search (#1743) we 2879 -- limit the search depth to ensure termination. 2880 , envIsDebugPrinting :: Bool 2881 , envPrintingPatternLambdas :: [QName] 2882 -- ^ #3004: pattern lambdas with copatterns may refer to themselves. We 2883 -- don't have a good story for what to do in this case, but at least 2884 -- printing shouldn't loop. Here we keep track of which pattern lambdas 2885 -- we are currently in the process of printing. 2886 , envCallByNeed :: Bool 2887 -- ^ Use call-by-need evaluation for reductions. 2888 , envCurrentCheckpoint :: CheckpointId 2889 -- ^ Checkpoints track the evolution of the context as we go 2890 -- under binders or refine it by pattern matching. 2891 , envCheckpoints :: Map CheckpointId Substitution 2892 -- ^ Keeps the substitution from each previous checkpoint to 2893 -- the current context. 2894 , envGeneralizeMetas :: DoGeneralize 2895 -- ^ Should new metas generalized over. 2896 , envGeneralizedVars :: Map QName GeneralizedValue 2897 -- ^ Values for used generalizable variables. 2898 , envActiveBackendName :: Maybe BackendName 2899 -- ^ Is some backend active at the moment, and if yes, which? 2900 -- NB: we only store the 'BackendName' here, otherwise 2901 -- @instance Data TCEnv@ is not derivable. 2902 -- The actual backend can be obtained from the name via 'stBackends'. 2903 , envConflComputingOverlap :: Bool 2904 -- ^ Are we currently computing the overlap between 2905 -- two rewrite rules for the purpose of confluence checking? 2906 } 2907 deriving (Generic) 2908 2909initEnv :: TCEnv 2910initEnv = TCEnv { envContext = [] 2911 , envLetBindings = Map.empty 2912 , envCurrentModule = noModuleName 2913 , envCurrentPath = Nothing 2914 , envAnonymousModules = [] 2915 , envImportPath = [] 2916 , envMutualBlock = Nothing 2917 , envTerminationCheck = TerminationCheck 2918 , envCoverageCheck = YesCoverageCheck 2919 , envMakeCase = False 2920 , envSolvingConstraints = False 2921 , envCheckingWhere = False 2922 , envActiveProblems = Set.empty 2923 , envWorkingOnTypes = False 2924 , envAssignMetas = True 2925 , envAbstractMode = ConcreteMode 2926 -- Andreas, 2013-02-21: This was 'AbstractMode' until now. 2927 -- However, top-level checks for mutual blocks, such as 2928 -- constructor-headedness, should not be able to look into 2929 -- abstract definitions unless abstract themselves. 2930 -- (See also discussion on issue 796.) 2931 -- The initial mode should be 'ConcreteMode', ensuring you 2932 -- can only look into abstract things in an abstract 2933 -- definition (which sets 'AbstractMode'). 2934 , envModality = unitModality 2935 , envSplitOnStrict = False 2936 , envDisplayFormsEnabled = True 2937 , envRange = noRange 2938 , envHighlightingRange = noRange 2939 , envClause = IPNoClause 2940 , envCall = Nothing 2941 , envHighlightingLevel = None 2942 , envHighlightingMethod = Indirect 2943 , envExpandLast = ExpandLast 2944 , envAppDef = Nothing 2945 , envSimplification = NoSimplification 2946 , envAllowedReductions = allReductions 2947 , envReduceDefs = reduceAllDefs 2948 , envReconstructed = False 2949 , envInjectivityDepth = 0 2950 , envCompareBlocked = False 2951 , envPrintDomainFreePi = False 2952 , envPrintMetasBare = False 2953 , envInsideDotPattern = False 2954 , envUnquoteFlags = defaultUnquoteFlags 2955 , envInstanceDepth = 0 2956 , envIsDebugPrinting = False 2957 , envPrintingPatternLambdas = [] 2958 , envCallByNeed = True 2959 , envCurrentCheckpoint = 0 2960 , envCheckpoints = Map.singleton 0 IdS 2961 , envGeneralizeMetas = NoGeneralize 2962 , envGeneralizedVars = Map.empty 2963 , envActiveBackendName = Nothing 2964 , envConflComputingOverlap = False 2965 } 2966 2967class LensTCEnv a where 2968 lensTCEnv :: Lens' TCEnv a 2969 2970instance LensTCEnv TCEnv where 2971 lensTCEnv = id 2972 2973instance LensModality TCEnv where 2974 -- Cohesion shouldn't have an environment component. 2975 getModality = setCohesion defaultCohesion . envModality 2976 mapModality f e = e { envModality = setCohesion defaultCohesion $ f $ envModality e } 2977 2978instance LensRelevance TCEnv where 2979instance LensQuantity TCEnv where 2980 2981data UnquoteFlags = UnquoteFlags 2982 { _unquoteNormalise :: Bool } 2983 deriving (Data, Generic) 2984 2985defaultUnquoteFlags :: UnquoteFlags 2986defaultUnquoteFlags = UnquoteFlags 2987 { _unquoteNormalise = False } 2988 2989unquoteNormalise :: Lens' Bool UnquoteFlags 2990unquoteNormalise f e = f (_unquoteNormalise e) <&> \ x -> e { _unquoteNormalise = x } 2991 2992eUnquoteNormalise :: Lens' Bool TCEnv 2993eUnquoteNormalise = eUnquoteFlags . unquoteNormalise 2994 2995-- * e-prefixed lenses 2996------------------------------------------------------------------------ 2997 2998eContext :: Lens' Context TCEnv 2999eContext f e = f (envContext e) <&> \ x -> e { envContext = x } 3000 3001eLetBindings :: Lens' LetBindings TCEnv 3002eLetBindings f e = f (envLetBindings e) <&> \ x -> e { envLetBindings = x } 3003 3004eCurrentModule :: Lens' ModuleName TCEnv 3005eCurrentModule f e = f (envCurrentModule e) <&> \ x -> e { envCurrentModule = x } 3006 3007eCurrentPath :: Lens' (Maybe AbsolutePath) TCEnv 3008eCurrentPath f e = f (envCurrentPath e) <&> \ x -> e { envCurrentPath = x } 3009 3010eAnonymousModules :: Lens' [(ModuleName, Nat)] TCEnv 3011eAnonymousModules f e = f (envAnonymousModules e) <&> \ x -> e { envAnonymousModules = x } 3012 3013eImportPath :: Lens' [C.TopLevelModuleName] TCEnv 3014eImportPath f e = f (envImportPath e) <&> \ x -> e { envImportPath = x } 3015 3016eMutualBlock :: Lens' (Maybe MutualId) TCEnv 3017eMutualBlock f e = f (envMutualBlock e) <&> \ x -> e { envMutualBlock = x } 3018 3019eTerminationCheck :: Lens' (TerminationCheck ()) TCEnv 3020eTerminationCheck f e = f (envTerminationCheck e) <&> \ x -> e { envTerminationCheck = x } 3021 3022eCoverageCheck :: Lens' CoverageCheck TCEnv 3023eCoverageCheck f e = f (envCoverageCheck e) <&> \ x -> e { envCoverageCheck = x } 3024 3025eMakeCase :: Lens' Bool TCEnv 3026eMakeCase f e = f (envMakeCase e) <&> \ x -> e { envMakeCase = x } 3027 3028eSolvingConstraints :: Lens' Bool TCEnv 3029eSolvingConstraints f e = f (envSolvingConstraints e) <&> \ x -> e { envSolvingConstraints = x } 3030 3031eCheckingWhere :: Lens' Bool TCEnv 3032eCheckingWhere f e = f (envCheckingWhere e) <&> \ x -> e { envCheckingWhere = x } 3033 3034eWorkingOnTypes :: Lens' Bool TCEnv 3035eWorkingOnTypes f e = f (envWorkingOnTypes e) <&> \ x -> e { envWorkingOnTypes = x } 3036 3037eAssignMetas :: Lens' Bool TCEnv 3038eAssignMetas f e = f (envAssignMetas e) <&> \ x -> e { envAssignMetas = x } 3039 3040eActiveProblems :: Lens' (Set ProblemId) TCEnv 3041eActiveProblems f e = f (envActiveProblems e) <&> \ x -> e { envActiveProblems = x } 3042 3043eAbstractMode :: Lens' AbstractMode TCEnv 3044eAbstractMode f e = f (envAbstractMode e) <&> \ x -> e { envAbstractMode = x } 3045 3046-- Andrea 23/02/2020: use get/setModality to enforce invariants of the 3047-- envModality field. 3048eModality :: Lens' Modality TCEnv 3049eModality f e = f (getModality e) <&> \ x -> setModality x e 3050 3051eRelevance :: Lens' Relevance TCEnv 3052eRelevance = eModality . lModRelevance 3053 3054eQuantity :: Lens' Quantity TCEnv 3055eQuantity = eModality . lModQuantity 3056 3057eSplitOnStrict :: Lens' Bool TCEnv 3058eSplitOnStrict f e = f (envSplitOnStrict e) <&> \ x -> e { envSplitOnStrict = x } 3059 3060eDisplayFormsEnabled :: Lens' Bool TCEnv 3061eDisplayFormsEnabled f e = f (envDisplayFormsEnabled e) <&> \ x -> e { envDisplayFormsEnabled = x } 3062 3063eRange :: Lens' Range TCEnv 3064eRange f e = f (envRange e) <&> \ x -> e { envRange = x } 3065 3066eHighlightingRange :: Lens' Range TCEnv 3067eHighlightingRange f e = f (envHighlightingRange e) <&> \ x -> e { envHighlightingRange = x } 3068 3069eCall :: Lens' (Maybe (Closure Call)) TCEnv 3070eCall f e = f (envCall e) <&> \ x -> e { envCall = x } 3071 3072eHighlightingLevel :: Lens' HighlightingLevel TCEnv 3073eHighlightingLevel f e = f (envHighlightingLevel e) <&> \ x -> e { envHighlightingLevel = x } 3074 3075eHighlightingMethod :: Lens' HighlightingMethod TCEnv 3076eHighlightingMethod f e = f (envHighlightingMethod e) <&> \ x -> e { envHighlightingMethod = x } 3077 3078eExpandLast :: Lens' ExpandHidden TCEnv 3079eExpandLast f e = f (envExpandLast e) <&> \ x -> e { envExpandLast = x } 3080 3081eAppDef :: Lens' (Maybe QName) TCEnv 3082eAppDef f e = f (envAppDef e) <&> \ x -> e { envAppDef = x } 3083 3084eSimplification :: Lens' Simplification TCEnv 3085eSimplification f e = f (envSimplification e) <&> \ x -> e { envSimplification = x } 3086 3087eAllowedReductions :: Lens' AllowedReductions TCEnv 3088eAllowedReductions f e = f (envAllowedReductions e) <&> \ x -> e { envAllowedReductions = x } 3089 3090eReduceDefs :: Lens' ReduceDefs TCEnv 3091eReduceDefs f e = f (envReduceDefs e) <&> \ x -> e { envReduceDefs = x } 3092 3093eReconstructed :: Lens' Bool TCEnv 3094eReconstructed f e = f (envReconstructed e) <&> \ x -> e { envReconstructed = x } 3095 3096eInjectivityDepth :: Lens' Int TCEnv 3097eInjectivityDepth f e = f (envInjectivityDepth e) <&> \ x -> e { envInjectivityDepth = x } 3098 3099eCompareBlocked :: Lens' Bool TCEnv 3100eCompareBlocked f e = f (envCompareBlocked e) <&> \ x -> e { envCompareBlocked = x } 3101 3102ePrintDomainFreePi :: Lens' Bool TCEnv 3103ePrintDomainFreePi f e = f (envPrintDomainFreePi e) <&> \ x -> e { envPrintDomainFreePi = x } 3104 3105eInsideDotPattern :: Lens' Bool TCEnv 3106eInsideDotPattern f e = f (envInsideDotPattern e) <&> \ x -> e { envInsideDotPattern = x } 3107 3108eUnquoteFlags :: Lens' UnquoteFlags TCEnv 3109eUnquoteFlags f e = f (envUnquoteFlags e) <&> \ x -> e { envUnquoteFlags = x } 3110 3111eInstanceDepth :: Lens' Int TCEnv 3112eInstanceDepth f e = f (envInstanceDepth e) <&> \ x -> e { envInstanceDepth = x } 3113 3114eIsDebugPrinting :: Lens' Bool TCEnv 3115eIsDebugPrinting f e = f (envIsDebugPrinting e) <&> \ x -> e { envIsDebugPrinting = x } 3116 3117ePrintingPatternLambdas :: Lens' [QName] TCEnv 3118ePrintingPatternLambdas f e = f (envPrintingPatternLambdas e) <&> \ x -> e { envPrintingPatternLambdas = x } 3119 3120eCallByNeed :: Lens' Bool TCEnv 3121eCallByNeed f e = f (envCallByNeed e) <&> \ x -> e { envCallByNeed = x } 3122 3123eCurrentCheckpoint :: Lens' CheckpointId TCEnv 3124eCurrentCheckpoint f e = f (envCurrentCheckpoint e) <&> \ x -> e { envCurrentCheckpoint = x } 3125 3126eCheckpoints :: Lens' (Map CheckpointId Substitution) TCEnv 3127eCheckpoints f e = f (envCheckpoints e) <&> \ x -> e { envCheckpoints = x } 3128 3129eGeneralizeMetas :: Lens' DoGeneralize TCEnv 3130eGeneralizeMetas f e = f (envGeneralizeMetas e) <&> \ x -> e { envGeneralizeMetas = x } 3131 3132eGeneralizedVars :: Lens' (Map QName GeneralizedValue) TCEnv 3133eGeneralizedVars f e = f (envGeneralizedVars e) <&> \ x -> e { envGeneralizedVars = x } 3134 3135eActiveBackendName :: Lens' (Maybe BackendName) TCEnv 3136eActiveBackendName f e = f (envActiveBackendName e) <&> \ x -> e { envActiveBackendName = x } 3137 3138eConflComputingOverlap :: Lens' Bool TCEnv 3139eConflComputingOverlap f e = f (envConflComputingOverlap e) <&> \ x -> e { envConflComputingOverlap = x } 3140 3141--------------------------------------------------------------------------- 3142-- ** Context 3143--------------------------------------------------------------------------- 3144 3145-- | The @Context@ is a stack of 'ContextEntry's. 3146type Context = [ContextEntry] 3147type ContextEntry = Dom (Name, Type) 3148 3149--------------------------------------------------------------------------- 3150-- ** Let bindings 3151--------------------------------------------------------------------------- 3152 3153type LetBindings = Map Name (Open (Term, Dom Type)) 3154 3155--------------------------------------------------------------------------- 3156-- ** Abstract mode 3157--------------------------------------------------------------------------- 3158 3159data AbstractMode 3160 = AbstractMode -- ^ Abstract things in the current module can be accessed. 3161 | ConcreteMode -- ^ No abstract things can be accessed. 3162 | IgnoreAbstractMode -- ^ All abstract things can be accessed. 3163 deriving (Data, Show, Eq, Generic) 3164 3165aDefToMode :: IsAbstract -> AbstractMode 3166aDefToMode AbstractDef = AbstractMode 3167aDefToMode ConcreteDef = ConcreteMode 3168 3169aModeToDef :: AbstractMode -> Maybe IsAbstract 3170aModeToDef AbstractMode = Just AbstractDef 3171aModeToDef ConcreteMode = Just ConcreteDef 3172aModeToDef _ = Nothing 3173 3174--------------------------------------------------------------------------- 3175-- ** Insertion of implicit arguments 3176--------------------------------------------------------------------------- 3177 3178data ExpandHidden 3179 = ExpandLast -- ^ Add implicit arguments in the end until type is no longer hidden 'Pi'. 3180 | DontExpandLast -- ^ Do not append implicit arguments. 3181 | ReallyDontExpandLast -- ^ Makes 'doExpandLast' have no effect. Used to avoid implicit insertion of arguments to metavariables. 3182 deriving (Eq, Data, Generic) 3183 3184isDontExpandLast :: ExpandHidden -> Bool 3185isDontExpandLast ExpandLast = False 3186isDontExpandLast DontExpandLast = True 3187isDontExpandLast ReallyDontExpandLast = True 3188 3189data CandidateKind 3190 = LocalCandidate 3191 | GlobalCandidate QName 3192 deriving (Show, Data, Generic) 3193 3194-- | A candidate solution for an instance meta is a term with its type. 3195-- It may be the case that the candidate is not fully applied yet or 3196-- of the wrong type, hence the need for the type. 3197data Candidate = Candidate { candidateKind :: CandidateKind 3198 , candidateTerm :: Term 3199 , candidateType :: Type 3200 , candidateOverlappable :: Bool 3201 } 3202 deriving (Show, Data, Generic) 3203 3204instance Free Candidate where 3205 freeVars' (Candidate _ t u _) = freeVars' (t, u) 3206 3207 3208--------------------------------------------------------------------------- 3209-- ** Checking arguments 3210--------------------------------------------------------------------------- 3211 3212data ArgsCheckState a = ACState 3213 { acRanges :: [Maybe Range] 3214 -- ^ Ranges of checked arguments, where present. 3215 -- e.g. inserted implicits have no correponding abstract syntax. 3216 , acElims :: Elims 3217 -- ^ Checked and inserted arguments so far. 3218 , acConstraints :: [Maybe (Abs Constraint)] 3219 -- ^ Constraints for the head so far, 3220 -- i.e. before applying the correponding elim. 3221 , acType :: Type 3222 -- ^ Type for the rest of the application. 3223 , acData :: a 3224 } 3225 deriving (Show) 3226 3227 3228--------------------------------------------------------------------------- 3229-- * Type checking warnings (aka non-fatal errors) 3230--------------------------------------------------------------------------- 3231 3232-- | A non-fatal error is an error which does not prevent us from 3233-- checking the document further and interacting with the user. 3234 3235data Warning 3236 = NicifierIssue DeclarationWarning 3237 | TerminationIssue [TerminationError] 3238 | UnreachableClauses QName [Range] 3239 -- ^ `UnreachableClauses f rs` means that the clauses in `f` whose ranges are rs 3240 -- are unreachable 3241 | CoverageIssue QName [(Telescope, [NamedArg DeBruijnPattern])] 3242 -- ^ `CoverageIssue f pss` means that `pss` are not covered in `f` 3243 | CoverageNoExactSplit QName [Clause] 3244 | NotStrictlyPositive QName (Seq OccursWhere) 3245 | UnsolvedMetaVariables [Range] -- ^ Do not use directly with 'warning' 3246 | UnsolvedInteractionMetas [Range] -- ^ Do not use directly with 'warning' 3247 | UnsolvedConstraints Constraints 3248 -- ^ Do not use directly with 'warning' 3249 | CantGeneralizeOverSorts [MetaId] 3250 | AbsurdPatternRequiresNoRHS [NamedArg DeBruijnPattern] 3251 | OldBuiltin String String 3252 -- ^ In `OldBuiltin old new`, the BUILTIN old has been replaced by new 3253 | EmptyRewritePragma 3254 -- ^ If the user wrote just @{-\# REWRITE \#-}@. 3255 | EmptyWhere 3256 -- ^ An empty @where@ block is dead code. 3257 | IllformedAsClause String 3258 -- ^ If the user wrote something other than an unqualified name 3259 -- in the @as@ clause of an @import@ statement. 3260 -- The 'String' gives optionally extra explanation. 3261 | ClashesViaRenaming NameOrModule [C.Name] 3262 -- ^ If a `renaming' import directive introduces a name or module name clash 3263 -- in the exported names of a module. 3264 -- (See issue #4154.) 3265 | UselessPatternDeclarationForRecord String 3266 -- ^ The 'pattern' declaration is useless in the presence 3267 -- of either @coinductive@ or @eta-equality@. 3268 -- Content of 'String' is "coinductive" or "eta", resp. 3269 | UselessPublic 3270 -- ^ If the user opens a module public before the module header. 3271 -- (See issue #2377.) 3272 | UselessHiding [C.ImportedName] 3273 -- ^ Names in `hiding` directive that don't hide anything 3274 -- imported by a `using` directive. 3275 | UselessInline QName 3276 | WrongInstanceDeclaration 3277 | InstanceWithExplicitArg QName 3278 -- ^ An instance was declared with an implicit argument, which means it 3279 -- will never actually be considered by instance search. 3280 | InstanceNoOutputTypeName Doc 3281 -- ^ The type of an instance argument doesn't end in a named or 3282 -- variable type, so it will never be considered by instance search. 3283 | InstanceArgWithExplicitArg Doc 3284 -- ^ As InstanceWithExplicitArg, but for local bindings rather than 3285 -- top-level instances. 3286 | InversionDepthReached QName 3287 -- ^ The --inversion-max-depth was reached. 3288 | NoGuardednessFlag QName 3289 -- ^ A coinductive record was declared but neither --guardedness nor 3290 -- --sized-types is enabled. 3291 3292 -- Generic warnings for one-off things 3293 | GenericWarning Doc 3294 -- ^ Harmless generic warning (not an error) 3295 | GenericNonFatalError Doc 3296 -- ^ Generic error which doesn't abort proceedings (not a warning) 3297 | GenericUseless Range Doc 3298 -- ^ Generic warning when code is useless and thus ignored. 3299 -- 'Range' is for dead code highlighting. 3300 3301 -- Safe flag errors 3302 | SafeFlagPostulate C.Name 3303 | SafeFlagPragma [String] -- ^ Unsafe OPTIONS. 3304 | SafeFlagNonTerminating 3305 | SafeFlagTerminating 3306 | SafeFlagWithoutKFlagPrimEraseEquality 3307 | WithoutKFlagPrimEraseEquality 3308 | SafeFlagNoPositivityCheck 3309 | SafeFlagPolarity 3310 | SafeFlagNoUniverseCheck 3311 | SafeFlagNoCoverageCheck 3312 | SafeFlagInjective 3313 | SafeFlagEta -- ^ ETA pragma is unsafe. 3314 | ParseWarning ParseWarning 3315 | LibraryWarning LibWarning 3316 | DeprecationWarning String String String 3317 -- ^ `DeprecationWarning old new version`: 3318 -- `old` is deprecated, use `new` instead. This will be an error in Agda `version`. 3319 | UserWarning Text 3320 -- ^ User-defined warning (e.g. to mention that a name is deprecated) 3321 | DuplicateUsing (List1 C.ImportedName) 3322 -- ^ Duplicate mentions of the same name in @using@ directive(s). 3323 | FixityInRenamingModule (List1 Range) 3324 -- ^ Fixity of modules cannot be changed via renaming (since modules have no fixity). 3325 | ModuleDoesntExport C.QName [C.Name] [C.Name] [C.ImportedName] 3326 -- ^ Some imported names are not actually exported by the source module. 3327 -- The second argument is the names that could be exported. 3328 -- The third argument is the module names that could be exported. 3329 | InfectiveImport String ModuleName 3330 -- ^ Importing a file using an infective option into one which doesn't 3331 | CoInfectiveImport String ModuleName 3332 -- ^ Importing a file not using a coinfective option from one which does 3333 | RewriteNonConfluent Term Term Term Doc 3334 -- ^ Confluence checker found critical pair and equality checking 3335 -- resulted in a type error 3336 | RewriteMaybeNonConfluent Term Term [Doc] 3337 -- ^ Confluence checker got stuck on computing overlap between two 3338 -- rewrite rules 3339 | RewriteAmbiguousRules Term Term Term 3340 -- ^ The global confluence checker found a term @u@ that reduces 3341 -- to both @v1@ and @v2@ and there is no rule to resolve the 3342 -- ambiguity. 3343 | RewriteMissingRule Term Term Term 3344 -- ^ The global confluence checker found a term @u@ that reduces 3345 -- to @v@, but @v@ does not reduce to @rho(u)@. 3346 | PragmaCompileErased BackendName QName 3347 -- ^ COMPILE directive for an erased symbol 3348 | NotInScopeW [C.QName] 3349 -- ^ Out of scope error we can recover from 3350 | AsPatternShadowsConstructorOrPatternSynonym Bool 3351 -- ^ The as-name in an as-pattern may not shadow a constructor (@False@) 3352 -- or pattern synonym name (@True@), 3353 -- because this can be confusing to read. 3354 | RecordFieldWarning RecordFieldWarning 3355 deriving (Show, Generic) 3356 3357data RecordFieldWarning 3358 = DuplicateFieldsWarning [(C.Name, Range)] 3359 -- ^ Each redundant field comes with a range of associated dead code. 3360 | TooManyFieldsWarning QName [C.Name] [(C.Name, Range)] 3361 -- ^ Record type, fields not supplied by user, non-fields but supplied. 3362 -- The redundant fields come with a range of associated dead code. 3363 deriving (Show, Data, Generic) 3364 3365recordFieldWarningToError :: RecordFieldWarning -> TypeError 3366recordFieldWarningToError = \case 3367 DuplicateFieldsWarning xrs -> DuplicateFields $ map fst xrs 3368 TooManyFieldsWarning q ys xrs -> TooManyFields q ys $ map fst xrs 3369 3370warningName :: Warning -> WarningName 3371warningName = \case 3372 -- special cases 3373 NicifierIssue dw -> declarationWarningName dw 3374 ParseWarning pw -> parseWarningName pw 3375 LibraryWarning lw -> libraryWarningName lw 3376 AsPatternShadowsConstructorOrPatternSynonym{} -> AsPatternShadowsConstructorOrPatternSynonym_ 3377 -- scope- and type-checking errors 3378 AbsurdPatternRequiresNoRHS{} -> AbsurdPatternRequiresNoRHS_ 3379 CantGeneralizeOverSorts{} -> CantGeneralizeOverSorts_ 3380 CoverageIssue{} -> CoverageIssue_ 3381 CoverageNoExactSplit{} -> CoverageNoExactSplit_ 3382 DeprecationWarning{} -> DeprecationWarning_ 3383 EmptyRewritePragma -> EmptyRewritePragma_ 3384 EmptyWhere -> EmptyWhere_ 3385 IllformedAsClause{} -> IllformedAsClause_ 3386 WrongInstanceDeclaration{} -> WrongInstanceDeclaration_ 3387 InstanceWithExplicitArg{} -> InstanceWithExplicitArg_ 3388 InstanceNoOutputTypeName{} -> InstanceNoOutputTypeName_ 3389 InstanceArgWithExplicitArg{} -> InstanceArgWithExplicitArg_ 3390 DuplicateUsing{} -> DuplicateUsing_ 3391 FixityInRenamingModule{} -> FixityInRenamingModule_ 3392 GenericNonFatalError{} -> GenericNonFatalError_ 3393 GenericUseless{} -> GenericUseless_ 3394 GenericWarning{} -> GenericWarning_ 3395 InversionDepthReached{} -> InversionDepthReached_ 3396 ModuleDoesntExport{} -> ModuleDoesntExport_ 3397 NoGuardednessFlag{} -> NoGuardednessFlag_ 3398 NotInScopeW{} -> NotInScope_ 3399 NotStrictlyPositive{} -> NotStrictlyPositive_ 3400 OldBuiltin{} -> OldBuiltin_ 3401 SafeFlagNoPositivityCheck -> SafeFlagNoPositivityCheck_ 3402 SafeFlagNonTerminating -> SafeFlagNonTerminating_ 3403 SafeFlagNoUniverseCheck -> SafeFlagNoUniverseCheck_ 3404 SafeFlagPolarity -> SafeFlagPolarity_ 3405 SafeFlagPostulate{} -> SafeFlagPostulate_ 3406 SafeFlagPragma{} -> SafeFlagPragma_ 3407 SafeFlagEta -> SafeFlagEta_ 3408 SafeFlagInjective -> SafeFlagInjective_ 3409 SafeFlagNoCoverageCheck -> SafeFlagNoCoverageCheck_ 3410 SafeFlagWithoutKFlagPrimEraseEquality -> SafeFlagWithoutKFlagPrimEraseEquality_ 3411 WithoutKFlagPrimEraseEquality -> WithoutKFlagPrimEraseEquality_ 3412 SafeFlagTerminating -> SafeFlagTerminating_ 3413 TerminationIssue{} -> TerminationIssue_ 3414 UnreachableClauses{} -> UnreachableClauses_ 3415 UnsolvedInteractionMetas{} -> UnsolvedInteractionMetas_ 3416 UnsolvedConstraints{} -> UnsolvedConstraints_ 3417 UnsolvedMetaVariables{} -> UnsolvedMetaVariables_ 3418 UselessHiding{} -> UselessHiding_ 3419 UselessInline{} -> UselessInline_ 3420 UselessPublic{} -> UselessPublic_ 3421 UselessPatternDeclarationForRecord{} -> UselessPatternDeclarationForRecord_ 3422 ClashesViaRenaming{} -> ClashesViaRenaming_ 3423 UserWarning{} -> UserWarning_ 3424 InfectiveImport{} -> InfectiveImport_ 3425 CoInfectiveImport{} -> CoInfectiveImport_ 3426 RewriteNonConfluent{} -> RewriteNonConfluent_ 3427 RewriteMaybeNonConfluent{} -> RewriteMaybeNonConfluent_ 3428 RewriteAmbiguousRules{} -> RewriteAmbiguousRules_ 3429 RewriteMissingRule{} -> RewriteMissingRule_ 3430 PragmaCompileErased{} -> PragmaCompileErased_ 3431 -- record field warnings 3432 RecordFieldWarning w -> case w of 3433 DuplicateFieldsWarning{} -> DuplicateFieldsWarning_ 3434 TooManyFieldsWarning{} -> TooManyFieldsWarning_ 3435 3436data TCWarning 3437 = TCWarning 3438 { tcWarningLocation :: CallStack 3439 -- ^ Location in the internal Agda source code location where the error raised 3440 , tcWarningRange :: Range 3441 -- ^ Range where the warning was raised 3442 , tcWarning :: Warning 3443 -- ^ The warning itself 3444 , tcWarningPrintedWarning :: Doc 3445 -- ^ The warning printed in the state and environment where it was raised 3446 , tcWarningCached :: Bool 3447 -- ^ Should the warning be affected by caching. 3448 } 3449 deriving (Show, Generic) 3450 3451tcWarningOrigin :: TCWarning -> SrcFile 3452tcWarningOrigin = rangeFile . tcWarningRange 3453 3454instance HasRange TCWarning where 3455 getRange = tcWarningRange 3456 3457-- used for merging lists of warnings 3458instance Eq TCWarning where 3459 (==) = (==) `on` tcWarningPrintedWarning 3460 3461--------------------------------------------------------------------------- 3462-- * Type checking errors 3463--------------------------------------------------------------------------- 3464 3465-- | Information about a call. 3466 3467data CallInfo = CallInfo 3468 { callInfoTarget :: QName 3469 -- ^ Target function name. 3470 , callInfoRange :: Range 3471 -- ^ Range of the target function. 3472 , callInfoCall :: Closure Term 3473 -- ^ To be formatted representation of the call. 3474 } deriving (Show, Generic) 3475 -- no Eq, Ord instances: too expensive! (see issues 851, 852) 3476 3477-- | We only 'show' the name of the callee. 3478instance Pretty CallInfo where pretty = pretty . callInfoTarget 3479 3480-- | Information about a mutual block which did not pass the 3481-- termination checker. 3482 3483data TerminationError = TerminationError 3484 { termErrFunctions :: [QName] 3485 -- ^ The functions which failed to check. (May not include 3486 -- automatically generated functions.) 3487 , termErrCalls :: [CallInfo] 3488 -- ^ The problematic call sites. 3489 } deriving (Show, Generic) 3490 3491-- | Error when splitting a pattern variable into possible constructor patterns. 3492data SplitError 3493 = NotADatatype (Closure Type) -- ^ Neither data type nor record. 3494 | BlockedType Blocker (Closure Type) -- ^ Type could not be sufficiently reduced. 3495 | ErasedDatatype Bool (Closure Type) -- ^ Data type, but in erased position. 3496 -- If the boolean is 'True', 3497 -- then the reason for the 3498 -- error is that the K rule 3499 -- is turned off. 3500 | CoinductiveDatatype (Closure Type) -- ^ Split on codata not allowed. 3501 -- UNUSED, but keep! 3502 -- -- | NoRecordConstructor Type -- ^ record type, but no constructor 3503 | UnificationStuck 3504 { cantSplitBlocker :: Maybe Blocker -- ^ Blocking metavariable (if any) 3505 , cantSplitConName :: QName -- ^ Constructor. 3506 , cantSplitTel :: Telescope -- ^ Context for indices. 3507 , cantSplitConIdx :: Args -- ^ Inferred indices (from type of constructor). 3508 , cantSplitGivenIdx :: Args -- ^ Expected indices (from checking pattern). 3509 , cantSplitFailures :: [UnificationFailure] -- ^ Reason(s) why unification got stuck. 3510 } 3511 | CosplitCatchall 3512 -- ^ Copattern split with a catchall 3513 | CosplitNoTarget 3514 -- ^ We do not know the target type of the clause. 3515 | CosplitNoRecordType (Closure Type) 3516 -- ^ Target type is not a record type. 3517 | CannotCreateMissingClause QName (Telescope,[NamedArg DeBruijnPattern]) Doc (Closure (Abs Type)) 3518 3519 | GenericSplitError String 3520 deriving (Show, Generic) 3521 3522data NegativeUnification 3523 = UnifyConflict Telescope Term Term 3524 | UnifyCycle Telescope Int Term 3525 deriving (Show, Generic) 3526 3527data UnificationFailure 3528 = UnifyIndicesNotVars Telescope Type Term Term Args -- ^ Failed to apply injectivity to constructor of indexed datatype 3529 | UnifyRecursiveEq Telescope Type Int Term -- ^ Can't solve equation because variable occurs in (type of) lhs 3530 | UnifyReflexiveEq Telescope Type Term -- ^ Can't solve reflexive equation because --without-K is enabled 3531 | UnifyUnusableModality Telescope Type Int Term Modality -- ^ Can't solve equation because solution modality is less "usable" 3532 deriving (Show, Generic) 3533 3534data UnquoteError 3535 = BadVisibility String (Arg I.Term) 3536 | ConInsteadOfDef QName String String 3537 | DefInsteadOfCon QName String String 3538 | NonCanonical String I.Term 3539 | BlockedOnMeta TCState Blocker 3540 | UnquotePanic String 3541 deriving (Show, Generic) 3542 3543data TypeError 3544 = InternalError String 3545 | NotImplemented String 3546 | NotSupported String 3547 | CompilationError String 3548 | PropMustBeSingleton 3549 | DataMustEndInSort Term 3550{- UNUSED 3551 | DataTooManyParameters 3552 -- ^ In @data D xs where@ the number of parameters @xs@ does not fit the 3553 -- the parameters given in the forward declaraion @data D Gamma : T@. 3554-} 3555 | ShouldEndInApplicationOfTheDatatype Type 3556 -- ^ The target of a constructor isn't an application of its 3557 -- datatype. The 'Type' records what it does target. 3558 | ShouldBeAppliedToTheDatatypeParameters Term Term 3559 -- ^ The target of a constructor isn't its datatype applied to 3560 -- something that isn't the parameters. First term is the correct 3561 -- target and the second term is the actual target. 3562 | ShouldBeApplicationOf Type QName 3563 -- ^ Expected a type to be an application of a particular datatype. 3564 | ConstructorPatternInWrongDatatype QName QName -- ^ constructor, datatype 3565 | CantResolveOverloadedConstructorsTargetingSameDatatype QName (List1 QName) 3566 -- ^ Datatype, constructors. 3567 | DoesNotConstructAnElementOf QName Type -- ^ constructor, type 3568 | WrongHidingInLHS 3569 -- ^ The left hand side of a function definition has a hidden argument 3570 -- where a non-hidden was expected. 3571 | WrongHidingInLambda Type 3572 -- ^ Expected a non-hidden function and found a hidden lambda. 3573 | WrongHidingInApplication Type 3574 -- ^ A function is applied to a hidden argument where a non-hidden was expected. 3575 | WrongNamedArgument (NamedArg A.Expr) [NamedName] 3576 -- ^ A function is applied to a hidden named argument it does not have. 3577 -- The list contains names of possible hidden arguments at this point. 3578 | WrongIrrelevanceInLambda 3579 -- ^ Wrong user-given relevance annotation in lambda. 3580 | WrongQuantityInLambda 3581 -- ^ Wrong user-given quantity annotation in lambda. 3582 | WrongCohesionInLambda 3583 -- ^ Wrong user-given cohesion annotation in lambda. 3584 | QuantityMismatch Quantity Quantity 3585 -- ^ The given quantity does not correspond to the expected quantity. 3586 | HidingMismatch Hiding Hiding 3587 -- ^ The given hiding does not correspond to the expected hiding. 3588 | RelevanceMismatch Relevance Relevance 3589 -- ^ The given relevance does not correspond to the expected relevane. 3590 | UninstantiatedDotPattern A.Expr 3591 | ForcedConstructorNotInstantiated A.Pattern 3592 | IllformedProjectionPattern A.Pattern 3593 | CannotEliminateWithPattern (Maybe Blocker) (NamedArg A.Pattern) Type 3594 | WrongNumberOfConstructorArguments QName Nat Nat 3595 | ShouldBeEmpty Type [DeBruijnPattern] 3596 | ShouldBeASort Type 3597 -- ^ The given type should have been a sort. 3598 | ShouldBePi Type 3599 -- ^ The given type should have been a pi. 3600 | ShouldBePath Type 3601 | ShouldBeRecordType Type 3602 | ShouldBeRecordPattern DeBruijnPattern 3603 | NotAProjectionPattern (NamedArg A.Pattern) 3604 | NotAProperTerm 3605 | InvalidTypeSort Sort 3606 -- ^ This sort is not a type expression. 3607 | InvalidType Term 3608 -- ^ This term is not a type expression. 3609 | FunctionTypeInSizeUniv Term 3610 -- ^ This term, a function type constructor, lives in 3611 -- @SizeUniv@, which is not allowed. 3612 | SplitOnIrrelevant (Dom Type) 3613 | SplitOnUnusableCohesion (Dom Type) 3614 -- UNUSED: -- | SplitOnErased (Dom Type) 3615 | SplitOnNonVariable Term Type 3616 | SplitOnNonEtaRecord QName 3617 | DefinitionIsIrrelevant QName 3618 | DefinitionIsErased QName 3619 | VariableIsIrrelevant Name 3620 | VariableIsErased Name 3621 | VariableIsOfUnusableCohesion Name Cohesion 3622 | UnequalLevel Comparison Level Level 3623 | UnequalTerms Comparison Term Term CompareAs 3624 | UnequalTypes Comparison Type Type 3625-- | UnequalTelescopes Comparison Telescope Telescope -- UNUSED 3626 | UnequalRelevance Comparison Term Term 3627 -- ^ The two function types have different relevance. 3628 | UnequalQuantity Comparison Term Term 3629 -- ^ The two function types have different relevance. 3630 | UnequalCohesion Comparison Term Term 3631 -- ^ The two function types have different cohesion. 3632 | UnequalHiding Term Term 3633 -- ^ The two function types have different hiding. 3634 | UnequalSorts Sort Sort 3635 | UnequalBecauseOfUniverseConflict Comparison Term Term 3636 | NotLeqSort Sort Sort 3637 | MetaCannotDependOn MetaId Nat 3638 -- ^ The arguments are the meta variable and the parameter that it wants to depend on. 3639 | MetaOccursInItself MetaId 3640 | MetaIrrelevantSolution MetaId Term 3641 | MetaErasedSolution MetaId Term 3642 | GenericError String 3643 | GenericDocError Doc 3644 | SortOfSplitVarError (Maybe Blocker) Doc 3645 -- ^ the meta is what we might be blocked on. 3646 | BuiltinMustBeConstructor String A.Expr 3647 | NoSuchBuiltinName String 3648 | DuplicateBuiltinBinding String Term Term 3649 | NoBindingForBuiltin String 3650 | NoSuchPrimitiveFunction String 3651 | DuplicatePrimitiveBinding String QName QName 3652 | WrongModalityForPrimitive String ArgInfo ArgInfo 3653 | ShadowedModule C.Name [A.ModuleName] 3654 | BuiltinInParameterisedModule String 3655 | IllegalLetInTelescope C.TypedBinding 3656 | IllegalPatternInTelescope C.Binder 3657 | NoRHSRequiresAbsurdPattern [NamedArg A.Pattern] 3658 | TooManyFields QName [C.Name] [C.Name] 3659 -- ^ Record type, fields not supplied by user, non-fields but supplied. 3660 | DuplicateFields [C.Name] 3661 | DuplicateConstructors [C.Name] 3662 | WithOnFreeVariable A.Expr Term 3663 | UnexpectedWithPatterns [A.Pattern] 3664 | WithClausePatternMismatch A.Pattern (NamedArg DeBruijnPattern) 3665 | FieldOutsideRecord 3666 | ModuleArityMismatch A.ModuleName Telescope [NamedArg A.Expr] 3667 | GeneralizeCyclicDependency 3668 | GeneralizeUnsolvedMeta 3669 -- Coverage errors 3670-- UNUSED: | IncompletePatternMatching Term [Elim] -- can only happen if coverage checking is switched off 3671 | SplitError SplitError 3672 | ImpossibleConstructor QName NegativeUnification 3673 -- Positivity errors 3674 | TooManyPolarities QName Int 3675 -- Import errors 3676 | LocalVsImportedModuleClash ModuleName 3677 | SolvedButOpenHoles 3678 -- ^ Some interaction points (holes) have not been filled by user. 3679 -- There are not 'UnsolvedMetas' since unification solved them. 3680 -- This is an error, since interaction points are never filled 3681 -- without user interaction. 3682 | CyclicModuleDependency [C.TopLevelModuleName] 3683 | FileNotFound C.TopLevelModuleName [AbsolutePath] 3684 | OverlappingProjects AbsolutePath C.TopLevelModuleName C.TopLevelModuleName 3685 | AmbiguousTopLevelModuleName C.TopLevelModuleName [AbsolutePath] 3686 | ModuleNameUnexpected C.TopLevelModuleName C.TopLevelModuleName 3687 -- ^ Found module name, expected module name. 3688 | ModuleNameDoesntMatchFileName C.TopLevelModuleName [AbsolutePath] 3689 | ClashingFileNamesFor ModuleName [AbsolutePath] 3690 | ModuleDefinedInOtherFile C.TopLevelModuleName AbsolutePath AbsolutePath 3691 -- ^ Module name, file from which it was loaded, file which 3692 -- the include path says contains the module. 3693 -- Scope errors 3694 | BothWithAndRHS 3695 | AbstractConstructorNotInScope A.QName 3696 | NotInScope [C.QName] 3697 | NoSuchModule C.QName 3698 | AmbiguousName C.QName (List1 A.QName) 3699 | AmbiguousModule C.QName (List1 A.ModuleName) 3700 | ClashingDefinition C.QName A.QName (Maybe NiceDeclaration) 3701 | ClashingModule A.ModuleName A.ModuleName 3702 | ClashingImport C.Name A.QName 3703 | ClashingModuleImport C.Name A.ModuleName 3704 | PatternShadowsConstructor C.Name A.QName 3705 | DuplicateImports C.QName [C.ImportedName] 3706 | InvalidPattern C.Pattern 3707 | RepeatedVariablesInPattern [C.Name] 3708 | GeneralizeNotSupportedHere A.QName 3709 | MultipleFixityDecls [(C.Name, [Fixity'])] 3710 | MultiplePolarityPragmas [C.Name] 3711 -- Concrete to Abstract errors 3712 | NotAModuleExpr C.Expr 3713 -- ^ The expr was used in the right hand side of an implicit module 3714 -- definition, but it wasn't of the form @m Delta@. 3715 | NotAnExpression C.Expr 3716 | NotAValidLetBinding NiceDeclaration 3717 | NotValidBeforeField NiceDeclaration 3718 | NothingAppliedToHiddenArg C.Expr 3719 | NothingAppliedToInstanceArg C.Expr 3720 -- Pattern synonym errors 3721 | BadArgumentsToPatternSynonym A.AmbiguousQName 3722 | TooFewArgumentsToPatternSynonym A.AmbiguousQName 3723 | CannotResolveAmbiguousPatternSynonym (List1 (A.QName, A.PatternSynDefn)) 3724 | UnusedVariableInPatternSynonym 3725 -- Operator errors 3726 | NoParseForApplication (List2 C.Expr) 3727 | AmbiguousParseForApplication (List2 C.Expr) (List1 C.Expr) 3728 | NoParseForLHS LHSOrPatSyn [C.Pattern] C.Pattern 3729 -- ^ The list contains patterns that failed to be interpreted. 3730 -- If it is non-empty, the first entry could be printed as error hint. 3731 | AmbiguousParseForLHS LHSOrPatSyn C.Pattern [C.Pattern] 3732 -- ^ Pattern and its possible interpretations. 3733 | OperatorInformation [NotationSection] TypeError 3734{- UNUSED 3735 | NoParseForPatternSynonym C.Pattern 3736 | AmbiguousParseForPatternSynonym C.Pattern [C.Pattern] 3737-} 3738 -- Usage errors 3739 -- Instance search errors 3740 | InstanceNoCandidate Type [(Term, TCErr)] 3741 -- Reflection errors 3742 | UnquoteFailed UnquoteError 3743 | DeBruijnIndexOutOfScope Nat Telescope [Name] 3744 -- Language option errors 3745 | NeedOptionCopatterns 3746 | NeedOptionRewriting 3747 | NeedOptionProp 3748 | NeedOptionTwoLevel 3749 -- Failure associated to warnings 3750 | NonFatalErrors [TCWarning] 3751 -- Instance search errors 3752 | InstanceSearchDepthExhausted Term Type Int 3753 | TriedToCopyConstrainedPrim QName 3754 deriving (Show, Generic) 3755 3756-- | Distinguish error message when parsing lhs or pattern synonym, resp. 3757data LHSOrPatSyn = IsLHS | IsPatSyn 3758 deriving (Eq, Show, Generic) 3759 3760-- | Type-checking errors. 3761 3762data TCErr 3763 = TypeError 3764 { tcErrLocation :: CallStack 3765 -- ^ Location in the internal Agda source code where the error was raised 3766 , tcErrState :: TCState 3767 -- ^ The state in which the error was raised. 3768 , tcErrClosErr :: Closure TypeError 3769 -- ^ The environment in which the error as raised plus the error. 3770 } 3771 | Exception Range Doc 3772 | IOException TCState Range E.IOException 3773 -- ^ The first argument is the state in which the error was 3774 -- raised. 3775 | PatternErr Blocker 3776 -- ^ The exception which is usually caught. 3777 -- Raised for pattern violations during unification ('assignV') 3778 -- but also in other situations where we want to backtrack. 3779 -- Contains an unblocker to control when the computation should 3780 -- be retried. 3781 3782instance Show TCErr where 3783 show (TypeError _ _ e) = prettyShow (envRange $ clEnv e) ++ ": " ++ show (clValue e) 3784 show (Exception r d) = prettyShow r ++ ": " ++ render d 3785 show (IOException _ r e) = prettyShow r ++ ": " ++ show e 3786 show PatternErr{} = "Pattern violation (you shouldn't see this)" 3787 3788instance HasRange TCErr where 3789 getRange (TypeError _ _ cl) = envRange $ clEnv cl 3790 getRange (Exception r _) = r 3791 getRange (IOException s r _) = r 3792 getRange PatternErr{} = noRange 3793 3794instance E.Exception TCErr 3795 3796----------------------------------------------------------------------------- 3797-- * Accessing options 3798----------------------------------------------------------------------------- 3799 3800instance MonadIO m => HasOptions (TCMT m) where 3801 pragmaOptions = useTC stPragmaOptions 3802 3803 commandLineOptions = do 3804 p <- useTC stPragmaOptions 3805 cl <- stPersistentOptions . stPersistentState <$> getTC 3806 return $ cl { optPragmaOptions = p } 3807 3808-- HasOptions lifts through monad transformers 3809-- (see default signatures in the HasOptions class). 3810 3811-- Ternary options are annoying to deal with so we provide auxiliary 3812-- definitions using @collapseDefault@. 3813 3814sizedTypesOption :: HasOptions m => m Bool 3815sizedTypesOption = collapseDefault . optSizedTypes <$> pragmaOptions 3816 3817guardednessOption :: HasOptions m => m Bool 3818guardednessOption = collapseDefault . optGuardedness <$> pragmaOptions 3819 3820withoutKOption :: HasOptions m => m Bool 3821withoutKOption = collapseDefault . optWithoutK <$> pragmaOptions 3822 3823enableCaching :: HasOptions m => m Bool 3824enableCaching = optCaching <$> pragmaOptions 3825----------------------------------------------------------------------------- 3826-- * The reduce monad 3827----------------------------------------------------------------------------- 3828 3829-- | Environment of the reduce monad. 3830data ReduceEnv = ReduceEnv 3831 { redEnv :: TCEnv -- ^ Read only access to environment. 3832 , redSt :: TCState -- ^ Read only access to state (signature, metas...). 3833 } 3834 3835mapRedEnv :: (TCEnv -> TCEnv) -> ReduceEnv -> ReduceEnv 3836mapRedEnv f s = s { redEnv = f (redEnv s) } 3837 3838mapRedSt :: (TCState -> TCState) -> ReduceEnv -> ReduceEnv 3839mapRedSt f s = s { redSt = f (redSt s) } 3840 3841mapRedEnvSt :: (TCEnv -> TCEnv) -> (TCState -> TCState) -> ReduceEnv 3842 -> ReduceEnv 3843mapRedEnvSt f g (ReduceEnv e s) = ReduceEnv (f e) (g s) 3844 3845-- Lenses 3846reduceEnv :: Lens' TCEnv ReduceEnv 3847reduceEnv f s = f (redEnv s) <&> \ e -> s { redEnv = e } 3848 3849reduceSt :: Lens' TCState ReduceEnv 3850reduceSt f s = f (redSt s) <&> \ e -> s { redSt = e } 3851 3852newtype ReduceM a = ReduceM { unReduceM :: ReduceEnv -> a } 3853-- deriving (Functor, Applicative, Monad) 3854 3855onReduceEnv :: (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a 3856onReduceEnv f (ReduceM m) = ReduceM (m . f) 3857 3858fmapReduce :: (a -> b) -> ReduceM a -> ReduceM b 3859fmapReduce f (ReduceM m) = ReduceM $ \ e -> f $! m e 3860{-# INLINE fmapReduce #-} 3861 3862-- Andreas, 2021-05-12, issue #5379: 3863-- It seems more stable to force to evaluate @mf <*> ma@ 3864-- from left to right, for the sake of printing 3865-- debug messages in order. 3866apReduce :: ReduceM (a -> b) -> ReduceM a -> ReduceM b 3867apReduce (ReduceM f) (ReduceM x) = ReduceM $ \ e -> 3868 let g = f e 3869 a = x e 3870 in g `pseq` a `pseq` g a 3871{-# INLINE apReduce #-} 3872 3873-- Andreas, 2021-05-12, issue #5379 3874-- Since the MonadDebug instance of ReduceM is implemented via 3875-- unsafePerformIO, we need to force results that later 3876-- computations do not depend on, otherwise we lose debug messages. 3877thenReduce :: ReduceM a -> ReduceM b -> ReduceM b 3878thenReduce (ReduceM x) (ReduceM y) = ReduceM $ \ e -> x e `pseq` y e 3879{-# INLINE thenReduce #-} 3880 3881-- Andreas, 2021-05-14: 3882-- `seq` does not force evaluation order, the optimizier is allowed to replace 3883-- @ 3884-- a `seq` b` 3885-- @ 3886-- by: 3887-- @ 3888-- b `seq` a `seq` b 3889-- @ 3890-- see https://hackage.haskell.org/package/parallel/docs/Control-Parallel.html 3891-- 3892-- In contrast, `pseq` is only strict in its first argument, so such a permutation 3893-- is forbidden. 3894-- If we want to ensure that debug messages are printed before exceptions are 3895-- propagated, we need to use `pseq`, as in: 3896-- @ 3897-- unsafePerformIO (putStrLn "Black hawk is going down...") `pseq` throw HitByRPG 3898-- @ 3899beforeReduce :: ReduceM a -> ReduceM b -> ReduceM a 3900beforeReduce (ReduceM x) (ReduceM y) = ReduceM $ \ e -> 3901 let a = x e 3902 in a `pseq` y e `pseq` a 3903{-# INLINE beforeReduce #-} 3904 3905bindReduce :: ReduceM a -> (a -> ReduceM b) -> ReduceM b 3906bindReduce (ReduceM m) f = ReduceM $ \ e -> unReduceM (f $! m e) e 3907{-# INLINE bindReduce #-} 3908 3909instance Functor ReduceM where 3910 fmap = fmapReduce 3911 3912instance Applicative ReduceM where 3913 pure x = ReduceM (const x) 3914 (<*>) = apReduce 3915 (*>) = thenReduce 3916 (<*) = beforeReduce 3917 3918instance Monad ReduceM where 3919 return = pure 3920 (>>=) = bindReduce 3921 (>>) = (*>) 3922#if __GLASGOW_HASKELL__ < 808 3923 fail = Fail.fail 3924#endif 3925 3926instance Fail.MonadFail ReduceM where 3927 fail = error 3928 3929instance ReadTCState ReduceM where 3930 getTCState = ReduceM redSt 3931 locallyTCState l f = onReduceEnv $ mapRedSt $ over l f 3932 3933runReduceM :: ReduceM a -> TCM a 3934runReduceM m = TCM $ \ r e -> do 3935 s <- readIORef r 3936 E.evaluate $ unReduceM m $ ReduceEnv e s 3937 -- Andreas, 2021-05-13, issue #5379 3938 -- This was the following, which is apparently not strict enough 3939 -- to force all unsafePerformIOs... 3940 -- runReduceM m = do 3941 -- e <- askTC 3942 -- s <- getTC 3943 -- return $! unReduceM m (ReduceEnv e s) 3944 3945runReduceF :: (a -> ReduceM b) -> TCM (a -> b) 3946runReduceF f = do 3947 e <- askTC 3948 s <- getTC 3949 return $ \x -> unReduceM (f x) (ReduceEnv e s) 3950 3951instance MonadTCEnv ReduceM where 3952 askTC = ReduceM redEnv 3953 localTC = onReduceEnv . mapRedEnv 3954 3955-- Andrea comments (https://github.com/agda/agda/issues/1829#issuecomment-522312084): 3956-- 3957-- useR forces the result of projecting the lens, 3958-- this usually prevents retaining the whole structure when we only need a field. 3959-- 3960-- This fixes (or contributes to the fix of) the space leak issue #1829 (caching). 3961useR :: (ReadTCState m) => Lens' a TCState -> m a 3962useR l = do 3963 !x <- (^.l) <$> getTCState 3964 return x 3965 3966askR :: ReduceM ReduceEnv 3967askR = ReduceM ask 3968 3969localR :: (ReduceEnv -> ReduceEnv) -> ReduceM a -> ReduceM a 3970localR f = ReduceM . local f . unReduceM 3971 3972instance HasOptions ReduceM where 3973 pragmaOptions = useR stPragmaOptions 3974 commandLineOptions = do 3975 p <- useR stPragmaOptions 3976 cl <- stPersistentOptions . stPersistentState <$> getTCState 3977 return $ cl{ optPragmaOptions = p } 3978 3979class ( Applicative m 3980 , MonadTCEnv m 3981 , ReadTCState m 3982 , HasOptions m 3983 ) => MonadReduce m where 3984 liftReduce :: ReduceM a -> m a 3985 3986 default liftReduce :: (MonadTrans t, MonadReduce n, t n ~ m) => ReduceM a -> m a 3987 liftReduce = lift . liftReduce 3988 3989instance MonadReduce ReduceM where 3990 liftReduce = id 3991 3992instance MonadReduce m => MonadReduce (ChangeT m) 3993instance MonadReduce m => MonadReduce (ExceptT err m) 3994instance MonadReduce m => MonadReduce (IdentityT m) 3995instance MonadReduce m => MonadReduce (ListT m) 3996instance MonadReduce m => MonadReduce (MaybeT m) 3997instance MonadReduce m => MonadReduce (ReaderT r m) 3998instance MonadReduce m => MonadReduce (StateT w m) 3999instance (Monoid w, MonadReduce m) => MonadReduce (WriterT w m) 4000instance MonadReduce m => MonadReduce (BlockT m) 4001 4002--------------------------------------------------------------------------- 4003-- * Monad with read-only 'TCEnv' 4004--------------------------------------------------------------------------- 4005 4006-- | @MonadTCEnv@ made into its own dedicated service class. 4007-- This allows us to use 'MonadReader' for 'ReaderT' extensions of @TCM@. 4008class Monad m => MonadTCEnv m where 4009 askTC :: m TCEnv 4010 localTC :: (TCEnv -> TCEnv) -> m a -> m a 4011 4012 default askTC :: (MonadTrans t, MonadTCEnv n, t n ~ m) => m TCEnv 4013 askTC = lift askTC 4014 4015 default localTC 4016 :: (MonadTransControl t, MonadTCEnv n, t n ~ m) 4017 => (TCEnv -> TCEnv) -> m a -> m a 4018 localTC = liftThrough . localTC 4019 4020instance MonadTCEnv m => MonadTCEnv (ChangeT m) 4021instance MonadTCEnv m => MonadTCEnv (ExceptT err m) 4022instance MonadTCEnv m => MonadTCEnv (IdentityT m) 4023instance MonadTCEnv m => MonadTCEnv (MaybeT m) 4024instance MonadTCEnv m => MonadTCEnv (ReaderT r m) 4025instance MonadTCEnv m => MonadTCEnv (StateT s m) 4026instance (Monoid w, MonadTCEnv m) => MonadTCEnv (WriterT w m) 4027 4028instance MonadTCEnv m => MonadTCEnv (ListT m) where 4029 localTC = mapListT . localTC 4030 4031asksTC :: MonadTCEnv m => (TCEnv -> a) -> m a 4032asksTC f = f <$> askTC 4033 4034viewTC :: MonadTCEnv m => Lens' a TCEnv -> m a 4035viewTC l = asksTC (^. l) 4036 4037-- | Modify the lens-indicated part of the @TCEnv@ in a subcomputation. 4038locallyTC :: MonadTCEnv m => Lens' a TCEnv -> (a -> a) -> m b -> m b 4039locallyTC l = localTC . over l 4040 4041--------------------------------------------------------------------------- 4042-- * Monad with mutable 'TCState' 4043--------------------------------------------------------------------------- 4044 4045-- | @MonadTCState@ made into its own dedicated service class. 4046-- This allows us to use 'MonadState' for 'StateT' extensions of @TCM@. 4047class Monad m => MonadTCState m where 4048 getTC :: m TCState 4049 putTC :: TCState -> m () 4050 modifyTC :: (TCState -> TCState) -> m () 4051 4052 default getTC :: (MonadTrans t, MonadTCState n, t n ~ m) => m TCState 4053 getTC = lift getTC 4054 4055 default putTC :: (MonadTrans t, MonadTCState n, t n ~ m) => TCState -> m () 4056 putTC = lift . putTC 4057 4058 default modifyTC :: (MonadTrans t, MonadTCState n, t n ~ m) => (TCState -> TCState) -> m () 4059 modifyTC = lift . modifyTC 4060 4061instance MonadTCState m => MonadTCState (MaybeT m) 4062instance MonadTCState m => MonadTCState (ListT m) 4063instance MonadTCState m => MonadTCState (ExceptT err m) 4064instance MonadTCState m => MonadTCState (ReaderT r m) 4065instance MonadTCState m => MonadTCState (StateT s m) 4066instance MonadTCState m => MonadTCState (ChangeT m) 4067instance MonadTCState m => MonadTCState (IdentityT m) 4068instance (Monoid w, MonadTCState m) => MonadTCState (WriterT w m) 4069 4070-- ** @TCState@ accessors (no lenses) 4071 4072getsTC :: ReadTCState m => (TCState -> a) -> m a 4073getsTC f = f <$> getTCState 4074 4075-- | A variant of 'modifyTC' in which the computation is strict in the 4076-- new state. 4077modifyTC' :: MonadTCState m => (TCState -> TCState) -> m () 4078modifyTC' f = do 4079 s' <- getTC 4080 putTC $! f s' 4081 4082-- SEE TC.Monad.State 4083-- -- | Restore the 'TCState' after computation. 4084-- localTCState :: MonadTCState m => m a -> m a 4085-- localTCState = bracket_ getTC putTC 4086 4087-- ** @TCState@ accessors via lenses 4088 4089useTC :: ReadTCState m => Lens' a TCState -> m a 4090useTC l = do 4091 !x <- getsTC (^. l) 4092 return x 4093 4094infix 4 `setTCLens` 4095 4096-- | Overwrite the part of the 'TCState' focused on by the lens. 4097setTCLens :: MonadTCState m => Lens' a TCState -> a -> m () 4098setTCLens l = modifyTC . set l 4099 4100-- | Modify the part of the 'TCState' focused on by the lens. 4101modifyTCLens :: MonadTCState m => Lens' a TCState -> (a -> a) -> m () 4102modifyTCLens l = modifyTC . over l 4103 4104-- | Modify a part of the state monadically. 4105modifyTCLensM :: MonadTCState m => Lens' a TCState -> (a -> m a) -> m () 4106modifyTCLensM l f = putTC =<< l f =<< getTC 4107 4108-- | Modify the part of the 'TCState' focused on by the lens, and return some result. 4109stateTCLens :: MonadTCState m => Lens' a TCState -> (a -> (r , a)) -> m r 4110stateTCLens l f = stateTCLensM l $ return . f 4111 4112-- | Modify a part of the state monadically, and return some result. 4113stateTCLensM :: MonadTCState m => Lens' a TCState -> (a -> m (r , a)) -> m r 4114stateTCLensM l f = do 4115 s <- getTC 4116 (result , x) <- f $ s ^. l 4117 putTC $ set l x s 4118 return result 4119 4120 4121--------------------------------------------------------------------------- 4122-- ** Monad with capability to block a computation 4123--------------------------------------------------------------------------- 4124 4125class Monad m => MonadBlock m where 4126 4127 -- | `patternViolation b` aborts the current computation 4128 patternViolation :: Blocker -> m a 4129 4130 default patternViolation :: (MonadTrans t, MonadBlock n, m ~ t n) => Blocker -> m a 4131 patternViolation = lift . patternViolation 4132 4133 -- | `catchPatternErr handle m` runs m, handling pattern violations 4134 -- with `handle` (doesn't roll back the state) 4135 catchPatternErr :: (Blocker -> m a) -> m a -> m a 4136 4137newtype BlockT m a = BlockT { unBlockT :: ExceptT Blocker m a } 4138 deriving ( Functor, Applicative, Monad, MonadTrans -- , MonadTransControl -- requires GHC >= 8.2 4139 , MonadIO, Fail.MonadFail 4140 , ReadTCState, HasOptions 4141 , MonadTCEnv, MonadTCState, MonadTCM 4142 ) 4143 4144instance Monad m => MonadBlock (BlockT m) where 4145 patternViolation = BlockT . throwError 4146 catchPatternErr h f = BlockT $ catchError (unBlockT f) (unBlockT . h) 4147 4148instance Monad m => MonadBlock (ExceptT TCErr m) where 4149 patternViolation = throwError . PatternErr 4150 catchPatternErr h f = catchError f $ \case 4151 PatternErr b -> h b 4152 err -> throwError err 4153 4154runBlocked :: Monad m => BlockT m a -> m (Either Blocker a) 4155runBlocked = runExceptT . unBlockT 4156 4157instance MonadBlock m => MonadBlock (MaybeT m) where 4158 catchPatternErr h m = MaybeT $ catchPatternErr (runMaybeT . h) $ runMaybeT m 4159 4160instance MonadBlock m => MonadBlock (ReaderT e m) where 4161 catchPatternErr h m = ReaderT $ \ e -> 4162 let run = flip runReaderT e in catchPatternErr (run . h) (run m) 4163 4164--------------------------------------------------------------------------- 4165-- * Type checking monad transformer 4166--------------------------------------------------------------------------- 4167 4168-- | The type checking monad transformer. 4169-- Adds readonly 'TCEnv' and mutable 'TCState'. 4170newtype TCMT m a = TCM { unTCM :: IORef TCState -> TCEnv -> m a } 4171 4172-- | Type checking monad. 4173type TCM = TCMT IO 4174 4175{-# SPECIALIZE INLINE mapTCMT :: (forall a. IO a -> IO a) -> TCM a -> TCM a #-} 4176mapTCMT :: (forall a. m a -> n a) -> TCMT m a -> TCMT n a 4177mapTCMT f (TCM m) = TCM $ \ s e -> f (m s e) 4178 4179pureTCM :: MonadIO m => (TCState -> TCEnv -> a) -> TCMT m a 4180pureTCM f = TCM $ \ r e -> do 4181 s <- liftIO $ readIORef r 4182 return (f s e) 4183 4184-- One goal of the definitions and pragmas below is to inline the 4185-- monad operations as much as possible. This doesn't seem to have a 4186-- large effect on the performance of the normal executable, but (at 4187-- least on one machine/configuration) it has a massive effect on the 4188-- performance of the profiling executable [1], and reduces the time 4189-- attributed to bind from over 90% to about 25%. 4190-- 4191-- [1] When compiled with -auto-all and run with -p: roughly 750% 4192-- faster for one example. 4193 4194returnTCMT :: MonadIO m => a -> TCMT m a 4195returnTCMT = \x -> TCM $ \_ _ -> return x 4196{-# INLINE returnTCMT #-} 4197 4198bindTCMT :: MonadIO m => TCMT m a -> (a -> TCMT m b) -> TCMT m b 4199bindTCMT = \(TCM m) k -> TCM $ \r e -> m r e >>= \x -> unTCM (k x) r e 4200{-# INLINE bindTCMT #-} 4201 4202thenTCMT :: MonadIO m => TCMT m a -> TCMT m b -> TCMT m b 4203thenTCMT = \(TCM m1) (TCM m2) -> TCM $ \r e -> m1 r e >> m2 r e 4204{-# INLINE thenTCMT #-} 4205 4206instance MonadIO m => Functor (TCMT m) where 4207 fmap = fmapTCMT 4208 4209fmapTCMT :: MonadIO m => (a -> b) -> TCMT m a -> TCMT m b 4210fmapTCMT = \f (TCM m) -> TCM $ \r e -> fmap f (m r e) 4211{-# INLINE fmapTCMT #-} 4212 4213instance MonadIO m => Applicative (TCMT m) where 4214 pure = returnTCMT 4215 (<*>) = apTCMT 4216 4217apTCMT :: MonadIO m => TCMT m (a -> b) -> TCMT m a -> TCMT m b 4218apTCMT = \(TCM mf) (TCM m) -> TCM $ \r e -> ap (mf r e) (m r e) 4219{-# INLINE apTCMT #-} 4220 4221instance MonadTrans TCMT where 4222 lift m = TCM $ \_ _ -> m 4223 4224-- We want a special monad implementation of fail. 4225instance MonadIO m => Monad (TCMT m) where 4226 return = pure 4227 (>>=) = bindTCMT 4228 (>>) = (*>) 4229#if __GLASGOW_HASKELL__ < 808 4230 fail = Fail.fail 4231#endif 4232 4233instance MonadIO m => Fail.MonadFail (TCMT m) where 4234 fail = internalError 4235 4236instance MonadIO m => MonadIO (TCMT m) where 4237 liftIO m = TCM $ \ s env -> do 4238 liftIO $ wrap s (envRange env) $ do 4239 x <- m 4240 x `seq` return x 4241 where 4242 wrap s r m = E.catch m $ \ err -> do 4243 s <- readIORef s 4244 E.throwIO $ IOException s r err 4245 4246instance MonadIO m => MonadTCEnv (TCMT m) where 4247 askTC = TCM $ \ _ e -> return e 4248 localTC f (TCM m) = TCM $ \ s e -> m s (f e) 4249 4250instance MonadIO m => MonadTCState (TCMT m) where 4251 getTC = TCM $ \ r _e -> liftIO (readIORef r) 4252 putTC s = TCM $ \ r _e -> liftIO (writeIORef r s) 4253 modifyTC f = putTC . f =<< getTC 4254 4255instance MonadIO m => ReadTCState (TCMT m) where 4256 getTCState = getTC 4257 locallyTCState l f = bracket_ (useTC l <* modifyTCLens l f) (setTCLens l) 4258 4259instance MonadBlock TCM where 4260 patternViolation b = throwError (PatternErr b) 4261 catchPatternErr handle v = 4262 catchError_ v $ \err -> 4263 case err of 4264 -- Not putting s (which should really be the what's already there) makes things go 4265 -- a lot slower (+20% total time on standard library). How is that possible?? 4266 -- The problem is most likely that there are internal catchErrors which forgets the 4267 -- state. catchError should preserve the state on pattern violations. 4268 PatternErr u -> handle u 4269 _ -> throwError err 4270 4271 4272instance MonadError TCErr TCM where 4273 throwError = liftIO . E.throwIO 4274 catchError m h = TCM $ \ r e -> do -- now we are in the IO monad 4275 oldState <- readIORef r 4276 unTCM m r e `E.catch` \err -> do 4277 -- Reset the state, but do not forget changes to the persistent 4278 -- component. Not for pattern violations. 4279 case err of 4280 PatternErr{} -> return () 4281 _ -> 4282 liftIO $ do 4283 newState <- readIORef r 4284 writeIORef r $ oldState { stPersistentState = stPersistentState newState } 4285 unTCM (h err) r e 4286 4287-- | Like 'catchError', but resets the state completely before running the handler. 4288-- This means it also loses changes to the 'stPersistentState'. 4289-- 4290-- The intended use is to catch internal errors during debug printing. 4291-- In debug printing, we are not expecting state changes. 4292instance CatchImpossible TCM where 4293 catchImpossibleJust f m h = TCM $ \ r e -> do 4294 -- save the state 4295 s <- readIORef r 4296 catchImpossibleJust f (unTCM m r e) $ \ err -> do 4297 writeIORef r s 4298 unTCM (h err) r e 4299 4300instance MonadIO m => MonadReduce (TCMT m) where 4301 liftReduce = liftTCM . runReduceM 4302 4303instance (IsString a, MonadIO m) => IsString (TCMT m a) where 4304 fromString s = return (fromString s) 4305 4306-- | Strict (non-shortcut) semigroup. 4307-- 4308-- Note that there might be a lazy alternative, e.g., 4309-- for TCM All we might want 'Agda.Utils.Monad.and2M' as concatenation, 4310-- to shortcut conjunction in case we already have 'False'. 4311-- 4312instance {-# OVERLAPPABLE #-} (MonadIO m, Semigroup a) => Semigroup (TCMT m a) where 4313 (<>) = liftA2 (<>) 4314 4315-- | Strict (non-shortcut) monoid. 4316instance {-# OVERLAPPABLE #-} (MonadIO m, Semigroup a, Monoid a) => Monoid (TCMT m a) where 4317 mempty = pure mempty 4318 mappend = (<>) 4319 mconcat = mconcat <.> sequence 4320 4321instance {-# OVERLAPPABLE #-} (MonadIO m, Null a) => Null (TCMT m a) where 4322 empty = return empty 4323 null = __IMPOSSIBLE__ 4324 4325-- | Preserve the state of the failing computation. 4326catchError_ :: TCM a -> (TCErr -> TCM a) -> TCM a 4327catchError_ m h = TCM $ \r e -> 4328 unTCM m r e 4329 `E.catch` \err -> unTCM (h err) r e 4330 4331-- | Execute a finalizer even when an exception is thrown. 4332-- Does not catch any errors. 4333-- In case both the regular computation and the finalizer 4334-- throw an exception, the one of the finalizer is propagated. 4335finally_ :: TCM a -> TCM b -> TCM a 4336finally_ m f = do 4337 x <- m `catchError_` \ err -> f >> throwError err 4338 _ <- f 4339 return x 4340 4341-- | Embedding a TCM computation. 4342 4343class ( Applicative tcm, MonadIO tcm 4344 , MonadTCEnv tcm 4345 , MonadTCState tcm 4346 , HasOptions tcm 4347 ) => MonadTCM tcm where 4348 liftTCM :: TCM a -> tcm a 4349 4350 default liftTCM :: (MonadTCM m, MonadTrans t, tcm ~ t m) => TCM a -> tcm a 4351 liftTCM = lift . liftTCM 4352 4353{-# RULES "liftTCM/id" liftTCM = id #-} 4354instance MonadIO m => MonadTCM (TCMT m) where 4355 liftTCM = mapTCMT liftIO 4356 4357instance MonadTCM tcm => MonadTCM (ChangeT tcm) 4358instance MonadTCM tcm => MonadTCM (ExceptT err tcm) 4359instance MonadTCM tcm => MonadTCM (IdentityT tcm) 4360instance MonadTCM tcm => MonadTCM (ListT tcm) 4361instance MonadTCM tcm => MonadTCM (MaybeT tcm) 4362instance MonadTCM tcm => MonadTCM (ReaderT r tcm) 4363instance MonadTCM tcm => MonadTCM (StateT s tcm) 4364instance (Monoid w, MonadTCM tcm) => MonadTCM (WriterT w tcm) 4365 4366-- | We store benchmark statistics in an IORef. 4367-- This enables benchmarking pure computation, see 4368-- "Agda.Benchmarking". 4369instance MonadBench TCM where 4370 type BenchPhase TCM = Phase 4371 getBenchmark = liftIO $ getBenchmark 4372 putBenchmark = liftIO . putBenchmark 4373 finally = finally_ 4374 4375instance Null (TCM Doc) where 4376 empty = return empty 4377 null = __IMPOSSIBLE__ 4378 4379internalError :: (HasCallStack, MonadTCM tcm) => String -> tcm a 4380internalError s = withCallerCallStack $ \ loc -> 4381 liftTCM $ typeError' loc $ InternalError s 4382 4383-- | The constraints needed for 'typeError' and similar. 4384type MonadTCError m = (MonadTCEnv m, ReadTCState m, MonadError TCErr m) 4385 4386-- | Utility function for 1-arg constructed type errors. 4387-- Note that the @HasCallStack@ constraint is on the *resulting* function. 4388locatedTypeError :: MonadTCError m => (a -> TypeError) -> (HasCallStack => a -> m b) 4389locatedTypeError f e = withCallerCallStack (flip typeError' (f e)) 4390 4391genericError :: (HasCallStack, MonadTCError m) => String -> m a 4392genericError = locatedTypeError GenericError 4393 4394{-# SPECIALIZE genericDocError :: Doc -> TCM a #-} 4395genericDocError :: (HasCallStack, MonadTCError m) => Doc -> m a 4396genericDocError = locatedTypeError GenericDocError 4397 4398{-# SPECIALIZE typeError' :: CallStack -> TypeError -> TCM a #-} 4399typeError' :: MonadTCError m => CallStack -> TypeError -> m a 4400typeError' loc err = throwError =<< typeError'_ loc err 4401 4402{-# SPECIALIZE typeError :: HasCallStack => TypeError -> TCM a #-} 4403typeError :: (HasCallStack, MonadTCError m) => TypeError -> m a 4404typeError err = withCallerCallStack $ \loc -> throwError =<< typeError'_ loc err 4405 4406{-# SPECIALIZE typeError'_ :: CallStack -> TypeError -> TCM TCErr #-} 4407typeError'_ :: (MonadTCEnv m, ReadTCState m) => CallStack -> TypeError -> m TCErr 4408typeError'_ loc err = TypeError loc <$> getTCState <*> buildClosure err 4409 4410{-# SPECIALIZE typeError_ :: HasCallStack => TypeError -> TCM TCErr #-} 4411typeError_ :: (HasCallStack, MonadTCEnv m, ReadTCState m) => TypeError -> m TCErr 4412typeError_ = withCallerCallStack . flip typeError'_ 4413 4414-- | Running the type checking monad (most general form). 4415{-# SPECIALIZE runTCM :: TCEnv -> TCState -> TCM a -> IO (a, TCState) #-} 4416runTCM :: MonadIO m => TCEnv -> TCState -> TCMT m a -> m (a, TCState) 4417runTCM e s m = do 4418 r <- liftIO $ newIORef s 4419 a <- unTCM m r e 4420 s <- liftIO $ readIORef r 4421 return (a, s) 4422 4423-- | Running the type checking monad on toplevel (with initial state). 4424runTCMTop :: TCM a -> IO (Either TCErr a) 4425runTCMTop m = (Right <$> runTCMTop' m) `E.catch` (return . Left) 4426 4427runTCMTop' :: MonadIO m => TCMT m a -> m a 4428runTCMTop' m = do 4429 r <- liftIO $ newIORef initState 4430 unTCM m r initEnv 4431 4432-- | 'runSafeTCM' runs a safe 'TCM' action (a 'TCM' action which 4433-- cannot fail, except that it might raise 'IOException's) in the 4434-- initial environment. 4435 4436runSafeTCM :: TCM a -> TCState -> IO (a, TCState) 4437runSafeTCM m st = 4438 runTCM initEnv st m `E.catch` \(e :: TCErr) -> case e of 4439 IOException _ _ err -> E.throwIO err 4440 _ -> __IMPOSSIBLE__ 4441 4442-- | Runs the given computation in a separate thread, with /a copy/ of 4443-- the current state and environment. 4444-- 4445-- Note that Agda sometimes uses actual, mutable state. If the 4446-- computation given to @forkTCM@ tries to /modify/ this state, then 4447-- bad things can happen, because accesses are not mutually exclusive. 4448-- The @forkTCM@ function has been added mainly to allow the thread to 4449-- /read/ (a snapshot of) the current state in a convenient way. 4450-- 4451-- Note also that exceptions which are raised in the thread are not 4452-- propagated to the parent, so the thread should not do anything 4453-- important. 4454 4455forkTCM :: TCM a -> TCM () 4456forkTCM m = do 4457 s <- getTC 4458 e <- askTC 4459 liftIO $ void $ C.forkIO $ void $ runTCM e s m 4460 4461--------------------------------------------------------------------------- 4462-- * Names for generated definitions 4463--------------------------------------------------------------------------- 4464 4465-- | Base name for patterns in telescopes 4466patternInTeleName :: String 4467patternInTeleName = ".patternInTele" 4468 4469-- | Base name for extended lambda patterns 4470extendedLambdaName :: String 4471extendedLambdaName = ".extendedlambda" 4472 4473-- | Check whether we have an definition from an extended lambda. 4474isExtendedLambdaName :: A.QName -> Bool 4475isExtendedLambdaName = (extendedLambdaName `List.isPrefixOf`) . prettyShow . nameConcrete . qnameName 4476 4477-- | Name of absurdLambda definitions. 4478absurdLambdaName :: String 4479absurdLambdaName = ".absurdlambda" 4480 4481-- | Check whether we have an definition from an absurd lambda. 4482isAbsurdLambdaName :: QName -> Bool 4483isAbsurdLambdaName = (absurdLambdaName ==) . prettyShow . qnameName 4484 4485-- | Base name for generalized variable projections 4486generalizedFieldName :: String 4487generalizedFieldName = ".generalizedField-" 4488 4489-- | Check whether we have a generalized variable field 4490getGeneralizedFieldName :: A.QName -> Maybe String 4491getGeneralizedFieldName q 4492 | generalizedFieldName `List.isPrefixOf` strName = Just (drop (length generalizedFieldName) strName) 4493 | otherwise = Nothing 4494 where strName = prettyShow $ nameConcrete $ qnameName q 4495 4496--------------------------------------------------------------------------- 4497-- * KillRange instances 4498--------------------------------------------------------------------------- 4499 4500instance KillRange Signature where 4501 killRange (Sig secs defs rews) = killRange2 Sig secs defs rews 4502 4503instance KillRange Sections where 4504 killRange = fmap killRange 4505 4506instance KillRange Definitions where 4507 killRange = fmap killRange 4508 4509instance KillRange RewriteRuleMap where 4510 killRange = fmap killRange 4511 4512instance KillRange Section where 4513 killRange (Section tel) = killRange1 Section tel 4514 4515instance KillRange Definition where 4516 killRange (Defn ai name t pols occs gens gpars displ mut compiled inst copy ma nc inj copat blk def) = 4517 killRange18 Defn ai name t pols occs gens gpars displ mut compiled inst copy ma nc inj copat blk def 4518 -- TODO clarify: Keep the range in the defName field? 4519 4520instance KillRange NumGeneralizableArgs where 4521 killRange = id 4522 4523instance KillRange NLPat where 4524 killRange (PVar x y) = killRange2 PVar x y 4525 killRange (PDef x y) = killRange2 PDef x y 4526 killRange (PLam x y) = killRange2 PLam x y 4527 killRange (PPi x y) = killRange2 PPi x y 4528 killRange (PSort x) = killRange1 PSort x 4529 killRange (PBoundVar x y) = killRange2 PBoundVar x y 4530 killRange (PTerm x) = killRange1 PTerm x 4531 4532instance KillRange NLPType where 4533 killRange (NLPType s a) = killRange2 NLPType s a 4534 4535instance KillRange NLPSort where 4536 killRange (PType l) = killRange1 PType l 4537 killRange (PProp l) = killRange1 PProp l 4538 killRange s@(PInf f n) = s 4539 killRange PSizeUniv = PSizeUniv 4540 killRange PLockUniv = PLockUniv 4541 4542instance KillRange RewriteRule where 4543 killRange (RewriteRule q gamma f es rhs t c) = 4544 killRange6 RewriteRule q gamma f es rhs t c 4545 4546instance KillRange CompiledRepresentation where 4547 killRange = id 4548 4549 4550instance KillRange EtaEquality where 4551 killRange = id 4552 4553instance KillRange System where 4554 killRange (System tel sys) = System (killRange tel) (killRange sys) 4555 4556instance KillRange ExtLamInfo where 4557 killRange (ExtLamInfo m b sys) = killRange3 ExtLamInfo m b sys 4558 4559instance KillRange FunctionFlag where 4560 killRange = id 4561 4562instance KillRange CompKit where 4563 killRange = id 4564 4565instance KillRange Defn where 4566 killRange def = 4567 case def of 4568 Axiom a -> Axiom a 4569 DataOrRecSig n -> DataOrRecSig n 4570 GeneralizableVar -> GeneralizableVar 4571 AbstractDefn{} -> __IMPOSSIBLE__ -- only returned by 'getConstInfo'! 4572 Function cls comp ct tt covering inv mut isAbs delayed proj flags term extlam with -> 4573 killRange14 Function cls comp ct tt covering inv mut isAbs delayed proj flags term extlam with 4574 Datatype a b c d e f g h -> killRange7 Datatype a b c d e f g h 4575 Record a b c d e f g h i j k l -> killRange12 Record a b c d e f g h i j k l 4576 Constructor a b c d e f g h i j-> killRange10 Constructor a b c d e f g h i j 4577 Primitive a b c d e -> killRange5 Primitive a b c d e 4578 PrimitiveSort a b -> killRange2 PrimitiveSort a b 4579 4580instance KillRange MutualId where 4581 killRange = id 4582 4583instance KillRange c => KillRange (FunctionInverse' c) where 4584 killRange NotInjective = NotInjective 4585 killRange (Inverse m) = Inverse $ killRangeMap m 4586 4587instance KillRange TermHead where 4588 killRange SortHead = SortHead 4589 killRange PiHead = PiHead 4590 killRange (ConsHead q) = ConsHead $ killRange q 4591 killRange h@VarHead{} = h 4592 killRange UnknownHead = UnknownHead 4593 4594instance KillRange Projection where 4595 killRange (Projection a b c d e) = killRange5 Projection a b c d e 4596 4597instance KillRange ProjLams where 4598 killRange = id 4599 4600instance KillRange a => KillRange (Open a) where 4601 killRange = fmap killRange 4602 4603instance KillRange DisplayForm where 4604 killRange (Display n es dt) = killRange3 Display n es dt 4605 4606instance KillRange Polarity where 4607 killRange = id 4608 4609instance KillRange IsForced where 4610 killRange = id 4611 4612instance KillRange DoGeneralize where 4613 killRange = id 4614 4615instance KillRange DisplayTerm where 4616 killRange dt = 4617 case dt of 4618 DWithApp dt dts es -> killRange3 DWithApp dt dts es 4619 DCon q ci dts -> killRange3 DCon q ci dts 4620 DDef q dts -> killRange2 DDef q dts 4621 DDot v -> killRange1 DDot v 4622 DTerm v -> killRange1 DTerm v 4623 4624instance KillRange a => KillRange (Closure a) where 4625 killRange = id 4626 4627--------------------------------------------------------------------------- 4628-- NFData instances 4629--------------------------------------------------------------------------- 4630 4631instance NFData NumGeneralizableArgs where 4632 rnf NoGeneralizableArgs = () 4633 rnf (SomeGeneralizableArgs _) = () 4634 4635instance NFData TCErr where 4636 rnf (TypeError a b c) = rnf a `seq` rnf b `seq` rnf c 4637 rnf (Exception a b) = rnf a `seq` rnf b 4638 rnf (IOException a b c) = rnf a `seq` rnf b `seq` rnf (c == c) 4639 -- At the time of writing there is no 4640 -- NFData instance for E.IOException. 4641 rnf (PatternErr a) = rnf a 4642 4643-- | This instance could be optimised, some things are guaranteed to 4644-- be forced. 4645 4646instance NFData PreScopeState 4647 4648-- | This instance could be optimised, some things are guaranteed to 4649-- be forced. 4650 4651instance NFData PostScopeState 4652 4653instance NFData TCState 4654instance NFData DisambiguatedName 4655instance NFData MutualBlock 4656instance NFData PersistentTCState 4657instance NFData LoadedFileCache 4658instance NFData TypeCheckAction 4659instance NFData ModuleCheckMode 4660instance NFData ModuleInfo 4661instance NFData ForeignCode 4662instance NFData Interface 4663instance NFData a => NFData (Closure a) 4664instance NFData ProblemConstraint 4665instance NFData Constraint 4666instance NFData Signature 4667instance NFData Comparison 4668instance NFData CompareAs 4669instance NFData a => NFData (Open a) 4670instance NFData a => NFData (Judgement a) 4671instance NFData DoGeneralize 4672instance NFData GeneralizedValue 4673instance NFData MetaVariable 4674instance NFData Listener 4675instance NFData MetaInstantiation 4676instance NFData Frozen 4677instance NFData PrincipalArgTypeMetas 4678instance NFData TypeCheckingProblem 4679instance NFData RunMetaOccursCheck 4680instance NFData MetaInfo 4681instance NFData InteractionPoint 4682instance NFData InteractionPoints 4683instance NFData Overapplied 4684instance NFData t => NFData (IPBoundary' t) 4685instance NFData IPClause 4686instance NFData DisplayForm 4687instance NFData DisplayTerm 4688instance NFData NLPat 4689instance NFData NLPType 4690instance NFData NLPSort 4691instance NFData RewriteRule 4692instance NFData Definition 4693instance NFData Polarity 4694instance NFData IsForced 4695instance NFData Projection 4696instance NFData ProjLams 4697instance NFData CompilerPragma 4698instance NFData System 4699instance NFData ExtLamInfo 4700instance NFData EtaEquality 4701instance NFData FunctionFlag 4702instance NFData CompKit 4703instance NFData Defn 4704instance NFData Simplification 4705instance NFData AllowedReduction 4706instance NFData ReduceDefs 4707instance NFData PrimFun 4708instance NFData c => NFData (FunctionInverse' c) 4709instance NFData TermHead 4710instance NFData Call 4711instance NFData pf => NFData (Builtin pf) 4712instance NFData HighlightingLevel 4713instance NFData HighlightingMethod 4714instance NFData TCEnv 4715instance NFData UnquoteFlags 4716instance NFData AbstractMode 4717instance NFData ExpandHidden 4718instance NFData CandidateKind 4719instance NFData Candidate 4720instance NFData Warning 4721instance NFData RecordFieldWarning 4722instance NFData TCWarning 4723instance NFData CallInfo 4724instance NFData TerminationError 4725instance NFData SplitError 4726instance NFData NegativeUnification 4727instance NFData UnificationFailure 4728instance NFData UnquoteError 4729instance NFData TypeError 4730instance NFData LHSOrPatSyn 4731