~ubuntu-branches/ubuntu/wily/agda/wily-proposed

« back to all changes in this revision

Viewing changes to src/full/Agda/TypeChecking/Monad/Base.hs

  • Committer: Package Import Robot
  • Author(s): Iain Lane
  • Date: 2014-08-05 06:38:12 UTC
  • mfrom: (1.1.6)
  • Revision ID: package-import@ubuntu.com-20140805063812-io8e77niomivhd49
Tags: 2.4.0.2-1
* [6e140ac] Imported Upstream version 2.4.0.2
* [2049fc8] Update Build-Depends to match control
* [93dc4d4] Install the new primitives
* [e48f40f] Fix typo dev→doc

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
{-# LANGUAGE CPP, ExistentialQuantification, FlexibleContexts, Rank2Types,
2
 
             TypeSynonymInstances, MultiParamTypeClasses, FlexibleInstances,
3
 
             UndecidableInstances, DeriveDataTypeable, GeneralizedNewtypeDeriving,
4
 
             DeriveFunctor, DeriveFoldable, DeriveTraversable
5
 
  #-}
 
1
{-# LANGUAGE CPP #-}
 
2
{-# LANGUAGE DeriveDataTypeable #-}
 
3
{-# LANGUAGE DeriveFoldable #-}
 
4
{-# LANGUAGE DeriveFunctor #-}
 
5
{-# LANGUAGE DeriveTraversable #-}
 
6
{-# LANGUAGE ExistentialQuantification #-}
 
7
{-# LANGUAGE FlexibleContexts #-}
 
8
{-# LANGUAGE FlexibleInstances #-}
 
9
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
 
10
{-# LANGUAGE MultiParamTypeClasses #-}
 
11
{-# LANGUAGE NamedFieldPuns #-}
 
12
{-# LANGUAGE Rank2Types #-}
 
13
{-# LANGUAGE ScopedTypeVariables #-}
 
14
{-# LANGUAGE TypeSynonymInstances #-}
 
15
{-# LANGUAGE UndecidableInstances #-}
 
16
 
6
17
module Agda.TypeChecking.Monad.Base where
7
18
 
8
 
import Control.Arrow
 
19
import Control.Arrow ((***), first, second)
9
20
import qualified Control.Concurrent as C
10
21
import Control.DeepSeq
11
22
import Control.Exception as E
12
23
import Control.Monad.Error
13
24
import Control.Monad.State
14
25
import Control.Monad.Reader
 
26
import Control.Monad.Writer
 
27
import Control.Monad.Trans.Maybe
15
28
import Control.Applicative
 
29
 
16
30
import Data.Function
17
31
import Data.Int
 
32
import qualified Data.List as List
18
33
import Data.Map as Map
19
34
import Data.Set as Set
20
35
import Data.Sequence as Seq
22
37
import Data.Foldable
23
38
import Data.Traversable
24
39
import Data.IORef
25
 
import Data.Hashable
26
40
 
27
 
import Agda.Syntax.Common
 
41
import Agda.Syntax.Concrete (TopLevelModuleName)
 
42
import Agda.Syntax.Common hiding (Arg, Dom, NamedArg, ArgInfo)
 
43
import qualified Agda.Syntax.Common as Common
28
44
import qualified Agda.Syntax.Concrete as C
29
45
import qualified Agda.Syntax.Concrete.Definitions as D
30
46
import qualified Agda.Syntax.Abstract as A
31
 
import Agda.Syntax.Internal
 
47
import Agda.Syntax.Internal as I
32
48
import Agda.Syntax.Position
33
49
import Agda.Syntax.Scope.Base
34
 
import Agda.Utils.HashMap as HMap
35
50
 
36
51
import Agda.TypeChecking.CompiledClause
37
52
 
38
53
import Agda.Interaction.Exceptions
39
 
import {-# SOURCE #-} Agda.Interaction.FindFile
 
54
-- import {-# SOURCE #-} Agda.Interaction.FindFile
40
55
import Agda.Interaction.Options
41
 
import qualified Agda.Interaction.Highlighting.Range as R
42
56
import {-# SOURCE #-} Agda.Interaction.Response
43
 
  (InteractionOutputCallback, defaultInteractionOutputCallback)
 
57
  (InteractionOutputCallback, defaultInteractionOutputCallback, Response)
44
58
import Agda.Interaction.Highlighting.Precise
45
59
  (CompressedFile, HighlightingInfo)
46
 
import Data.Monoid
47
60
 
48
61
import qualified Agda.Compiler.JS.Syntax as JS
49
62
 
 
63
import Agda.TypeChecking.Monad.Base.Benchmark (Benchmark)
 
64
import qualified Agda.TypeChecking.Monad.Base.Benchmark as Benchmark
 
65
 
50
66
import Agda.Utils.FileName
51
67
import Agda.Utils.Fresh
52
 
import Agda.Utils.Monad
 
68
import Agda.Utils.HashMap as HMap
 
69
import Agda.Utils.Hash
53
70
import Agda.Utils.Permutation
54
71
import Agda.Utils.Pretty
55
72
import Agda.Utils.Time
77
94
         , stOccursCheckDefs   :: Set QName
78
95
           -- ^ Definitions to be considered during occurs check.
79
96
           --   Initialized to the current mutual block before the check.
 
97
           --   During occurs check, we remove definitions from this set
 
98
           --   as soon we have checked them.
80
99
         , stSignature         :: Signature
81
100
         , stImports           :: Signature
82
101
         , stImportedModules   :: Set ModuleName
92
111
           -- ^ Options applying to the current file. @OPTIONS@
93
112
           -- pragmas only affect this field.
94
113
         , stStatistics        :: Statistics
95
 
         , stExtLambdaTele     :: Map QName (Int , Int)
 
114
           -- ^ Counters to collect various statistics about meta variables etc.
96
115
         , stMutualBlocks      :: Map MutualId (Set QName)
97
116
         , stLocalBuiltins     :: BuiltinThings PrimFun
98
117
         , stImportedBuiltins  :: BuiltinThings PrimFun
100
119
           -- ^ Imports that should be generated by the compiler (this
101
120
           -- includes imports from imported modules).
102
121
         , stPersistent        :: PersistentTCState
103
 
         , stInteractionOutputCallback  :: InteractionOutputCallback
104
 
           -- ^ Callback fuction to call when there is a response
105
 
           --   to give to the interactive frontend.
106
 
           --   See the documentation of 'InteractionOutputCallback'.
107
 
         }
 
122
           -- ^ Options which apply to all files, unless overridden.
 
123
         }
108
124
 
109
125
-- | A part of the state which is not reverted when an error is thrown
110
126
-- or the state is reset.
112
128
data PersistentTCState = PersistentTCSt
113
129
  { stDecodedModules    :: DecodedModules
114
130
  , stPersistentOptions :: CommandLineOptions
115
 
    -- ^ Options which apply to all files, unless overridden.
 
131
  , stInteractionOutputCallback  :: InteractionOutputCallback
 
132
    -- ^ Callback function to call when there is a response
 
133
    --   to give to the interactive frontend.
 
134
    --   See the documentation of 'InteractionOutputCallback'.
 
135
  , stBenchmark         :: !Benchmark
 
136
    -- ^ Structure to track how much CPU time was spent on which Agda phase.
 
137
    --   Needs to be a strict field to avoid space leaks!
 
138
  }
 
139
 
 
140
-- | Empty persistent state.
 
141
 
 
142
initPersistentState :: PersistentTCState
 
143
initPersistentState = PersistentTCSt
 
144
  { stPersistentOptions         = defaultOptions
 
145
  , stDecodedModules            = Map.empty
 
146
  , stInteractionOutputCallback = defaultInteractionOutputCallback
 
147
  , stBenchmark                 = Benchmark.empty
116
148
  }
117
149
 
118
150
data FreshThings =
127
159
              }
128
160
    deriving (Show)
129
161
 
 
162
-- | Empty state of type checker.
 
163
 
130
164
initState :: TCState
131
 
initState =
132
 
    TCSt { stFreshThings       = (Fresh 0 0 0 (NameId 0 0) 0 0 0) { fProblem = 1 }
133
 
         , stMetaStore         = Map.empty
134
 
         , stSyntaxInfo        = mempty
135
 
         , stTokens            = mempty
136
 
         , stTermErrs          = Seq.empty
137
 
         , stInteractionPoints = Map.empty
138
 
         , stAwakeConstraints    = []
139
 
         , stSleepingConstraints = []
140
 
         , stDirty               = False
141
 
         , stOccursCheckDefs   = Set.empty
142
 
         , stSignature         = emptySignature
143
 
         , stImports           = emptySignature
144
 
         , stImportedModules   = Set.empty
145
 
         , stModuleToSource    = Map.empty
146
 
         , stVisitedModules    = Map.empty
147
 
         , stCurrentModule     = Nothing
148
 
         , stScope             = emptyScopeInfo
149
 
         , stPatternSyns       = Map.empty
150
 
         , stPatternSynImports = Map.empty
151
 
         , stPragmaOptions     = defaultInteractionOptions
152
 
         , stStatistics        = Map.empty
153
 
         , stExtLambdaTele     = Map.empty
154
 
         , stMutualBlocks      = Map.empty
155
 
         , stLocalBuiltins     = Map.empty
156
 
         , stImportedBuiltins  = Map.empty
157
 
         , stHaskellImports    = Set.empty
158
 
         , stPersistent        = PersistentTCSt
159
 
           { stPersistentOptions = defaultOptions
160
 
           , stDecodedModules    = Map.empty
161
 
           }
162
 
         , stInteractionOutputCallback = defaultInteractionOutputCallback
163
 
         }
 
165
initState = TCSt
 
166
  { stFreshThings          = (Fresh 0 0 0 (NameId 0 0) 0 0 0) { fProblem = 1 }
 
167
  , stMetaStore            = Map.empty
 
168
  , stSyntaxInfo           = mempty
 
169
  , stTokens               = mempty
 
170
  , stTermErrs             = Seq.empty
 
171
  , stInteractionPoints    = Map.empty
 
172
  , stAwakeConstraints     = []
 
173
  , stSleepingConstraints  = []
 
174
  , stDirty                = False
 
175
  , stOccursCheckDefs      = Set.empty
 
176
  , stSignature            = emptySignature
 
177
  , stImports              = emptySignature
 
178
  , stImportedModules      = Set.empty
 
179
  , stModuleToSource       = Map.empty
 
180
  , stVisitedModules       = Map.empty
 
181
  , stCurrentModule        = Nothing
 
182
  , stScope                = emptyScopeInfo
 
183
  , stPatternSyns          = Map.empty
 
184
  , stPatternSynImports    = Map.empty
 
185
  , stPragmaOptions        = defaultInteractionOptions
 
186
  , stStatistics           = Map.empty
 
187
  , stMutualBlocks         = Map.empty
 
188
  , stLocalBuiltins        = Map.empty
 
189
  , stImportedBuiltins     = Map.empty
 
190
  , stHaskellImports       = Set.empty
 
191
  , stPersistent           = initPersistentState
 
192
  }
164
193
 
165
194
stBuiltinThings :: TCState -> BuiltinThings PrimFun
166
195
stBuiltinThings s = stLocalBuiltins s `Map.union` stImportedBuiltins s
210
239
        where
211
240
            (i, f) = nextFresh $ stFreshThings s
212
241
 
 
242
 
 
243
---------------------------------------------------------------------------
 
244
-- ** Managing file names
 
245
---------------------------------------------------------------------------
 
246
 
 
247
-- | Maps top-level module names to the corresponding source file
 
248
-- names.
 
249
 
 
250
type ModuleToSource = Map TopLevelModuleName AbsolutePath
 
251
 
 
252
-- | Maps source file names to the corresponding top-level module
 
253
-- names.
 
254
 
 
255
type SourceToModule = Map AbsolutePath TopLevelModuleName
 
256
 
 
257
-- | Creates a 'SourceToModule' map based on 'stModuleToSource'.
 
258
 
 
259
sourceToModule :: TCM SourceToModule
 
260
sourceToModule =
 
261
  Map.fromList
 
262
     .  List.map (\(m, f) -> (f, m))
 
263
     .  Map.toList
 
264
     .  stModuleToSource
 
265
    <$> get
 
266
 
213
267
---------------------------------------------------------------------------
214
268
-- ** Interface
215
269
---------------------------------------------------------------------------
219
273
  , miWarnings   :: Bool
220
274
    -- ^ 'True' if warnings were encountered when the module was type
221
275
    -- checked.
222
 
  , miTimeStamp  :: ClockTime
223
 
    -- ^ The modification time stamp of the interface file when the
224
 
    -- interface was read or written. Alternatively, if warnings were
225
 
    -- encountered (in which case there may not be any up-to-date
226
 
    -- interface file), the time at which the interface was produced
227
 
    -- (approximately).
228
276
  }
229
277
 
230
278
-- Note that the use of 'C.TopLevelModuleName' here is a potential
232
280
-- identifiers.
233
281
 
234
282
type VisitedModules = Map C.TopLevelModuleName ModuleInfo
235
 
type DecodedModules = Map C.TopLevelModuleName (Interface, ClockTime)
 
283
type DecodedModules = Map C.TopLevelModuleName Interface
236
284
 
237
285
data Interface = Interface
238
 
        { iImportedModules :: [ModuleName]
239
 
        , iModuleName      :: ModuleName
240
 
        , iScope           :: Map ModuleName Scope
241
 
        , iInsideScope     :: ScopeInfo
242
 
        , iSignature       :: Signature
243
 
        , iBuiltin         :: BuiltinThings (String, QName)
244
 
        , iHaskellImports  :: Set String
245
 
                              -- ^ Haskell imports listed in
246
 
                              -- (transitively) imported modules are
247
 
                              -- not included here.
248
 
        , iHighlighting    :: HighlightingInfo
249
 
        , iPragmaOptions   :: [OptionsPragma]
250
 
                              -- ^ Pragma options set in the file.
251
 
        , iPatternSyns     :: A.PatternSynDefns
252
 
        }
253
 
    deriving (Typeable, Show)
 
286
  { iSourceHash      :: Hash
 
287
    -- ^ Hash of the source code.
 
288
  , iImportedModules :: [(ModuleName, Hash)]
 
289
    -- ^ Imported modules and their hashes.
 
290
  , iModuleName      :: ModuleName
 
291
    -- ^ Module name of this interface.
 
292
  , iScope           :: Map ModuleName Scope
 
293
  , iInsideScope     :: ScopeInfo
 
294
    -- ^ Scope after we loaded this interface.
 
295
    --   Used in 'Agda.Interaction.BasicOps.AtTopLevel'
 
296
    --   and     'Agda.Interaction.CommandLine.CommandLine.interactionLoop'.
 
297
  , iSignature       :: Signature
 
298
  , iBuiltin         :: BuiltinThings (String, QName)
 
299
  , iHaskellImports  :: Set String
 
300
                        -- ^ Haskell imports listed in
 
301
                        -- (transitively) imported modules are
 
302
                        -- not included here.
 
303
  , iHighlighting    :: HighlightingInfo
 
304
  , iPragmaOptions   :: [OptionsPragma]
 
305
                        -- ^ Pragma options set in the file.
 
306
  , iPatternSyns     :: A.PatternSynDefns
 
307
  }
 
308
  deriving (Typeable, Show)
 
309
 
 
310
-- | Combines the source hash and the (full) hashes of the imported modules.
 
311
iFullHash :: Interface -> Hash
 
312
iFullHash i = combineHashes $ iSourceHash i : List.map snd (iImportedModules i)
254
313
 
255
314
---------------------------------------------------------------------------
256
315
-- ** Closure
288
347
  }
289
348
  deriving (Typeable, Show)
290
349
 
 
350
instance HasRange ProblemConstraint where
 
351
  getRange = getRange . theConstraint
 
352
 
291
353
data Constraint
292
354
  = ValueCmp Comparison Type Term Term
293
355
  | ElimCmp [Polarity] Type Term [Elim] [Elim]
304
366
  | FindInScope MetaId [(Term, Type)]
305
367
  deriving (Typeable, Show)
306
368
 
 
369
instance HasRange Constraint where
 
370
  getRange (IsEmpty r t) = r
 
371
  getRange _ = noRange
 
372
{- no Range instances for Term, Type, Elm, Tele, Sort, Level, MetaId
 
373
  getRange (ValueCmp cmp a u v) = getRange (a,u,v)
 
374
  getRange (ElimCmp pol a v es es') = getRange (a,v,es,es')
 
375
  getRange (TypeCmp cmp a b) = getRange (a,b)
 
376
  getRange (TelCmp a b cmp tel tel') = getRange (a,b,tel,tel')
 
377
  getRange (SortCmp cmp s s') = getRange (s,s')
 
378
  getRange (LevelCmp cmp l l') = getRange (l,l')
 
379
  getRange (UnBlock x) = getRange x
 
380
  getRange (Guarded c pid) = getRange c
 
381
  getRange (FindInScope x cands) = getRange x
 
382
-}
 
383
 
307
384
data Comparison = CmpEq | CmpLeq
308
385
  deriving (Eq, Typeable)
309
386
 
311
388
  show CmpEq  = "="
312
389
  show CmpLeq = "=<"
313
390
 
 
391
-- | An extension of 'Comparison' to @>=@.
 
392
data CompareDirection = DirEq | DirLeq | DirGeq
 
393
  deriving (Eq, Typeable)
 
394
 
 
395
instance Show CompareDirection where
 
396
  show DirEq  = "="
 
397
  show DirLeq = "=<"
 
398
  show DirGeq = ">="
 
399
 
 
400
-- | Embed 'Comparison' into 'CompareDirection'.
 
401
fromCmp :: Comparison -> CompareDirection
 
402
fromCmp CmpEq  = DirEq
 
403
fromCmp CmpLeq = DirLeq
 
404
 
 
405
-- | Flip the direction of comparison.
 
406
flipCmp :: CompareDirection -> CompareDirection
 
407
flipCmp DirEq  = DirEq
 
408
flipCmp DirLeq = DirGeq
 
409
flipCmp DirGeq = DirLeq
 
410
 
 
411
-- | Turn a 'Comparison' function into a 'CompareDirection' function.
 
412
--
 
413
--   Property: @dirToCmp f (fromCmp cmp) = f cmp@
 
414
dirToCmp :: (Comparison -> a -> a -> c) -> CompareDirection -> a -> a -> c
 
415
dirToCmp cont DirEq  = cont CmpEq
 
416
dirToCmp cont DirLeq = cont CmpLeq
 
417
dirToCmp cont DirGeq = flip $ cont CmpLeq
 
418
 
314
419
---------------------------------------------------------------------------
315
420
-- * Open things
316
421
---------------------------------------------------------------------------
317
422
 
318
423
-- | A thing tagged with the context it came from.
319
 
data Open a = OpenThing [CtxId] a
 
424
data Open a = OpenThing { openThingCtxIds :: [CtxId], openThing :: a }
320
425
    deriving (Typeable, Show, Functor)
321
426
 
322
427
---------------------------------------------------------------------------
365
470
  EtaExpand       x   `compare` EtaExpand       y   = x `compare` y
366
471
  CheckConstraint x _ `compare` CheckConstraint y _ = x `compare` y
367
472
  EtaExpand{} `compare` CheckConstraint{} = LT
368
 
  CheckConstraint{} `compare` EtaExpand{} = Prelude.GT
 
473
  CheckConstraint{} `compare` EtaExpand{} = GT
369
474
 
370
475
-- | Frozen meta variable cannot be instantiated by unification.
371
476
--   This serves to prevent the completion of a definition by its use
382
487
        | Open               -- ^ unsolved
383
488
        | OpenIFS            -- ^ open, to be instantiated as "implicit from scope"
384
489
        | BlockedConst Term  -- ^ solution blocked by unsolved constraints
385
 
        | PostponedTypeCheckingProblem (Closure (A.Expr, Type, TCM Bool))
 
490
        | PostponedTypeCheckingProblem (Closure TypeCheckingProblem) (TCM Bool)
386
491
    deriving (Typeable)
387
492
 
 
493
data TypeCheckingProblem
 
494
  = CheckExpr A.Expr Type
 
495
  | CheckArgs ExpandHidden ExpandInstances Range [I.NamedArg A.Expr] Type Type (Args -> Type -> TCM Term)
 
496
  deriving (Typeable)
 
497
 
388
498
instance Show MetaInstantiation where
389
499
  show (InstV t) = "InstV (" ++ show t ++ ")"
390
500
  show (InstS s) = "InstS (" ++ show s ++ ")"
393
503
  show (BlockedConst t) = "BlockedConst (" ++ show t ++ ")"
394
504
  show (PostponedTypeCheckingProblem{}) = "PostponedTypeCheckingProblem (...)"
395
505
 
 
506
-- | Meta variable priority:
 
507
--   When we have an equation between meta-variables, which one
 
508
--   should be instantiated?
 
509
--
 
510
--   Higher value means higher priority to be instantiated.
396
511
newtype MetaPriority = MetaPriority Int
397
512
    deriving (Eq, Ord, Show)
398
513
 
426
541
 
427
542
type MetaStore = Map MetaId MetaVariable
428
543
 
 
544
instance HasRange MetaInfo where
 
545
  getRange = clValue . miClosRange
 
546
 
429
547
instance HasRange MetaVariable where
430
548
    getRange m = getRange $ getMetaInfo m
431
549
 
 
550
instance SetRange MetaInfo where
 
551
  setRange r m = m { miClosRange = (miClosRange m) { clValue = r }}
 
552
 
432
553
instance SetRange MetaVariable where
433
 
  setRange r m = m { mvInfo = (mvInfo m)
434
 
                     { miClosRange = (miClosRange (mvInfo m))
435
 
                       { clValue = r }}}
 
554
  setRange r m = m { mvInfo = setRange r (mvInfo m) }
436
555
 
437
556
normalMetaPriority :: MetaPriority
438
557
normalMetaPriority = MetaPriority 0
458
577
getMetaRelevance :: MetaVariable -> Relevance
459
578
getMetaRelevance = envRelevance . getMetaEnv
460
579
 
 
580
getMetaColors :: MetaVariable -> [Color]
 
581
getMetaColors = envColors . getMetaEnv
 
582
 
461
583
---------------------------------------------------------------------------
462
584
-- ** Interaction meta variables
463
585
---------------------------------------------------------------------------
464
586
 
465
 
type InteractionPoints = Map InteractionId MetaId
466
 
 
467
 
newtype InteractionId = InteractionId Nat
468
 
    deriving (Eq,Ord,Num,Integral,Real,Enum)
469
 
 
470
 
instance Show InteractionId where
471
 
    show (InteractionId x) = "?" ++ show x
 
587
-- | Interaction points are created by the scope checker who sets the range.
 
588
--   The meta variable is created by the type checker and then hooked up to the
 
589
--   interaction point.
 
590
data InteractionPoint = InteractionPoint
 
591
  { ipRange :: Range        -- ^ The position of the interaction point.
 
592
  , ipMeta  :: Maybe MetaId -- ^ The meta variable, if any, holding the type etc.
 
593
  }
 
594
 
 
595
instance Eq InteractionPoint where (==) = (==) `on` ipMeta
 
596
 
 
597
-- | Data structure managing the interaction points.
 
598
type InteractionPoints = Map InteractionId InteractionPoint
472
599
 
473
600
---------------------------------------------------------------------------
474
601
-- ** Signature
497
624
emptySignature :: Signature
498
625
emptySignature = Sig Map.empty HMap.empty
499
626
 
500
 
data DisplayForm = Display Nat [Term] DisplayTerm
501
 
                -- ^ The three arguments are:
502
 
                --
503
 
                --   * @n@: number of free variables;
504
 
                --
505
 
                --   * Patterns for arguments, one extra free var which
506
 
                --     represents pattern vars. There should @n@ of them.
507
 
                --
508
 
                --   * Display form. @n@ free variables.
509
 
  deriving (Typeable, Show)
510
 
 
511
 
data DisplayTerm = DWithApp [DisplayTerm] Args
512
 
                 | DCon QName [Arg DisplayTerm]
513
 
                 | DDef QName [Arg DisplayTerm]
514
 
                 | DDot Term
515
 
                 | DTerm Term
516
 
  deriving (Typeable, Show)
517
 
 
 
627
-- | A @DisplayForm@ is in essence a rewrite rule
 
628
--   @
 
629
--      q ts --> dt
 
630
--   @
 
631
--   for a defined symbol (could be a constructor as well) @q@.
 
632
--   The right hand side is a 'DisplayTerm' which is used to
 
633
--   'reify' to a more readable 'Abstract.Syntax'.
 
634
--
 
635
--   The patterns @ts@ are just terms, but @var 0@ is interpreted
 
636
--   as a hole.  Each occurrence of @var 0@ is a new hole (pattern var).
 
637
--   For each *occurrence* of @var0@ the rhs @dt@ has a free variable.
 
638
--   These are instantiated when matching a display form against a
 
639
--   term @q vs@ succeeds.
 
640
data DisplayForm = Display
 
641
  { dfFreeVars :: Nat
 
642
    -- ^ Number @n@ of free variables in 'dfRHS'.
 
643
  , dfPats     :: [Term]
 
644
    -- ^ Left hand side patterns, where @var 0@ stands for a pattern
 
645
    --   variable.  There should be @n@ occurrences of @var0@ in
 
646
    --   'dfPats'.
 
647
  , dfRHS      :: DisplayTerm
 
648
    -- ^ Right hand side, with @n@ free variables.
 
649
  }
 
650
  deriving (Typeable, Show)
 
651
 
 
652
-- | A structured presentation of a 'Term' for reification into
 
653
--   'Abstract.Syntax'.
 
654
data DisplayTerm
 
655
  = DWithApp DisplayTerm [DisplayTerm] Args
 
656
    -- ^ @(f vs | ws) us@.
 
657
    --   The first 'DisplayTerm' is the parent function @f@ with its args @vs@.
 
658
    --   The list of 'DisplayTerm's are the with expressions @ws@.
 
659
    --   The 'Args' are additional arguments @us@
 
660
    --   (possible in case the with-application is of function type).
 
661
  | DCon QName [Arg DisplayTerm]
 
662
    -- ^ @c vs@.
 
663
  | DDef QName [Arg DisplayTerm]
 
664
    -- ^ @d vs@.
 
665
  | DDot Term
 
666
    -- ^ @.v@.
 
667
  | DTerm Term
 
668
    -- ^ @v@.
 
669
  deriving (Typeable, Show)
 
670
 
 
671
-- | By default, we have no display form.
518
672
defaultDisplayForm :: QName -> [Open DisplayForm]
519
673
defaultDisplayForm c = []
520
674
 
 
675
defRelevance = argInfoRelevance . defArgInfo
 
676
defColors    = argInfoColors    . defArgInfo
 
677
 
521
678
data Definition = Defn
522
 
  { defRelevance      :: Relevance -- ^ Some defs can be irrelevant (but not hidden).
 
679
  { defArgInfo        :: ArgInfo -- ^ Hiding should not be used.
523
680
  , defName           :: QName
524
 
  , defType           :: Type         -- ^ Type of the lifted definition.
 
681
  , defType           :: Type    -- ^ Type of the lifted definition.
525
682
  , defPolarity       :: [Polarity]
526
683
  , defArgOccurrences :: [Occurrence]
527
684
  , defDisplay        :: [Open DisplayForm]
531
688
  }
532
689
    deriving (Typeable, Show)
533
690
 
 
691
-- | Create a definition with sensible defaults.
 
692
defaultDefn :: ArgInfo -> QName -> Type -> Defn -> Definition
 
693
defaultDefn info x t def = Defn
 
694
  { defArgInfo        = info
 
695
  , defName           = x
 
696
  , defType           = t
 
697
  , defPolarity       = []
 
698
  , defArgOccurrences = []
 
699
  , defDisplay        = defaultDisplayForm x
 
700
  , defMutual         = 0
 
701
  , defCompiledRep    = noCompiledRep
 
702
  , theDef            = def
 
703
  }
 
704
 
534
705
type HaskellCode = String
535
706
type HaskellType = String
536
707
type EpicCode    = String
541
712
      | HsType HaskellType
542
713
  deriving (Typeable, Show)
543
714
 
 
715
data HaskellExport = HsExport HaskellType String deriving (Show, Typeable)
 
716
 
544
717
-- | Polarity for equality and subtype checking.
545
718
data Polarity
546
719
  = Covariant      -- ^ monotone
551
724
 
552
725
data CompiledRepresentation = CompiledRep
553
726
  { compiledHaskell :: Maybe HaskellRepresentation
 
727
  , exportHaskell   :: Maybe HaskellExport
554
728
  , compiledEpic    :: Maybe EpicCode
555
729
  , compiledJS      :: Maybe JSCode
556
730
  }
557
731
  deriving (Typeable, Show)
558
732
 
559
733
noCompiledRep :: CompiledRepresentation
560
 
noCompiledRep = CompiledRep Nothing Nothing Nothing
 
734
noCompiledRep = CompiledRep Nothing Nothing Nothing Nothing
561
735
 
562
736
-- | Subterm occurrences for positivity checking.
563
737
--   The constructors are listed in increasing information they provide:
574
748
 
575
749
instance NFData Occurrence
576
750
 
 
751
-- | Additional information for projection 'Function's.
 
752
data Projection = Projection
 
753
  { projProper    :: Maybe QName
 
754
    -- ^ @Nothing@ if only projection-like, @Just q@ if record projection,
 
755
    --   where @q@ is the original projection name
 
756
    --   (current name could be from module app).
 
757
  , projFromType  :: QName
 
758
    -- ^ Type projected from.  Record type if @projProper = Just{}@.
 
759
  , projIndex     :: Int
 
760
    -- ^ Index of the record argument.
 
761
    --   Start counting with 1, because 0 means that
 
762
    --   it is already applied to the record.
 
763
    --   (Can happen in module instantiation.)
 
764
  , projDropPars  :: Term
 
765
    -- ^ Term @t@ to be be applied to record parameters and record value.
 
766
    --   The parameters will be dropped.
 
767
    --   In case of a proper projection, a postfix projection application
 
768
    --   will be created: @t = \ pars r -> r .p@
 
769
    --   In case of a projection-like function, just the function symbol
 
770
    --   is returned as 'Def':  @t = \ pars -> f@.
 
771
  , projArgInfo   :: I.ArgInfo
 
772
    -- ^ The info of the principal (record) argument.
 
773
  } deriving (Typeable, Show)
 
774
 
577
775
data Defn = Axiom
 
776
            -- ^ Postulate.
578
777
          | Function
579
778
            { funClauses        :: [Clause]
580
 
            , funCompiled       :: CompiledClauses
 
779
            , funCompiled       :: Maybe CompiledClauses
 
780
              -- ^ 'Nothing' while function is still type-checked.
 
781
              --   @Just cc@ after type and coverage checking and
 
782
              --   translation to case trees.
581
783
            , funInv            :: FunctionInverse
582
 
{- MOVED to Definition
583
 
            , funPolarity       :: [Polarity]
584
 
            , funArgOccurrences :: [Occurrence]
585
 
-}
586
784
            , funMutual         :: [QName]
587
785
              -- ^ Mutually recursive functions, @data@s and @record@s.
 
786
              --   Does not include this function.
588
787
            , funAbstr          :: IsAbstract
589
788
            , funDelayed        :: Delayed
590
789
              -- ^ Are the clauses of this definition delayed?
591
 
            , funProjection     :: Maybe (QName, Int)
 
790
            , funProjection     :: Maybe Projection
592
791
              -- ^ Is it a record projection?
593
792
              --   If yes, then return the name of the record type and index of
594
793
              --   the record argument.  Start counting with 1, because 0 means that
602
801
                                   -- instantiation?
603
802
            , funTerminates     :: Maybe Bool
604
803
              -- ^ Has this function been termination checked?  Did it pass?
 
804
            , funExtLam         :: Maybe (Int,Int)
 
805
              -- ^ Is this function generated from an extended lambda?
 
806
              --   If yes, then return the number of hidden and non-hidden lambda-lifted arguments
 
807
            , funWith           :: Maybe QName
 
808
              -- ^ Is this a generated with-function? If yes, then what's the
 
809
              --   name of the parent function.
605
810
            }
606
811
          | Datatype
607
 
            { dataPars           :: Nat           -- nof parameters
608
 
            , dataIxs            :: Nat           -- nof indices
609
 
            , dataInduction      :: Induction  -- data or codata?
610
 
            , dataClause         :: (Maybe Clause) -- this might be in an instantiated module
611
 
            , dataCons           :: [QName]        -- constructor names
 
812
            { dataPars           :: Nat            -- ^ Number of parameters.
 
813
            , dataSmallPars      :: Permutation    -- ^ Parameters that are maybe small.
 
814
            , dataNonLinPars     :: Drop Permutation  -- ^ Parameters that appear in indices.
 
815
            , dataIxs            :: Nat            -- ^ Number of indices.
 
816
            , dataInduction      :: Induction      -- ^ @data@ or @codata@ (legacy).
 
817
            , dataClause         :: (Maybe Clause) -- ^ This might be in an instantiated module.
 
818
            , dataCons           :: [QName]        -- ^ Constructor names.
612
819
            , dataSort           :: Sort
613
 
{- MOVED
614
 
            , dataPolarity       :: [Polarity]
615
 
            , dataArgOccurrences :: [Occurrence]
616
 
-}
617
 
            , dataMutual         :: [QName]        -- ^ Mutually recursive functions, @data@s and @record@s.
 
820
            , dataMutual         :: [QName]        -- ^ Mutually recursive functions, @data@s and @record@s.  Does not include this data type.
618
821
            , dataAbstr          :: IsAbstract
619
822
            }
620
823
          | Record
621
824
            { recPars           :: Nat                  -- ^ Number of parameters.
622
825
            , recClause         :: Maybe Clause
623
 
            , recCon            :: QName                -- ^ Constructor name.
 
826
            , recConHead        :: ConHead              -- ^ Constructor name and fields.
624
827
            , recNamedCon       :: Bool
625
 
            , recConType        :: Type                 -- ^ The record constructor's type.
626
 
            , recFields         :: [Arg A.QName]
627
 
            , recTel            :: Telescope            -- ^ The record field telescope
628
 
{- MOVED
629
 
            , recPolarity       :: [Polarity]
630
 
            , recArgOccurrences :: [Occurrence]
631
 
-}
632
 
            , recMutual         :: [QName]              -- ^ Mutually recursive functions, @data@s and @record@s.
633
 
            , recEtaEquality    :: Bool                 -- ^ Eta-expand at this record type.  @False@ for unguarded recursive records.
 
828
            , recConType        :: Type                 -- ^ The record constructor's type. (Includes record parameters.)
 
829
            , recFields         :: [Arg QName]
 
830
            , recTel            :: Telescope            -- ^ The record field telescope. (Includes record parameters.)
 
831
                                                        --   Note: @TelV recTel _ == telView' recConType@.
 
832
                                                        --   Thus, @recTel@ is redundant.
 
833
            , recMutual         :: [QName]              -- ^ Mutually recursive functions, @data@s and @record@s.  Does not include this record.
 
834
            , recEtaEquality    :: Bool                 -- ^ Eta-expand at this record type.  @False@ for unguarded recursive records and coinductive records.
634
835
            , recInduction      :: Induction            -- ^ 'Inductive' or 'Coinductive'?  Matters only for recursive records.
635
836
            , recRecursive      :: Bool                 -- ^ Recursive record.  Implies @recEtaEquality = False@.  Projections are not size-preserving.
636
837
            , recAbstr          :: IsAbstract
637
838
            }
638
839
          | Constructor
639
 
            { conPars   :: Nat         -- nof parameters
640
 
            , conSrcCon :: QName       -- original constructor (this might be in a module instance)
641
 
            , conData   :: QName       -- name of datatype or record type
 
840
            { conPars   :: Nat         -- ^ Number of parameters.
 
841
            , conSrcCon :: ConHead     -- ^ Name of (original) constructor and fields. (This might be in a module instance.)
 
842
            , conData   :: QName       -- ^ Name of datatype or record type.
642
843
            , conAbstr  :: IsAbstract
643
844
            , conInd    :: Induction   -- ^ Inductive or coinductive?
644
845
            }
645
846
          | Primitive
646
847
            { primAbstr :: IsAbstract
647
848
            , primName  :: String
648
 
            , primClauses :: Maybe [Clause]
649
 
              -- ^ 'Nothing' for primitive functions, @'Just'
650
 
              -- something@ for builtin functions.
 
849
            , primClauses :: [Clause]
 
850
              -- ^ 'null' for primitive functions, @not null@ for builtin functions.
651
851
            , primCompiled :: Maybe CompiledClauses
652
 
              -- ^ 'Nothing' for primitive functions, @'Just'
653
 
              -- something@ for builtin functions.
 
852
              -- ^ 'Nothing' for primitive functions,
 
853
              --   @'Just' something@ for builtin functions.
654
854
            }
655
855
            -- ^ Primitive or builtin functions.
656
856
    deriving (Typeable, Show)
657
857
 
 
858
-- | A template for creating 'Function' definitions, with sensible defaults.
 
859
emptyFunction :: Defn
 
860
emptyFunction = Function
 
861
  { funClauses     = []
 
862
  , funCompiled    = Nothing
 
863
  , funInv         = NotInjective
 
864
  , funMutual      = []
 
865
  , funAbstr       = ConcreteDef
 
866
  , funDelayed     = NotDelayed
 
867
  , funProjection  = Nothing
 
868
  , funStatic      = False
 
869
  , funCopy        = False
 
870
  , funTerminates  = Nothing
 
871
  , funExtLam      = Nothing
 
872
  , funWith        = Nothing
 
873
  }
 
874
 
 
875
 
 
876
recCon :: Defn -> QName
 
877
recCon Record{ recConHead } = conName recConHead
 
878
recCon _ = __IMPOSSIBLE__
 
879
 
658
880
defIsRecord :: Defn -> Bool
659
881
defIsRecord Record{} = True
660
882
defIsRecord _        = False
667
889
newtype Fields = Fields [(C.Name, Type)]
668
890
  deriving (Typeable)
669
891
 
670
 
data Reduced no yes = NoReduction no | YesReduction yes
 
892
-- | Did we encounter a simplifying reduction?
 
893
--   In terms of CIC, that would be a iota-reduction.
 
894
--   In terms of Agda, this is a constructor or literal
 
895
--   pattern that matched.
 
896
--   Just beta-reduction (substitution) or delta-reduction
 
897
--   (unfolding of definitions) does not count as simplifying?
 
898
 
 
899
data Simplification = YesSimplification | NoSimplification
 
900
  deriving (Typeable, Eq, Show)
 
901
 
 
902
instance Monoid Simplification where
 
903
  mempty = NoSimplification
 
904
  mappend YesSimplification _ = YesSimplification
 
905
  mappend NoSimplification  s = s
 
906
 
 
907
data Reduced no yes = NoReduction no | YesReduction Simplification yes
671
908
    deriving (Typeable, Functor)
672
909
 
673
 
data IsReduced = NotReduced | Reduced (Blocked ())
 
910
-- | Three cases: 1. not reduced, 2. reduced, but blocked, 3. reduced, not blocked.
 
911
data IsReduced
 
912
  = NotReduced
 
913
  | Reduced    (Blocked ())
 
914
 
674
915
data MaybeReduced a = MaybeRed
675
916
  { isReduced     :: IsReduced
676
917
  , ignoreReduced :: a
677
918
  }
678
919
  deriving (Functor)
679
920
 
 
921
instance IsProjElim e => IsProjElim (MaybeReduced e) where
 
922
  isProjElim = isProjElim . ignoreReduced
 
923
 
680
924
type MaybeReducedArgs = [MaybeReduced (Arg Term)]
 
925
type MaybeReducedElims = [MaybeReduced Elim]
681
926
 
682
927
notReduced :: a -> MaybeReduced a
683
928
notReduced x = MaybeRed NotReduced x
684
929
 
685
930
reduced :: Blocked (Arg Term) -> MaybeReduced (Arg Term)
686
931
reduced b = case fmap ignoreSharing <$> b of
687
 
  NotBlocked (Arg _ _ (MetaV x _)) -> MaybeRed (Reduced $ Blocked x ()) v
688
 
  _                                -> MaybeRed (Reduced $ () <$ b)      v
 
932
  NotBlocked (Common.Arg _ (MetaV x _)) -> MaybeRed (Reduced $ Blocked x ()) v
 
933
  _                                     -> MaybeRed (Reduced $ () <$ b)      v
689
934
  where
690
935
    v = ignoreBlocking b
691
936
 
 
937
-- | Controlling 'reduce'.
 
938
data AllowedReduction
 
939
  = ProjectionReductions -- ^ (Projection and) projection-like functions may be reduced.
 
940
  | FunctionReductions   -- ^ Functions which are not projections may be reduced.
 
941
  | LevelReductions      -- ^ Reduce @'Level'@ terms.
 
942
  deriving (Show, Eq, Ord, Enum, Bounded)
 
943
 
 
944
type AllowedReductions = [AllowedReduction]
 
945
 
 
946
allReductions = [minBound..maxBound]
 
947
 
692
948
data PrimFun = PrimFun
693
949
        { primFunName           :: QName
694
950
        , primFunArity          :: Arity
695
 
        , primFunImplementation :: [Arg Term] -> TCM (Reduced MaybeReducedArgs Term)
 
951
        , primFunImplementation :: [Arg Term] -> ReduceM (Reduced MaybeReducedArgs Term)
696
952
        }
697
953
    deriving (Typeable)
698
954
 
699
955
defClauses :: Definition -> [Clause]
700
956
defClauses Defn{theDef = Function{funClauses = cs}}        = cs
701
 
defClauses Defn{theDef = Primitive{primClauses = Just cs}} = cs
 
957
defClauses Defn{theDef = Primitive{primClauses = cs}}      = cs
702
958
defClauses Defn{theDef = Datatype{dataClause = Just c}}    = [c]
703
959
defClauses Defn{theDef = Record{recClause = Just c}}       = [c]
704
960
defClauses _                                               = []
705
961
 
706
962
defCompiled :: Definition -> Maybe CompiledClauses
707
 
defCompiled Defn{theDef = Function{funCompiled = cc}} = Just cc
 
963
defCompiled Defn{theDef = Function {funCompiled  = mcc}} = mcc
708
964
defCompiled Defn{theDef = Primitive{primCompiled = mcc}} = mcc
709
965
defCompiled _ = Nothing
710
966
 
719
975
defDelayed Defn{theDef = Function{funDelayed = d}} = d
720
976
defDelayed _                                       = NotDelayed
721
977
 
 
978
-- | Has the definition failed the termination checker?
 
979
defNonterminating :: Definition -> Bool
 
980
defNonterminating Defn{theDef = Function{funTerminates = Just False}} = True
 
981
defNonterminating _                                                   = False
 
982
 
722
983
-- | Is the definition just a copy created by a module instantiation?
723
984
defCopy :: Definition -> Bool
724
985
defCopy Defn{theDef = Function{funCopy = b}} = b
746
1007
 
747
1008
data TermHead = SortHead
748
1009
              | PiHead
749
 
              | ConHead QName
 
1010
              | ConsHead QName
750
1011
  deriving (Typeable, Eq, Ord, Show)
751
1012
 
752
1013
---------------------------------------------------------------------------
766
1027
-- ** Trace
767
1028
---------------------------------------------------------------------------
768
1029
 
769
 
data Call = CheckClause Type A.Clause (Maybe Clause)
 
1030
data Call = CheckClause Type A.SpineClause (Maybe Clause)
770
1031
          | forall a. CheckPattern A.Pattern Telescope Type (Maybe a)
771
1032
          | CheckLetBinding A.LetBinding (Maybe ())
772
1033
          | InferExpr A.Expr (Maybe (Term, Type))
773
 
          | CheckExpr A.Expr Type (Maybe Term)
 
1034
          | CheckExprCall A.Expr Type (Maybe Term)
774
1035
          | CheckDotPattern A.Expr Term (Maybe Constraints)
775
 
          | CheckPatternShadowing A.Clause (Maybe ())
 
1036
          | CheckPatternShadowing A.SpineClause (Maybe ())
776
1037
          | IsTypeCall A.Expr Sort (Maybe Type)
777
1038
          | IsType_ A.Expr (Maybe Type)
778
1039
          | InferVar Name (Maybe (Term, Type))
798
1059
    getRange (CheckClause _ c _)                   = getRange c
799
1060
    getRange (CheckPattern p _ _ _)                = getRange p
800
1061
    getRange (InferExpr e _)                       = getRange e
801
 
    getRange (CheckExpr e _ _)                     = getRange e
 
1062
    getRange (CheckExprCall e _ _)                 = getRange e
802
1063
    getRange (CheckLetBinding b _)                 = getRange b
803
1064
    getRange (IsTypeCall e s _)                    = getRange e
804
1065
    getRange (IsType_ e _)                         = getRange e
826
1087
-- ** Builtin things
827
1088
---------------------------------------------------------------------------
828
1089
 
829
 
data BuiltinDescriptor = BuiltinData (TCM Type) [String]
830
 
                       | BuiltinDataCons (TCM Type)
831
 
                       | BuiltinPrim String (Term -> TCM ())
832
 
                       | BuiltinPostulate Relevance (TCM Type)
833
 
                       | BuiltinUnknown (Maybe (TCM Type)) (Term -> TCM ())
 
1090
data BuiltinDescriptor
 
1091
  = BuiltinData (TCM Type) [String]
 
1092
  | BuiltinDataCons (TCM Type)
 
1093
  | BuiltinPrim String (Term -> TCM ())
 
1094
  | BuiltinPostulate Relevance (TCM Type)
 
1095
  | BuiltinUnknown (Maybe (TCM Type)) (Term -> Type -> TCM ())
 
1096
    -- ^ Builtin of any kind.
 
1097
    --   Type can be checked (@Just t@) or inferred (@Nothing@).
 
1098
    --   The second argument is the hook for the verification function.
834
1099
 
835
1100
data BuiltinInfo =
836
1101
   BuiltinInfo { builtinName :: String
907
1172
                -- ^ Are we checking an irrelevant argument? (=@Irrelevant@)
908
1173
                -- Then top-level irrelevant declarations are enabled.
909
1174
                -- Other value: @Relevant@, then only relevant decls. are avail.
 
1175
          , envColors              :: [Color]
910
1176
          , envDisplayFormsEnabled :: Bool
911
1177
                -- ^ Sometimes we want to disable display forms.
912
1178
          , envReifyInteractionPoints :: Bool
922
1188
                --   than 'envRange'.
923
1189
          , envCall  :: Maybe (Closure Call)
924
1190
                -- ^ what we're doing at the moment
925
 
          , envEmacs :: Bool
926
 
                -- ^ True when called from the Emacs mode.
927
1191
          , envHighlightingLevel  :: HighlightingLevel
928
1192
                -- ^ Set to 'None' when imported modules are
929
1193
                --   type-checked.
942
1206
                --   doing speculative checking, like solve instance metas, or
943
1207
                --   when updating might break abstraction, as is the case when
944
1208
                --   checking abstract definitions.
 
1209
          , envExpandLast :: ExpandHidden
 
1210
                -- ^ When type-checking an alias f=e, we do not want
 
1211
                -- to insert hidden arguments in the end, because
 
1212
                -- these will become unsolved metas.
 
1213
          , envAppDef :: Maybe QName
 
1214
                -- ^ We are reducing an application of this function.
 
1215
                -- (For debugging of incomplete matches only.)
 
1216
          , envSimplification :: Simplification
 
1217
                -- ^ Did we encounter a simplification (proper match)
 
1218
                --   during the current reduction process?
 
1219
          , envAllowedReductions :: AllowedReductions
 
1220
          , envPrintDomainFreePi :: Bool
 
1221
                -- ^ When True types will be omitted from printed pi types if they
 
1222
                --   can be inferred
 
1223
          , envInsideDotPattern :: Bool
 
1224
                -- ^ Used by the scope checker to make sure that certain forms
 
1225
                --   of expressions are not used inside dot patterns: extended
 
1226
                --   lambdas and let-expressions.
945
1227
          }
946
1228
    deriving (Typeable)
947
1229
 
956
1238
                , envSolvingConstraints  = False
957
1239
                , envActiveProblems      = [0]
958
1240
                , envAssignMetas         = True
959
 
                , envAbstractMode        = AbstractMode
 
1241
                , envAbstractMode        = ConcreteMode
 
1242
  -- Andreas, 2013-02-21:  This was 'AbstractMode' until now.
 
1243
  -- However, top-level checks for mutual blocks, such as
 
1244
  -- constructor-headedness, should not be able to look into
 
1245
  -- abstract definitions unless abstract themselves.
 
1246
  -- (See also discussion on issue 796.)
 
1247
  -- The initial mode should be 'ConcreteMode', ensuring you
 
1248
  -- can only look into abstract things in an abstract
 
1249
  -- definition (which sets 'AbstractMode').
960
1250
                , envRelevance           = Relevant
 
1251
                , envColors              = []
961
1252
                , envDisplayFormsEnabled = True
962
1253
                , envReifyInteractionPoints = True
963
1254
                , envEtaContractImplicit    = True
964
1255
                , envRange                  = noRange
965
1256
                , envHighlightingRange      = noRange
966
1257
                , envCall                   = Nothing
967
 
                , envEmacs                  = False
968
1258
                , envHighlightingLevel      = None
969
1259
                , envHighlightingMethod     = Indirect
970
1260
                , envModuleNestingLevel     = -1
971
1261
                , envAllowDestructiveUpdate = True
 
1262
                , envExpandLast             = ExpandLast
 
1263
                , envAppDef                 = Nothing
 
1264
                , envSimplification         = NoSimplification
 
1265
                , envAllowedReductions      = allReductions
 
1266
                , envPrintDomainFreePi      = False
 
1267
                , envInsideDotPattern       = False
972
1268
                }
973
1269
 
974
1270
---------------------------------------------------------------------------
995
1291
-- ** Abstract mode
996
1292
---------------------------------------------------------------------------
997
1293
 
998
 
data AbstractMode = AbstractMode       -- ^ abstract things in the current module can be accessed
999
 
                  | ConcreteMode       -- ^ no abstract things can be accessed
1000
 
                  | IgnoreAbstractMode -- ^ all abstract things can be accessed
1001
 
  deriving (Typeable)
 
1294
data AbstractMode
 
1295
  = AbstractMode        -- ^ Abstract things in the current module can be accessed.
 
1296
  | ConcreteMode        -- ^ No abstract things can be accessed.
 
1297
  | IgnoreAbstractMode  -- ^ All abstract things can be accessed.
 
1298
  deriving (Typeable, Show)
1002
1299
 
1003
1300
---------------------------------------------------------------------------
1004
1301
-- ** Insertion of implicit arguments
1007
1304
data ExpandHidden
1008
1305
  = ExpandLast      -- ^ Add implicit arguments in the end until type is no longer hidden 'Pi'.
1009
1306
  | DontExpandLast  -- ^ Do not append implicit arguments.
 
1307
  deriving (Eq)
1010
1308
 
1011
1309
data ExpandInstances
1012
1310
  = ExpandInstanceArguments
1034
1332
-- | Information about a call.
1035
1333
 
1036
1334
data CallInfo = CallInfo
1037
 
  { callInfoRange :: Range
1038
 
    -- ^ Range of the head identifier.
1039
 
  , callInfoCall :: String
1040
 
    -- ^ Formatted representation of the call.
1041
 
    --
1042
 
    -- ('Doc' would perhaps be better here, but 'Doc' doesn't come
1043
 
    -- with an 'Ord' instance.)
1044
 
  } deriving (Eq, Ord, Typeable, Show)
 
1335
  { callInfoTarget :: QName
 
1336
    -- ^ Target function name pretty-printed.
 
1337
  , callInfoRange :: Range
 
1338
    -- ^ Range of the target function.
 
1339
  , callInfoCall :: Closure Term
 
1340
    -- ^ To be formatted representation of the call.
 
1341
  } deriving Typeable
 
1342
 
 
1343
-- no Eq, Ord instances: too expensive! (see issues 851, 852)
 
1344
 
 
1345
-- | We only 'show' the name of the callee.
 
1346
instance Show CallInfo where show = show . callInfoTarget
 
1347
 
 
1348
instance Pretty CallInfo where pretty = text . show . callInfoTarget
1045
1349
 
1046
1350
-- | Information about a mutual block which did not pass the
1047
1351
-- termination checker.
1052
1356
    -- automatically generated functions.)
1053
1357
  , termErrCalls :: [CallInfo]
1054
1358
    -- ^ The problematic call sites.
1055
 
  } deriving (Typeable, Show, Eq)
1056
 
 
1057
 
{-
1058
 
instance Eq TerminationError where
1059
 
  (==) = (==) `on` termErrCalls
1060
 
-}
 
1359
  } deriving (Typeable, Show)
 
1360
 
 
1361
 
 
1362
data SplitError = NotADatatype (Closure Type) -- ^ neither data type nor record
 
1363
                | IrrelevantDatatype (Closure Type)   -- ^ data type, but in irrelevant position
 
1364
                | CoinductiveDatatype (Closure Type)  -- ^ coinductive data type
 
1365
{- UNUSED
 
1366
                | NoRecordConstructor Type  -- ^ record type, but no constructor
 
1367
 -}
 
1368
                | CantSplit QName Telescope Args Args [Term]
 
1369
                | GenericSplitError String
 
1370
  deriving (Show)
 
1371
 
 
1372
instance Error SplitError where
 
1373
  noMsg  = strMsg ""
 
1374
  strMsg = GenericSplitError
1061
1375
 
1062
1376
data TypeError
1063
1377
        = InternalError String
1090
1402
          -- ^ Indices (variables), index expressions (with
1091
1403
          -- constructors applied to reconstructed parameters),
1092
1404
          -- parameters.
1093
 
        | DoesNotConstructAnElementOf QName Term -- ^ constructor, type
 
1405
        | CantResolveOverloadedConstructorsTargetingSameDatatype QName [QName]
 
1406
          -- ^ Datatype, constructors.
 
1407
        | DoesNotConstructAnElementOf QName Type -- ^ constructor, type
1094
1408
        | DifferentArities
1095
1409
            -- ^ Varying number of arguments for a function.
1096
 
        | WrongHidingInLHS Type
 
1410
        | WrongHidingInLHS
1097
1411
            -- ^ The left hand side of a function definition has a hidden argument
1098
1412
            --   where a non-hidden was expected.
1099
1413
        | WrongHidingInLambda Type
1100
1414
            -- ^ Expected a non-hidden function and found a hidden lambda.
1101
1415
        | WrongHidingInApplication Type
1102
1416
            -- ^ A function is applied to a hidden argument where a non-hidden was expected.
 
1417
        | WrongNamedArgument (I.NamedArg A.Expr)
 
1418
            -- ^ A function is applied to a hidden named argument it does not have.
1103
1419
        | WrongIrrelevanceInLambda Type
1104
1420
            -- ^ Expected a relevant function and found an irrelevant lambda.
 
1421
        | HidingMismatch Hiding Hiding
 
1422
            -- ^ The given hiding does not correspond to the expected hiding.
 
1423
        | RelevanceMismatch Relevance Relevance
 
1424
            -- ^ The given relevance does not correspond to the expected relevane.
 
1425
        | ColorMismatch [Color] [Color]
 
1426
            -- ^ The given color does not correspond to the expected color.
1105
1427
        | NotInductive Term
1106
1428
          -- ^ The term does not correspond to an inductive data type.
1107
1429
        | UninstantiatedDotPattern A.Expr
1108
1430
        | IlltypedPattern A.Pattern Type
 
1431
        | IllformedProjectionPattern A.Pattern
 
1432
        | CannotEliminateWithPattern (A.NamedArg A.Pattern) Type
1109
1433
        | TooManyArgumentsInLHS Type
1110
1434
        | WrongNumberOfConstructorArguments QName Nat Nat
1111
1435
        | ShouldBeEmpty Type [Pattern]
1115
1439
            -- ^ The given type should have been a pi.
1116
1440
        | ShouldBeRecordType Type
1117
1441
        | ShouldBeRecordPattern Pattern
 
1442
        | NotAProjectionPattern (A.NamedArg A.Pattern)
1118
1443
        | NotAProperTerm
1119
1444
        | SetOmegaNotValidType
 
1445
        | InvalidType Term
 
1446
            -- ^ This term is not a type expression.
1120
1447
        | SplitOnIrrelevant A.Pattern (Dom Type)
1121
1448
        | DefinitionIsIrrelevant QName
1122
1449
        | VariableIsIrrelevant Name
1123
 
        | UnequalLevel Comparison Term Term
 
1450
--        | UnequalLevel Comparison Term Term  -- UNUSED
1124
1451
        | UnequalTerms Comparison Term Term Type
1125
1452
        | UnequalTypes Comparison Type Type
1126
 
        | UnequalTelescopes Comparison Telescope Telescope
 
1453
--      | UnequalTelescopes Comparison Telescope Telescope -- UNUSED
1127
1454
        | UnequalRelevance Comparison Term Term
1128
1455
            -- ^ The two function types have different relevance.
1129
1456
        | UnequalHiding Term Term
1130
1457
            -- ^ The two function types have different hiding.
 
1458
        | UnequalColors Term Term
 
1459
            -- ^ The two function types have different color.
1131
1460
        | UnequalSorts Sort Sort
1132
1461
        | UnequalBecauseOfUniverseConflict Comparison Term Term
1133
1462
        | HeterogeneousEquality Term Type Term Type
1147
1476
        | NoSuchPrimitiveFunction String
1148
1477
        | ShadowedModule C.Name [A.ModuleName]
1149
1478
        | BuiltinInParameterisedModule String
 
1479
        | IllegalLetInTelescope C.TypedBinding
1150
1480
        | NoRHSRequiresAbsurdPattern [NamedArg A.Pattern]
1151
1481
        | AbsurdPatternRequiresNoRHS [NamedArg A.Pattern]
1152
1482
        | TooFewFields QName [C.Name]
1158
1488
        | FieldOutsideRecord
1159
1489
        | ModuleArityMismatch A.ModuleName Telescope [NamedArg A.Expr]
1160
1490
    -- Coverage errors
1161
 
        | IncompletePatternMatching Term Args -- can only happen if coverage checking is switched off
 
1491
    -- TODO: Remove some of the constructors in this section, now that
 
1492
    -- the SplitError constructor has been added?
 
1493
        | IncompletePatternMatching Term [Elim] -- can only happen if coverage checking is switched off
1162
1494
        | CoverageFailure QName [[Arg Pattern]]
1163
1495
        | UnreachableClauses QName [[Arg Pattern]]
1164
1496
        | CoverageCantSplitOn QName Telescope Args Args
1165
1497
        | CoverageCantSplitIrrelevantType Type
1166
1498
        | CoverageCantSplitType Type
 
1499
        | WithoutKError Type Term Term
 
1500
        | SplitError SplitError
1167
1501
    -- Positivity errors
1168
1502
        | NotStrictlyPositive QName [Occ]
1169
1503
    -- Import errors
1265
1599
 
1266
1600
instance Exception TCErr
1267
1601
 
 
1602
-----------------------------------------------------------------------------
 
1603
-- * The reduce monad
 
1604
-----------------------------------------------------------------------------
 
1605
 
 
1606
-- | Environment of the reduce monad.
 
1607
data ReduceEnv = ReduceEnv
 
1608
  { redEnv :: TCEnv    -- ^ Read only access to environment.
 
1609
  , redSt  :: TCState  -- ^ Read only access to state (signature, metas...).
 
1610
  }
 
1611
 
 
1612
mapRedEnv :: (TCEnv -> TCEnv) -> ReduceEnv -> ReduceEnv
 
1613
mapRedEnv f s = s { redEnv = f (redEnv s) }
 
1614
 
 
1615
mapRedSt :: (TCState -> TCState) -> ReduceEnv -> ReduceEnv
 
1616
mapRedSt f s = s { redSt = f (redSt s) }
 
1617
 
 
1618
mapRedEnvSt :: (TCEnv -> TCEnv) -> (TCState -> TCState) -> ReduceEnv
 
1619
            -> ReduceEnv
 
1620
mapRedEnvSt f g (ReduceEnv e s) = ReduceEnv (f e) (g s)
 
1621
 
 
1622
newtype ReduceM a = ReduceM { unReduceM :: Reader ReduceEnv a }
 
1623
  deriving (Functor, Applicative, Monad)
 
1624
 
 
1625
runReduceM :: ReduceM a -> TCM a
 
1626
runReduceM m = do
 
1627
  e <- ask
 
1628
  s <- get
 
1629
  return $ runReader (unReduceM m) (ReduceEnv e s)
 
1630
 
 
1631
instance MonadReader TCEnv ReduceM where
 
1632
  ask = redEnv <$> ReduceM ask
 
1633
  local f = ReduceM . local (mapRedEnv f) . unReduceM
 
1634
 
1268
1635
---------------------------------------------------------------------------
1269
1636
-- * Type checking monad transformer
1270
1637
---------------------------------------------------------------------------
1271
1638
 
1272
1639
newtype TCMT m a = TCM { unTCM :: IORef TCState -> TCEnv -> m a }
1273
1640
 
 
1641
-- TODO: make dedicated MonadTCEnv and MonadTCState service classes
 
1642
 
1274
1643
instance MonadIO m => MonadReader TCEnv (TCMT m) where
1275
1644
  ask = TCM $ \s e -> return e
1276
1645
  local f (TCM m) = TCM $ \s e -> m s (f e)
1318
1687
instance MonadIO m => MonadTCM (TCMT m) where
1319
1688
    liftTCM = mapTCMT liftIO
1320
1689
 
 
1690
instance MonadTCM tcm => MonadTCM (MaybeT tcm) where
 
1691
  liftTCM = lift . liftTCM
 
1692
 
1321
1693
instance (Error err, MonadTCM tcm) => MonadTCM (ErrorT err tcm) where
1322
1694
  liftTCM = lift . liftTCM
1323
1695
 
 
1696
instance (Monoid w, MonadTCM tcm) => MonadTCM (WriterT w tcm) where
 
1697
  liftTCM = lift . liftTCM
 
1698
 
 
1699
{- The following is not possible since MonadTCM needs to be a
 
1700
-- MonadState TCState and a MonadReader TCEnv
 
1701
 
 
1702
instance (MonadTCM tcm) => MonadTCM (StateT s tcm) where
 
1703
  liftTCM = lift . liftTCM
 
1704
 
 
1705
instance (MonadTCM tcm) => MonadTCM (ReaderT r tcm) where
 
1706
  liftTCM = lift . liftTCM
 
1707
-}
 
1708
 
1324
1709
instance MonadTrans TCMT where
1325
1710
    lift m = TCM $ \_ _ -> m
1326
1711
 
1343
1728
 
1344
1729
returnTCMT :: MonadIO m => a -> TCMT m a
1345
1730
returnTCMT = \x -> TCM $ \_ _ -> return x
1346
 
{-# RULES "returnTCMT"
1347
 
      returnTCMT = \x -> TCM $ \_ _ -> return x
1348
 
  #-}
1349
1731
{-# INLINE returnTCMT #-}
1350
 
{-# SPECIALIZE INLINE returnTCMT :: a -> TCM a #-}
1351
1732
 
1352
1733
bindTCMT :: MonadIO m => TCMT m a -> (a -> TCMT m b) -> TCMT m b
1353
1734
bindTCMT = \(TCM m) k -> TCM $ \r e -> m r e >>= \x -> unTCM (k x) r e
1354
 
{-# RULES "bindTCMT"
1355
 
      bindTCMT = \(TCM m) k -> TCM $ \r e ->
1356
 
                   m r e >>= \x -> unTCM (k x) r e
1357
 
  #-}
1358
1735
{-# INLINE bindTCMT #-}
1359
 
{-# SPECIALIZE INLINE bindTCMT :: TCM a -> (a -> TCM b) -> TCM b #-}
1360
1736
 
1361
1737
thenTCMT :: MonadIO m => TCMT m a -> TCMT m b -> TCMT m b
1362
1738
thenTCMT = \(TCM m1) (TCM m2) -> TCM $ \r e -> m1 r e >> m2 r e
1363
 
{-# RULES "thenTCMT"
1364
 
      thenTCMT = \(TCM m1) (TCM m2) -> TCM $ \r e -> m1 r e >> m2 r e
1365
 
  #-}
1366
1739
{-# INLINE thenTCMT #-}
1367
 
{-# SPECIALIZE INLINE thenTCMT :: TCM a -> TCM b -> TCM b #-}
1368
1740
 
1369
1741
instance MonadIO m => Functor (TCMT m) where
1370
1742
    fmap = fmapTCMT
1371
1743
 
1372
1744
fmapTCMT :: MonadIO m => (a -> b) -> TCMT m a -> TCMT m b
1373
1745
fmapTCMT = \f (TCM m) -> TCM $ \r e -> liftM f (m r e)
1374
 
{-# RULES "fmapTCMT"
1375
 
      fmapTCMT = \f (TCM m) -> TCM $ \r e -> liftM f (m r e)
1376
 
  #-}
1377
1746
{-# INLINE fmapTCMT #-}
1378
 
{-# SPECIALIZE INLINE fmapTCMT :: (a -> b) -> TCM a -> TCM b #-}
1379
1747
 
1380
1748
instance MonadIO m => Applicative (TCMT m) where
1381
1749
    pure  = returnTCMT
1383
1751
 
1384
1752
apTCMT :: MonadIO m => TCMT m (a -> b) -> TCMT m a -> TCMT m b
1385
1753
apTCMT = \(TCM mf) (TCM m) -> TCM $ \r e -> ap (mf r e) (m r e)
1386
 
{-# RULES "apTCMT"
1387
 
      apTCMT = \(TCM mf) (TCM m) -> TCM $ \r e -> ap (mf r e) (m r e)
1388
 
  #-}
1389
1754
{-# INLINE apTCMT #-}
1390
 
{-# SPECIALIZE INLINE apTCMT :: TCM (a -> b) -> TCM a -> TCM b #-}
1391
1755
 
1392
1756
instance MonadIO m => MonadIO (TCMT m) where
1393
1757
  liftIO m = TCM $ \s e ->
1416
1780
    s  <- get
1417
1781
    throwError $ TypeError s cl
1418
1782
 
1419
 
runTCM :: TCMT IO a -> IO (Either TCErr a)
1420
 
runTCM m = (Right <$> runTCM' m) `E.catch` (return . Left)
1421
 
 
1422
 
runTCM' :: MonadIO m => TCMT m a -> m a
1423
 
runTCM' m = do
 
1783
-- | Running the type checking monad (most general form).
 
1784
{-# SPECIALIZE runTCM :: TCEnv -> TCState -> TCM a -> IO (a, TCState) #-}
 
1785
runTCM :: MonadIO m => TCEnv -> TCState -> TCMT m a -> m (a, TCState)
 
1786
runTCM e s m = do
 
1787
  r <- liftIO $ newIORef s
 
1788
  a <- unTCM m r e
 
1789
  s <- liftIO $ readIORef r
 
1790
  return (a, s)
 
1791
 
 
1792
-- | Running the type checking monad on toplevel (with initial state).
 
1793
runTCMTop :: TCM a -> IO (Either TCErr a)
 
1794
runTCMTop m = (Right <$> runTCMTop' m) `E.catch` (return . Left)
 
1795
 
 
1796
runTCMTop' :: MonadIO m => TCMT m a -> m a
 
1797
runTCMTop' m = do
1424
1798
  r <- liftIO $ newIORef initState
1425
1799
  unTCM m r initEnv
1426
1800
 
 
1801
-- | 'runSafeTCM' runs a safe 'TCM' action (a 'TCM' action which cannot fail)
 
1802
--   in the initial environment.
 
1803
 
 
1804
runSafeTCM :: TCM a -> TCState -> IO (a, TCState)
 
1805
runSafeTCM m st = runTCM initEnv st m `E.catch` (\ (e :: TCErr) -> __IMPOSSIBLE__)
 
1806
-- runSafeTCM m st = either__IMPOSSIBLE__ return <$> do
 
1807
--     -- Errors must be impossible.
 
1808
--     runTCM $ do
 
1809
--         put st
 
1810
--         a <- m
 
1811
--         st <- get
 
1812
--         return (a, st)
 
1813
 
1427
1814
-- | Runs the given computation in a separate thread, with /a copy/ of
1428
1815
-- the current state and environment.
1429
1816
--
1442
1828
forkTCM m = do
1443
1829
  s <- get
1444
1830
  e <- ask
1445
 
  liftIO $ C.forkIO $ do
1446
 
    runTCM $ local (\_ -> e) $ do
1447
 
      put s
1448
 
      m
1449
 
    return ()
1450
 
  return ()
1451
 
 
 
1831
  liftIO $ void $ C.forkIO $ void $ runTCM e s m
1452
1832
 
1453
1833
 
1454
1834
-- | Base name for extended lambda patterns
1455
1835
extendlambdaname = ".extendedlambda"
 
1836
 
 
1837
-- | Name of absurdLambda definitions.
 
1838
absurdLambdaName = ".absurdlambda"
 
1839
 
 
1840
-- | Check whether we have an definition from an absurd lambda.
 
1841
isAbsurdLambdaName :: QName -> Bool
 
1842
isAbsurdLambdaName (QName _ x) | show x == absurdLambdaName = True
 
1843
isAbsurdLambdaName _ = False