~ubuntu-branches/ubuntu/trusty/agda/trusty

« back to all changes in this revision

Viewing changes to src/full/Agda/TypeChecking/Rules/Term.hs

  • Committer: Package Import Robot
  • Author(s): Iain Lane, Kiwamu Okabe, Iain Lane
  • Date: 2013-04-10 11:46:43 UTC
  • mfrom: (4.1.5 experimental)
  • Revision ID: package-import@ubuntu.com-20130410114643-prunhsz59f0fhrdn
Tags: 2.3.2-1
[ Kiwamu Okabe ]
* New patch: Extend haskell-src-exts dependency and fix type miss.

[ Iain Lane ]
* [dfbca48] Imported Upstream version 2.3.2
* [7746bcc] Remove all patches — all upstream.
* [2cdb691] Update build-deps to match control file
* [868ebf4] agda-mode no longer depends on haskell-mode or GHCi.
  Remove dependency and update .el file accordingly
* [9e0ba22] Add agda-bin package here, as the separate package has been
  removed
* [75a240f] agda-mode needs to depend on agda-bin
* [d290f95] Allow Quickcheck up to 2.7. Fix haskeline build-dep.
* [79190e6] Add missing geniplate and parallel BDs

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
{-# LANGUAGE CPP, PatternGuards #-}
 
1
{-# LANGUAGE CPP, PatternGuards, TupleSections #-}
2
2
 
3
3
module Agda.TypeChecking.Rules.Term where
4
4
 
9
9
import Control.Monad.Error
10
10
import Data.Maybe
11
11
import Data.List hiding (sort)
12
 
import qualified Agda.Utils.IO.Locale as LocIO
13
12
import qualified Data.Map as Map
14
13
import qualified Data.Set as Set
15
 
import Data.Traversable (traverse)
 
14
import Data.Traversable (traverse,sequenceA)
16
15
 
17
16
import Agda.Interaction.Options
18
17
 
26
25
import Agda.Syntax.Concrete.Pretty
27
26
import Agda.Syntax.Fixity
28
27
import Agda.Syntax.Internal
29
 
import Agda.Syntax.Internal.Generic
30
28
import Agda.Syntax.Position
31
29
import Agda.Syntax.Literal
32
30
import Agda.Syntax.Abstract.Views
40
38
import Agda.TypeChecking.MetaVars
41
39
import Agda.TypeChecking.Pretty
42
40
import Agda.TypeChecking.Records
 
41
import Agda.TypeChecking.RecordPatterns
43
42
import Agda.TypeChecking.Conversion
 
43
import Agda.TypeChecking.Implicit (implicitArgs)
 
44
import Agda.TypeChecking.InstanceArguments
44
45
import Agda.TypeChecking.Primitive
45
46
import Agda.TypeChecking.Constraints
46
 
import Agda.TypeChecking.Free
 
47
import Agda.TypeChecking.Free hiding (Occurrence(..))
47
48
import Agda.TypeChecking.Telescope
48
49
import Agda.TypeChecking.Datatypes
49
50
import Agda.TypeChecking.Irrelevance
52
53
import Agda.TypeChecking.CompiledClause
53
54
import Agda.TypeChecking.Level
54
55
import {-# SOURCE #-} Agda.TypeChecking.Rules.Builtin.Coinduction
 
56
import Agda.TypeChecking.Rules.LHS (checkLeftHandSide)
55
57
 
56
58
import Agda.Utils.Fresh
57
59
import Agda.Utils.Tuple
58
60
import Agda.Utils.Permutation
 
61
import Agda.Utils.List (zipWithTails)
59
62
 
60
63
import {-# SOURCE #-} Agda.TypeChecking.Empty (isEmptyType)
61
64
import {-# SOURCE #-} Agda.TypeChecking.Rules.Decl (checkSectionApplication)
81
84
-- | Check that an expression is a type without knowing the sort.
82
85
isType_ :: A.Expr -> TCM Type
83
86
isType_ e =
84
 
  traceCall (IsType_ e) $
85
 
  case e of
86
 
    A.Fun i a b -> do
87
 
      a <- traverse isType_ a
 
87
  traceCall (IsType_ e) $ sharedType <$>
 
88
  case unScope e of
 
89
    A.Fun i (Arg h r t) b -> do
 
90
      a <- Dom h r <$> isType_ t
88
91
      b <- isType_ b
89
 
      return $ El (sLub (getSort $ unArg a) (getSort b)) (Pi a (NoAbs "_" b))
 
92
      return $ El (sLub (getSort $ unDom a) (getSort b)) (Pi a (NoAbs "_" b))
90
93
    A.Pi _ tel e -> do
91
94
      checkTelescope_ tel $ \tel -> do
92
95
        t   <- instantiateFull =<< isType_ e
115
118
isTypeEqualTo e t = case e of
116
119
  A.ScopedExpr _ e -> isTypeEqualTo e t
117
120
  A.Underscore i | A.metaNumber i == Nothing -> return t
118
 
  e -> do
 
121
  e -> workOnTypes $ do
119
122
    t' <- isType e (getSort t)
120
 
    t' <$ leqType_ t t'
 
123
    t' <$ leqType t t'
121
124
 
122
125
leqType_ :: Type -> Type -> TCM ()
123
126
leqType_ t t' = workOnTypes $ leqType t t'
150
153
-- * Telescopes
151
154
---------------------------------------------------------------------------
152
155
 
153
 
{- UNUSED
154
 
checkTelescope :: A.Telescope -> Sort -> (Telescope -> TCM a) -> TCM a
155
 
checkTelescope [] s ret = ret EmptyTel
156
 
checkTelescope (b : tel) s ret =
157
 
    checkTypedBindings b s $ \tel1 ->
158
 
    checkTelescope tel s   $ \tel2 ->
159
 
        ret $ abstract tel1 tel2
160
 
 
161
 
checkTypedBindings :: A.TypedBindings -> Sort -> (Telescope -> TCM a) -> TCM a
162
 
checkTypedBindings (A.TypedBindings i (Arg h rel b)) s ret =
163
 
    checkTypedBinding h rel s b $ \bs ->
164
 
    ret $ foldr (\(x,t) -> ExtendTel (Arg h rel t) . Abs x) EmptyTel bs
165
 
 
166
 
checkTypedBinding :: Hiding -> Relevance -> Sort -> A.TypedBinding -> ([(String,Type)] -> TCM a) -> TCM a
167
 
checkTypedBinding h rel s (A.TBind i xs e) ret = do
168
 
    t <- isType e s
169
 
    addCtxs xs (Arg h rel t) $ ret $ mkTel xs t
170
 
    where
171
 
        mkTel [] t     = []
172
 
        mkTel (x:xs) t = (show $ nameConcrete x,t) : mkTel xs (raise 1 t)
173
 
checkTypedBinding h rel s (A.TNoBind e) ret = do
174
 
    t <- isType e s
175
 
    ret [("_",t)]
176
 
-}
177
 
 
178
156
-- | Type check a telescope. Binds the variables defined by the telescope.
179
157
checkTelescope_ :: A.Telescope -> (Telescope -> TCM a) -> TCM a
180
158
checkTelescope_ [] ret = ret EmptyTel
201
176
checkTypedBindings :: LamOrPi -> A.TypedBindings -> (Telescope -> TCM a) -> TCM a
202
177
checkTypedBindings lamOrPi (A.TypedBindings i (Arg h rel b)) ret =
203
178
    checkTypedBinding lamOrPi h rel b $ \bs ->
204
 
    ret $ foldr (\(x,t) -> ExtendTel (Arg h rel t) . Abs x) EmptyTel bs
 
179
    ret $ foldr (\(x,t) -> ExtendTel (Dom h rel t) . Abs x) EmptyTel bs
205
180
 
206
181
checkTypedBinding :: LamOrPi -> Hiding -> Relevance -> A.TypedBinding -> ([(String,Type)] -> TCM a) -> TCM a
207
182
checkTypedBinding lamOrPi h rel (A.TBind i xs e) ret = do
210
185
    -- 2011-10-04 if flag --experimental-irrelevance is set
211
186
    allowed <- optExperimentalIrrelevance <$> pragmaOptions
212
187
    t <- modEnv lamOrPi allowed $ isType_ e
213
 
    addCtxs xs (Arg h (modRel lamOrPi allowed rel) t) $ ret $ mkTel xs t
 
188
    addCtxs xs (Dom h (modRel lamOrPi allowed rel) t) $ ret $ mkTel xs t
214
189
    where
215
190
        -- if we are checking a typed lambda, we resurrect before we check the
216
191
        -- types, but do not modify the new context entries
230
205
checkLambda :: Arg A.TypedBinding -> A.Expr -> Type -> TCM Term
231
206
checkLambda (Arg _ _ A.TNoBind{}) _ _ = __IMPOSSIBLE__
232
207
checkLambda (Arg h r (A.TBind _ xs typ)) body target = do
233
 
  TelV tel btyp <- telViewUpTo (length xs) target
234
 
  if size tel < size xs || length xs /= 1
 
208
  let numbinds = length xs
 
209
  TelV tel btyp <- telViewUpTo numbinds target
 
210
  if size tel < size xs || numbinds /= 1
235
211
    then dontUseTargetType
236
212
    else useTargetType tel btyp
237
213
  where
240
216
      verboseS "tc.term.lambda" 5 $ tick "lambda-no-target-type"
241
217
 
242
218
      -- First check that argsT is a valid type
243
 
      argsT <- workOnTypes $ Arg h r <$> isType_ typ
 
219
      argsT <- workOnTypes $ Dom h r <$> isType_ typ
244
220
 
245
221
      -- In order to have as much type information as possible when checking
246
222
      -- body, we first unify (xs : argsT) → ?t₁ with the target type. If this
248
224
      -- fresh problem for the check.
249
225
      t1 <- addCtxs xs argsT $ workOnTypes newTypeMeta_
250
226
      let tel = telFromList $ mkTel xs argsT
251
 
      pid <- newProblem_ $ leqType (telePi tel t1) target
252
 
 
253
 
      -- Now check body : ?t₁
254
 
      v <- addCtxs xs argsT $ checkExpr body t1
255
 
 
256
 
      -- Block on the type comparison
257
 
      blockTermOnProblem target (teleLam tel v) pid
258
 
 
259
 
    useTargetType tel@(ExtendTel arg (Abs _ EmptyTel)) btyp = do
 
227
      -- Do not coerce hidden lambdas
 
228
      if (h /= NotHidden) then do
 
229
        pid <- newProblem_ $ leqType (telePi tel t1) target
 
230
        -- Now check body : ?t₁
 
231
        v <- addCtxs xs argsT $ checkExpr body t1
 
232
        -- Block on the type comparison
 
233
        blockTermOnProblem target (teleLam tel v) pid
 
234
       else do
 
235
        -- Now check body : ?t₁
 
236
        v <- addCtxs xs argsT $ checkExpr body t1
 
237
        -- Block on the type comparison
 
238
        coerce (teleLam tel v) (telePi tel t1) target
 
239
 
 
240
    useTargetType tel@(ExtendTel arg (Abs y EmptyTel)) btyp = do
260
241
        verboseS "tc.term.lambda" 5 $ tick "lambda-with-target-type"
261
 
        unless (argHiding    arg == h) $ typeError $ WrongHidingInLambda target
 
242
        unless (domHiding    arg == h) $ typeError $ WrongHidingInLambda target
262
243
        -- Andreas, 2011-10-01 ignore relevance in lambda if not explicitly given
263
 
        let r' = argRelevance arg -- relevance of function type
 
244
        let r' = domRelevance arg -- relevance of function type
264
245
        when (r == Irrelevant && r' /= r) $ typeError $ WrongIrrelevanceInLambda target
265
246
--        unless (argRelevance arg == r) $ typeError $ WrongIrrelevanceInLambda target
266
247
        -- We only need to block the final term on the argument type
267
248
        -- comparison. The body will be blocked if necessary. We still want to
268
249
        -- compare the argument types first, so we spawn a new problem for that
269
250
        -- check.
270
 
        (pid, argT) <- newProblem $ isTypeEqualTo typ (unArg arg)
271
 
        v <- addCtx x (Arg h r' argT) $ checkExpr body btyp
 
251
        (pid, argT) <- newProblem $ isTypeEqualTo typ (unDom arg)
 
252
        v <- add x y (Dom h r' argT) $ checkExpr body btyp
272
253
        blockTermOnProblem target (Lam h $ Abs (show $ nameConcrete x) v) pid
273
254
      where
274
255
        [x] = xs
 
256
        add x y | C.isNoName (nameConcrete x) = addCtxString y
 
257
                | otherwise                   = addCtx x
275
258
    useTargetType _ _ = __IMPOSSIBLE__
276
259
 
277
260
 
286
269
checkLiteral :: Literal -> Type -> TCM Term
287
270
checkLiteral lit t = do
288
271
  t' <- litType lit
289
 
  blockTerm t $ Lit lit <$ leqType_ t' t
 
272
  coerce (Lit lit) t' t
290
273
 
291
 
litType :: Literal -> TCM Type
292
 
litType l = case l of
293
 
    LitInt _ _    -> el <$> primNat
294
 
    LitFloat _ _  -> el <$> primFloat
295
 
    LitChar _ _   -> el <$> primChar
296
 
    LitString _ _ -> el <$> primString
297
 
    LitQName _ _  -> el <$> primQName
298
 
  where
299
 
    el t = El (mkType 0) t
 
274
-- moved to TypeChecking.Monad.Builtin to avoid import cycles:
 
275
-- litType :: Literal -> TCM Type
300
276
 
301
277
---------------------------------------------------------------------------
302
278
-- * Terms
305
281
-- TODO: move somewhere suitable
306
282
reduceCon :: QName -> TCM QName
307
283
reduceCon c = do
308
 
  Con c [] <- constructorForm =<< reduce (Con c [])
 
284
  Con c [] <- ignoreSharing <$> (constructorForm =<< reduce (Con c []))
309
285
  return c
310
286
 
311
287
-- | @checkArguments' exph r args t0 t e k@ tries @checkArguments exph args t0 t@.
315
291
--
316
292
-- Checks @e := ((_ : t0) args) : t@.
317
293
checkArguments' ::
318
 
  ExpandHidden -> Range -> [NamedArg A.Expr] -> Type -> Type -> A.Expr ->
 
294
  ExpandHidden -> ExpandInstances -> Range -> [NamedArg A.Expr] -> Type -> Type -> A.Expr ->
319
295
  (Args -> Type -> TCM Term) -> TCM Term
320
 
checkArguments' exph r args t0 t e k = do
321
 
  z <- runErrorT $ checkArguments exph r args t0 t
 
296
checkArguments' exph expIFS r args t0 t e k = do
 
297
  z <- runErrorT $ checkArguments exph expIFS r args t0 t
322
298
  case z of
323
299
    Right (vs, t1) -> k vs t1
324
300
      -- vs = evaluated args
333
309
-- | Type check an expression.
334
310
checkExpr :: A.Expr -> Type -> TCM Term
335
311
checkExpr e t =
336
 
    verboseBracket "tc.term.expr.top" 5 "checkExpr" $
337
 
    traceCall (CheckExpr e t) $ localScope $ do
 
312
  verboseBracket "tc.term.expr.top" 5 "checkExpr" $
 
313
  traceCall (CheckExpr e t) $ localScope $ shared <$> do
338
314
    reportSDoc "tc.term.expr.top" 15 $
339
315
        text "Checking" <+> sep
340
316
          [ fsep [ prettyTCM e, text ":", prettyTCM t ]
352
328
        unScope e                      = e
353
329
 
354
330
    e <- scopedExpr e
 
331
 
355
332
    case e of
356
333
        -- Insert hidden lambda if appropriate
357
 
        _   | Pi (Arg h rel _) _ <- unEl t
 
334
        _   | Pi (Dom h rel _) _ <- ignoreSharing $ unEl t
358
335
            , not (hiddenLambdaOrHole h e)
359
336
            , h /= NotHidden                          -> do
360
337
                x <- freshName r (argName t)
374
351
                hiddenLambdaOrHole _ (A.QuestionMark _)                                = True
375
352
                hiddenLambdaOrHole _ _                                                 = False
376
353
 
377
 
                hiddenLHS (A.Clause (A.LHS _ _ (a : _) _) _ _) = elem (argHiding a) [Hidden, Instance]
 
354
                hiddenLHS (A.Clause (A.LHS _ (A.LHSHead _ (a : _)) _) _ _) = elem (argHiding a) [Hidden, Instance]
378
355
                hiddenLHS _ = False
379
356
 
380
357
        -- a meta variable without arguments: type check directly for efficiency
381
358
        A.QuestionMark i -> checkMeta newQuestionMark t i
382
 
        A.Underscore i   -> checkMeta newValueMeta t i
 
359
        A.Underscore i   -> checkMeta (newValueMeta RunMetaOccursCheck) t i
383
360
 
384
361
        A.WithApp _ e es -> typeError $ NotImplemented "type checking of with application"
385
362
 
398
375
            reportSDoc "tc.univ.poly" 10 $
399
376
              text "checking Set " <+> prettyTCM n <+>
400
377
              text "against" <+> prettyTCM t
401
 
            blockTerm t $ Sort (Type n) <$ leqType_ (sort $ sSuc $ Type n) t
 
378
            coerce (Sort $ Type n) (sort $ sSuc $ Type n) t
402
379
 
403
380
        A.App i q (Arg NotHidden r e)
404
381
          | A.Quote _ <- unScope q -> do
409
386
              quoted _                  = typeError $ GenericError $ "quote: not a defined name"
410
387
          x <- quoted (namedThing e)
411
388
          ty <- qNameType
412
 
          blockTerm t $ quoteName x <$ leqType_ ty t
 
389
          coerce (quoteName x) ty t
413
390
 
414
391
          | A.QuoteTerm _ <- unScope q ->
415
392
             do (et, _) <- inferExpr (namedThing e)
416
393
                q <- quoteTerm =<< normalise et
417
394
                ty <- el primAgdaTerm
418
 
                blockTerm t $ q <$ leqType_ ty t
 
395
                coerce q ty t
419
396
 
420
397
          | A.Unquote _ <- unScope q ->
421
398
             do e1 <- checkExpr (namedThing e) =<< el primAgdaTerm
424
401
        A.Quote _ -> typeError $ GenericError "quote must be applied to a defined name"
425
402
        A.QuoteTerm _ -> typeError $ GenericError "quoteTerm must be applied to a term"
426
403
        A.Unquote _ -> typeError $ GenericError "unquote must be applied to a term"
427
 
 
428
404
        A.AbsurdLam i h -> do
429
 
          t <- reduceB =<< instantiateFull t
430
 
          case t of
431
 
            Blocked{}                 -> postponeTypeCheckingProblem_ e $ ignoreBlocking t
432
 
            NotBlocked (El _ MetaV{}) -> postponeTypeCheckingProblem_ e $ ignoreBlocking t
433
 
            NotBlocked t' -> case unEl t' of
434
 
              Pi (Arg h' _ a) _
435
 
                | h == h' && not (null $ foldTerm metas a) ->
436
 
                    postponeTypeCheckingProblem e (ignoreBlocking t) $
437
 
                      null . foldTerm metas <$> instantiateFull a
 
405
          t <- instantiateFull t
 
406
          ifBlockedType t (\ m t' -> postponeTypeCheckingProblem_ e t') $ \ t' -> do
 
407
            case ignoreSharing $ unEl t' of
 
408
              Pi dom@(Dom h' r a) _
 
409
                | h == h' && not (null $ allMetas a) ->
 
410
                    postponeTypeCheckingProblem e t' $
 
411
                      null . allMetas <$> instantiateFull a
438
412
                | h == h' -> blockTerm t' $ do
439
 
                  isEmptyType a
 
413
                  isEmptyType (getRange i) a
440
414
                  -- Add helper function
441
415
                  top <- currentModule
442
416
                  let name = "absurd"
448
422
                    [ text "Adding absurd function" <+> prettyTCM rel <> prettyTCM aux
449
423
                    , nest 2 $ text "of type" <+> prettyTCM t'
450
424
                    ]
451
 
                  addConstant aux $ Defn rel aux t' (defaultDisplayForm aux) 0 noCompiledRep
452
 
                                  $ Function
453
 
                                    { funClauses        =
454
 
                                        [Clause { clauseRange = getRange e
455
 
                                                , clauseTel   = EmptyTel
456
 
                                                , clausePerm  = Perm 0 []
457
 
                                                , clausePats  = [Arg h Relevant $ VarP "()"]
458
 
                                                , clauseBody  = NoBody
459
 
                                                }
460
 
                                        ]
461
 
                                    , funCompiled       = Fail
462
 
                                    , funDelayed        = NotDelayed
463
 
                                    , funInv            = NotInjective
464
 
                                    , funAbstr          = ConcreteDef
465
 
                                    , funPolarity       = [Covariant]
466
 
                                    , funArgOccurrences = [Unused]
467
 
                                    , funProjection     = Nothing
468
 
                                    , funStatic         = False
469
 
                                    }
470
 
                  return (Def aux [])
 
425
                  addConstant aux
 
426
                    $ Defn rel aux t' [Nonvariant] [Unused] (defaultDisplayForm aux) 0 noCompiledRep
 
427
                    $ Function
 
428
                      { funClauses        =
 
429
                          [Clause
 
430
                            { clauseRange = getRange e
 
431
                            , clauseTel   = EmptyTel   -- telFromList [fmap ("()",) dom]
 
432
                            , clausePerm  = Perm 1 []  -- Perm 1 [0]
 
433
                            , clausePats  = [Arg h r $ VarP "()"]
 
434
                            , clauseBody  = Bind $ NoAbs "()" NoBody
 
435
                            }
 
436
                          ]
 
437
                      , funCompiled       = Fail
 
438
                      , funDelayed        = NotDelayed
 
439
                      , funInv            = NotInjective
 
440
                      , funAbstr          = ConcreteDef
 
441
{-
 
442
                      , funPolarity       = [Nonvariant] -- WAS: [Covariant]
 
443
                      , funArgOccurrences = [Unused]
 
444
-}
 
445
                      , funMutual         = []
 
446
                      , funProjection     = Nothing
 
447
                      , funStatic         = False
 
448
                      , funCopy           = False
 
449
                      , funTerminates     = Just True
 
450
                      }
 
451
                  -- Andreas 2012-01-30: since aux is lifted to toplevel
 
452
                  -- it needs to be applied to the current telescope (issue 557)
 
453
                  tel <- getContextTelescope
 
454
                  return $ Def aux $ teleArgs tel
 
455
                  -- WAS: return (Def aux [])
471
456
                | otherwise -> typeError $ WrongHidingInLambda t'
472
457
              _ -> typeError $ ShouldBePi t'
473
 
          where
474
 
            metas (MetaV m _) = [m]
475
 
            metas _           = []
 
458
 
 
459
{- OLD
476
460
        A.ExtendedLam i di qname cs -> do
477
461
             t <- reduceB =<< instantiateFull t
 
462
             let isMeta t = case ignoreSharing $ unEl t of { MetaV{} -> True; _ -> False }
478
463
             case t of
479
464
               Blocked{}                 -> postponeTypeCheckingProblem_ e $ ignoreBlocking t
480
 
               NotBlocked (El _ MetaV{}) -> postponeTypeCheckingProblem_ e $ ignoreBlocking t
 
465
               NotBlocked t' | isMeta t' -> postponeTypeCheckingProblem_ e $ ignoreBlocking t
481
466
               NotBlocked t -> do
482
 
                 j   <- currentMutualBlock
483
 
                 rel <- asks envRelevance
484
 
                 addConstant qname (Defn rel qname t (defaultDisplayForm qname) j noCompiledRep Axiom)
485
 
                 reportSDoc "tc.term.exlam" 50 $ text "extended lambda's implementation \"" <> prettyTCM qname <>
486
 
                                                 text "\" has type: " $$ prettyTCM t -- <+>
487
 
                 abstract (A.defAbstract di) $ checkFunDef' t rel NotDelayed di qname cs
488
 
                 tel <- getContextTelescope
489
 
                 addExtLambdaTele qname (counthidden tel , countnothidden tel)
490
 
                 reduce $ (Def qname [] `apply` (mkArgs tel))
 
467
-}
 
468
        A.ExtendedLam i di qname cs -> do
 
469
           t <- instantiateFull t
 
470
           ifBlockedType t (\ m t' -> postponeTypeCheckingProblem_ e t') $ \ t -> do
 
471
             j   <- currentOrFreshMutualBlock
 
472
             rel <- asks envRelevance
 
473
             addConstant qname $
 
474
               Defn rel qname t [] [] (defaultDisplayForm qname) j noCompiledRep Axiom
 
475
             reportSDoc "tc.term.exlam" 50 $
 
476
               text "extended lambda's implementation \"" <> prettyTCM qname <>
 
477
               text "\" has type: " $$ prettyTCM t -- <+>
 
478
--               text " where clauses: " <+> text (show cs)
 
479
             abstract (A.defAbstract di) $ checkFunDef' t rel NotDelayed di qname cs
 
480
             args     <- getContextArgs
 
481
             top      <- currentModule
 
482
             freevars <- getSecFreeVars top
 
483
             let argsNoParam = genericDrop freevars args -- don't count module parameters
 
484
             let (hid, notHid) = partition ((Hidden ==) . argHiding) argsNoParam
 
485
             addExtLambdaTele qname (length hid, length notHid)
 
486
             reduce $ (Def qname [] `apply` args)
491
487
          where
492
488
            -- Concrete definitions cannot use information about abstract things.
493
489
            abstract ConcreteDef = inConcreteMode
494
490
            abstract AbstractDef = inAbstractMode
495
 
            mkArgs :: Telescope -> Args
496
 
            mkArgs tel = map arg [n - 1, n - 2..0]
497
 
              where
498
 
                n     = size tel
499
 
                arg i = defaultArg (Var i [])
500
 
 
501
 
            metas (MetaV m _) = [m]
502
 
            metas _           = []
503
 
 
504
 
            counthidden :: Telescope -> Int
505
 
            counthidden t = length $ filter (\ (Arg h r a) -> h == Hidden ) $ teleArgs t
506
 
 
507
 
            countnothidden :: Telescope -> Int
508
 
            countnothidden t = length $ filter (\ (Arg h r a) -> h == NotHidden ) $ teleArgs t
509
 
 
510
 
 
511
 
{- Andreas, 2011-04-27 DOES NOT WORK
512
 
   -- a telescope is not for type checking abstract syn
513
 
 
514
 
        A.Lam i (A.DomainFull b) e -> do
515
 
            -- check the types, get the telescope with unchanged relevance
516
 
            (tel, t1, cs) <- workOnTypes $ checkTypedBindings_ b $ \tel -> do
517
 
               t1 <- newTypeMeta_
518
 
               cs <- escapeContext (size tel) $ leqType (telePi tel t1) t
519
 
               return (tel, t1, cs)
520
 
            -- check the body under the unchanged telescope
521
 
            v <- addCtxTel tel $ do teleLam tel <$> checkExpr e t1
522
 
            blockTerm t v (return cs)
523
 
-}
 
491
 
524
492
        A.Lam i (A.DomainFull (A.TypedBindings _ b)) e -> checkLambda b e t
525
493
 
526
 
        --      A.Lam i (A.DomainFull b) e -> do
527
 
        --          (v, cs) <- checkTypedBindings LamNotPi b $ \tel -> do
528
 
        --         (t1, cs) <- workOnTypes $ do
529
 
        --                t1 <- newTypeMeta_
530
 
        --           cs <- escapeContext (size tel) $ leqType (telePi tel t1) t
531
 
        --           return (t1, cs)
532
 
        --         v <- checkExpr e t1
533
 
        --         return (teleLam tel v, cs)
534
 
        --          blockTerm t v (return cs)
535
 
 
536
494
        A.Lam i (A.DomainFree h rel x) e0 -> checkExpr (A.Lam i (domainFree h rel x) e0) t
537
495
 
538
496
        A.Lit lit    -> checkLiteral lit t
549
506
                   , nest 2 $ text "t   =" <+> prettyTCM t'
550
507
                   , nest 2 $ text "cxt =" <+> (prettyTCM =<< getContextTelescope)
551
508
                   ]
552
 
            blockTerm t $ unEl t' <$ leqType_ (sort s) t
 
509
            coerce (unEl t') (sort s) t
553
510
        A.Fun _ (Arg h r a) b -> do
554
511
            a' <- isType_ a
555
512
            b' <- isType_ b
556
513
            s <- reduce $ getSort a' `sLub` getSort b'
557
 
            blockTerm t $ Pi (Arg h r a') (NoAbs "_" b') <$ leqType_ (sort s) t
 
514
            coerce (Pi (Dom h r a') (NoAbs "_" b')) (sort s) t
558
515
        A.Set _ n    -> do
559
516
          n <- ifM typeInType (return 0) (return n)
560
 
          blockTerm t $ Sort (mkType n) <$ leqType_ (sort $ mkType $ n + 1) t
 
517
          coerce (Sort $ mkType n) (sort $ mkType $ n + 1) t
561
518
        A.Prop _     -> do
562
519
          typeError $ GenericError "Prop is no longer supported"
563
520
          -- s <- ifM typeInType (return $ mkType 0) (return Prop)
564
 
          -- blockTerm t (Sort Prop) $ leqType_ (sort $ mkType 1) t
 
521
          -- coerce (Sort Prop) (sort $ mkType 1) t
565
522
 
566
523
        A.Rec _ fs  -> do
567
524
          t <- reduce t
568
 
          case unEl t of
 
525
          case ignoreSharing $ unEl t of
569
526
            Def r vs  -> do
570
527
              axs    <- getRecordFieldNames r
571
528
              let xs = map unArg axs
575
532
              let arg x e =
576
533
                    case [ a | a <- axs, unArg a == x ] of
577
534
                      [a] -> unnamed e <$ a
578
 
                      _   -> defaultArg $ unnamed e -- we only end up here if the field names are bad
579
 
              let meta = A.Underscore $ A.MetaInfo (getRange e) scope Nothing
580
 
                  missingExplicits = [ (unArg a, [unnamed meta <$ a])
 
535
                      _   -> defaultNamedArg e -- we only end up here if the field names are bad
 
536
              let meta x = A.Underscore $ A.MetaInfo (getRange e) scope Nothing (show x)
 
537
                  missingExplicits = [ (unArg a, [unnamed . meta <$> a])
581
538
                                     | a <- axs, argHiding a == NotHidden
582
539
                                     , notElem (unArg a) (map fst fs) ]
583
540
              -- In es omitted explicit fields are replaced by underscores
605
562
                  def <- getConstInfo r
606
563
                  vs  <- newArgsMeta (defType def)
607
564
                  let target = piApply (defType def) vs
608
 
                      s      = case unEl target of
 
565
                      s      = case ignoreSharing $ unEl target of
609
566
                                 Level l -> Type l
610
567
                                 Sort s  -> s
611
568
                                 _       -> __IMPOSSIBLE__
612
569
                      inferred = El s $ Def r vs
613
570
                  v <- checkExpr e inferred
614
 
                  blockTerm t $ v <$ leqType_ t inferred
 
571
                  coerce v inferred t
 
572
                  -- Andreas 2012-04-21: OLD CODE, WRONG DIRECTION, I GUESS:
 
573
                  -- blockTerm t $ v <$ leqType_ t inferred
 
574
 
615
575
                  -- If there are more than one possible record we postpone
616
576
                _:_:_ -> do
617
577
                  reportSDoc "tc.term.expr.rec" 10 $ sep
622
582
            _         -> typeError $ ShouldBeRecordType t
623
583
 
624
584
        A.RecUpdate ei recexpr fs -> do
625
 
          case unEl t of
 
585
          case ignoreSharing $ unEl t of
626
586
            Def r vs  -> do
627
587
              rec <- checkExpr recexpr t
628
588
              name <- freshNoName (getRange recexpr)
636
596
                checkExpr (A.Rec ei [ (x, e) | (x, Just e) <- zip xs es' ]) t
637
597
            MetaV _ _ -> do
638
598
              inferred <- inferExpr recexpr >>= reduce . snd
639
 
              case unEl inferred of
 
599
              case ignoreSharing $ unEl inferred of
640
600
                MetaV _ _ -> postponeTypeCheckingProblem_ e t
641
601
                _         -> do
642
602
                  v <- checkExpr e inferred
643
 
                  blockTerm t $ v <$ leqType_ t inferred
 
603
                  coerce v inferred t
644
604
            _         -> typeError $ ShouldBeRecordType t
645
605
          where
646
606
            replaceFields :: Name -> A.ExprInfo -> Arg A.QName -> Maybe A.Expr -> Maybe A.Expr
647
 
            replaceFields n ei (Arg NotHidden _ p) Nothing  = Just $ A.App ei (A.Def p) $ defaultArg (unnamed $ A.Var n)
 
607
            replaceFields n ei (Arg NotHidden _ p) Nothing  = Just $ A.App ei (A.Def p) $ defaultNamedArg $ A.Var n
648
608
            replaceFields _ _  (Arg _         _ _) Nothing  = Nothing
649
609
            replaceFields _ _  _                   (Just e) = Just $ e
650
610
 
651
 
        A.DontCare e -> -- can happen in the context of with functions
652
 
          checkExpr e t
653
 
{- Andreas, 2011-10-03 why do I get an internal error for Issue337?
 
611
        A.DontCare e -> -- resurrect vars
 
612
          ifM ((Irrelevant ==) <$> asks envRelevance)
 
613
            (DontCare <$> do applyRelevanceToContext Irrelevant $ checkExpr e t)
 
614
            (internalError "DontCare may only appear in irrelevant contexts")
 
615
{- STALE?:
 
616
   Andreas, 2011-10-03 why do I get an internal error for Issue337?
654
617
                        -- except that should be fixed now (issue 337)
655
618
                        __IMPOSSIBLE__
656
619
-}
658
621
 
659
622
        e0@(A.QuoteGoal _ x e) -> do
660
623
          t' <- etaContract =<< normalise t
661
 
          let metas = foldTerm (\v -> case v of
662
 
                                       MetaV m _ -> [m]
663
 
                                       _         -> []
664
 
                               ) t'
 
624
          let metas = allMetas t'
665
625
          case metas of
666
 
            _:_ -> postponeTypeCheckingProblem e0 t' $ and <$> mapM isInstantiatedMeta metas
 
626
            _:_ -> postponeTypeCheckingProblem e0 t' $ andM $ map isInstantiatedMeta metas
667
627
            []  -> do
668
628
              quoted <- quoteTerm (unEl t')
669
629
              tmType <- agdaTermType
670
630
              (v, ty) <- addLetBinding Relevant x quoted tmType (inferExpr e)
671
 
              blockTerm t' $ v <$ leqType_ ty t'
 
631
              blockTerm t' $ coerce v ty t'
672
632
 
673
633
        A.ETel _   -> __IMPOSSIBLE__
674
634
 
694
654
                -- Type error
695
655
                let badCon t = typeError $ DoesNotConstructAnElementOf
696
656
                                            (fst $ head cs) t
697
 
 
 
657
{- OLD CODE
698
658
                -- Lets look at the target type at this point
699
659
                let getCon = do
700
660
                      TelV _ t1 <- telView t
701
661
                      t1 <- reduceB $ unEl t1
702
662
                      reportSDoc "tc.check.term.con" 40 $ nest 2 $
703
663
                        text "target type: " <+> prettyTCM t1
704
 
                      case t1 of
 
664
                      case ignoreSharing <$> t1 of
705
665
                        NotBlocked (Def d _) -> do
706
666
                          let dataOrRec = case [ c | (d', c) <- dcs, d == d' ] of
707
667
                                [c] -> do
719
679
                        NotBlocked (MetaV _ _)  -> return Nothing
720
680
                        Blocked{} -> return Nothing
721
681
                        _ -> badCon (ignoreBlocking t1)
722
 
                let unblock = isJust <$> getCon
 
682
-}
 
683
                -- Lets look at the target type at this point
 
684
                let getCon = do
 
685
                     TelV _ t1 <- telView t
 
686
                     reportSDoc "tc.check.term.con" 40 $ nest 2 $
 
687
                       text "target type: " <+> prettyTCM t1
 
688
                     ifBlocked (unEl t1) (\ m t -> return Nothing) $ \ t' ->
 
689
                       (isDataOrRecord t' >>=) $ maybe (badCon t') $ \ d ->
 
690
                           case [ c | (d', c) <- dcs, d == d' ] of
 
691
                                [c] -> do
 
692
                                  reportSLn "tc.check.term" 40 $ "  decided on: " ++ show c
 
693
                                  return (Just c)
 
694
                                []  -> badCon (Def d [])
 
695
                                cs  -> typeError $ GenericError $
 
696
                                        "Can't resolve overloaded constructors targeting the same datatype (" ++ show d ++
 
697
                                        "): " ++ unwords (map show cs)
 
698
                let unblock = isJust <$> getCon -- to unblock, call getCon later again
723
699
                mc <- getCon
724
700
                case mc of
725
701
                  Just c  -> checkConstructorApplication e t c args
728
704
              -- Subcase: non-ambiguous constructor
729
705
            | Application (A.Con (AmbQ [c])) args <- appView e ->
730
706
                checkConstructorApplication e t c args
 
707
 
 
708
              -- Subcase: pattern synonym
 
709
            | Application (A.PatternSyn n) args <- appView e -> do
 
710
                (ns, p) <- lookupPatternSyn n
 
711
                -- Expand the pattern synonym by substituting for
 
712
                -- the arguments we have got and lambda-lifting
 
713
                -- over the ones we haven't.
 
714
                let (zs, ns', as) = zipWithTails (\n a -> (n, namedThing (unArg a))) ns args
 
715
                    p'            = A.patternToExpr $ setRange (getRange n) p
 
716
                    e'            = A.lambdaLiftExpr ns' (A.substExpr zs p') `A.app` as
 
717
                checkExpr e' t
 
718
 
731
719
              -- Subcase: defined symbol or variable.
732
720
            | Application hd args <- appView e ->
733
721
                checkHeadApplication e t hd args
736
724
  A.DomainFull $ A.TypedBindings r $ Arg h rel $ A.TBind r [x] $ A.Underscore info
737
725
  where
738
726
    r = getRange x
739
 
    info = A.MetaInfo{ A.metaRange = r, A.metaScope = emptyScopeInfo, A.metaNumber = Nothing }
 
727
    info = A.MetaInfo
 
728
      { A.metaRange          = r
 
729
      , A.metaScope          = emptyScopeInfo
 
730
      , A.metaNumber         = Nothing
 
731
      , A.metaNameSuggestion = show x
 
732
      }
740
733
 
741
734
checkMeta :: (Type -> TCM Term) -> Type -> A.MetaInfo -> TCM Term
742
735
checkMeta newMeta t i = do
743
736
  case A.metaNumber i of
744
737
    Nothing -> do
745
738
      setScope (A.metaScope i)
746
 
      newMeta t
 
739
      v <- newMeta t
 
740
      setValueMetaName v (A.metaNameSuggestion i)
 
741
      return v
747
742
    -- Rechecking an existing metavariable
748
743
    Just n -> do
749
744
      let v = MetaV (MetaId n) []
750
745
      t' <- jMetaType . mvJudgement <$> lookupMeta (MetaId n)
751
 
      blockTerm t $ v <$ leqType t' t
 
746
      coerce v t' t
752
747
 
753
748
inferMeta :: (Type -> TCM Term) -> A.MetaInfo -> TCM (Args -> Term, Type)
754
749
inferMeta newMeta i =
768
763
inferHead :: A.Expr -> TCM (Args -> Term, Type)
769
764
inferHead (A.Var x) = do -- traceCall (InferVar x) $ do
770
765
  (u, a) <- getVarInfo x
771
 
  when (unusableRelevance $ argRelevance a) $
 
766
  when (unusableRelevance $ domRelevance a) $
772
767
    typeError $ VariableIsIrrelevant x
773
 
  return (apply u, unArg a)
 
768
  return (apply u, unDom a)
774
769
inferHead (A.Def x) = do
775
770
  proj <- isProjection x
776
771
  case proj of
805
800
  Constructor{conPars = n} <- theDef <$> (instantiateDef =<< getConstInfo c)
806
801
 
807
802
  verboseS "tc.term.con" 7 $ do
808
 
    liftIO $ LocIO.putStrLn $ unwords [show c, "has", show n, "parameters."]
 
803
    reportSLn "" 0 $ unwords [show c, "has", show n, "parameters."]
809
804
 
810
805
  -- So when applying the constructor throw away the parameters.
811
806
  return (apply u . genericDrop n, a)
812
807
inferHead (A.Con _) = __IMPOSSIBLE__  -- inferHead will only be called on unambiguous constructors
813
808
inferHead (A.QuestionMark i)  = inferMeta newQuestionMark i
814
 
inferHead (A.Underscore i) = inferMeta newValueMeta i
 
809
inferHead (A.Underscore i) = inferMeta (newValueMeta RunMetaOccursCheck) i
815
810
inferHead e = do (term, t) <- inferExpr e
816
811
                 return (apply term, t)
817
812
 
833
828
      ds <- mapM prettyTCM vs
834
829
      dx <- prettyTCM x
835
830
      dt <- prettyTCM $ defType d
836
 
      liftIO $ LocIO.putStrLn $ "inferred def " ++ unwords (show dx : map show ds) ++ " : " ++ show dt
 
831
      reportSLn "" 0 $ "inferred def " ++ unwords (show dx : map show ds) ++ " : " ++ show dt
837
832
    return (mkTerm x vs, defType d)
838
833
 
839
834
-- | Check the type of a constructor application. This is easier than
840
835
--   a general application since the implicit arguments can be inserted
841
836
--   without looking at the arguments to the constructor.
842
837
checkConstructorApplication :: A.Expr -> Type -> QName -> [NamedArg A.Expr] -> TCM Term
843
 
checkConstructorApplication org t c args
844
 
  | hiddenArg = fallback
845
 
  | otherwise = do
 
838
checkConstructorApplication org t c args = do
 
839
  reportSDoc "tc.term.con" 50 $ vcat
 
840
    [ text "entering checkConstructorApplication"
 
841
    , nest 2 $ vcat
 
842
      [ text "org  =" <+> prettyTCM org
 
843
      , text "t    =" <+> prettyTCM t
 
844
      , text "c    =" <+> prettyTCM c
 
845
      , text "args =" <+> prettyTCM args
 
846
    ] ]
 
847
  let (args', paramsGiven) = checkForParams args
 
848
  if paramsGiven then fallback else do
 
849
    reportSDoc "tc.term.con" 50 $ text "checkConstructorApplication: no parameters explicitly supplied, continuing..."
846
850
    cdef  <- getConstInfo c
847
851
    let Constructor{conData = d} = theDef cdef
848
 
    case unEl t of -- Only fully applied constructors get special treatment
849
 
      Def d' vs | d' == d -> do
850
 
        def <- theDef <$> getConstInfo d
851
 
        let npars = case def of
852
 
                      Datatype{ dataPars = n } -> Just n
853
 
                      Record{ recPars = n }    -> Just n
854
 
                      _                        -> Nothing
855
 
        flip (maybe fallback) npars $ \n -> do
856
 
        let ps    = genericTake n vs
 
852
    reportSDoc "tc.term.con" 50 $ nest 2 $ text "d    =" <+> prettyTCM d
 
853
    -- Issue 661: t maybe an evaluated form of d .., so we evaluate d
 
854
    -- as well and then check wether we deal with the same datatype
 
855
    t0 <- reduce (Def d [])
 
856
    case (ignoreSharing t0, ignoreSharing $ unEl t) of -- Only fully applied constructors get special treatment
 
857
      (Def d0 _, Def d' vs) -> do
 
858
       reportSDoc "tc.term.con" 50 $ nest 2 $ text "d0   =" <+> prettyTCM d0
 
859
       reportSDoc "tc.term.con" 50 $ nest 2 $ text "d'   =" <+> prettyTCM d'
 
860
       reportSDoc "tc.term.con" 50 $ nest 2 $ text "vs   =" <+> prettyTCM vs
 
861
       if d' /= d0 then fallback else do
 
862
        -- Issue 661: d' may take more parameters than d, in particular
 
863
        -- these additional parameters could be a module parameter telescope.
 
864
        -- Since we get the constructor type ctype from d but the parameters
 
865
        -- from t = Def d' vs, we drop the additional parameters.
 
866
        npars  <- getNumberOfParameters d
 
867
        npars' <- getNumberOfParameters d'
 
868
        flip (maybe fallback) (sequenceA $ List2 (npars, npars')) $ \(List2 (n,n')) -> do
 
869
        reportSDoc "tc.term.con" 50 $ nest 2 $ text $ "n    = " ++ show n
 
870
        reportSDoc "tc.term.con" 50 $ nest 2 $ text $ "n'   = " ++ show n'
 
871
        -- when (n > n') __IMPOSSIBLE__ -- NOT IN SCOPE `__IMPOSSIBLE__' WHY???
 
872
        when (n > n') bla
 
873
        let ps    = genericTake n $ genericDrop (n' - n) vs
857
874
            ctype = defType cdef
858
875
        reportSDoc "tc.term.con" 20 $ vcat
859
876
          [ text "special checking of constructor application of" <+> prettyTCM c
861
878
                          , text "ctype  =" <+> prettyTCM ctype ] ]
862
879
        let ctype' = ctype `piApply` ps
863
880
        reportSDoc "tc.term.con" 20 $ nest 2 $ text "ctype' =" <+> prettyTCM ctype'
864
 
        checkArguments' ExpandLast (getRange c) args ctype' t org $ \us t' -> do
 
881
        -- check the non-parameter arguments
 
882
        checkArguments' ExpandLast ExpandInstanceArguments (getRange c) args' ctype' t org $ \us t' -> do
865
883
          reportSDoc "tc.term.con" 20 $ nest 2 $ vcat
866
884
            [ text "us     =" <+> prettyTCM us
867
885
            , text "t'     =" <+> prettyTCM t' ]
868
 
          blockTerm t $ Con c us <$ leqType_ t' t
869
 
      _ -> fallback
 
886
          coerce (Con c us) t' t
 
887
      _ -> do
 
888
        reportSDoc "tc.term.con" 50 $ nest 2 $ text "we are not at a datatype, falling back"
 
889
        fallback
870
890
  where
871
891
    fallback = checkHeadApplication org t (A.Con (AmbQ [c])) args
 
892
    bla = __IMPOSSIBLE__
872
893
 
873
894
    -- Check if there are explicitly given hidden arguments,
874
895
    -- in which case we fall back to default type checking.
875
896
    -- We could work harder, but let's not for now.
876
 
    hiddenArg = case args of
877
 
      Arg Hidden _ _ : _ -> True
878
 
      _                  -> False
 
897
    --
 
898
    -- Andreas, 2012-04-18: if all inital args are underscores, ignore them
 
899
    checkForParams args =
 
900
      let (hargs, rest) = span isHiddenArg args
 
901
          removeScope (A.ScopedExpr _ e) = removeScope e
 
902
          removeScope e                  = e
 
903
          notUnderscore A.Underscore{} = False
 
904
          notUnderscore _              = True
 
905
      in  (rest,) $ any notUnderscore $ map (removeScope . namedArg) hargs
 
906
 
 
907
{- UNUSED CODE, BUT DON'T REMOVE (2012-04-18)
879
908
 
880
909
    -- Split the arguments to a constructor into those corresponding
881
910
    -- to parameters and those that don't. Dummy underscores are inserted
894
923
        mname = nameOf (unArg arg)
895
924
 
896
925
    dummyUnderscore = Arg Hidden Relevant (unnamed $ A.Underscore $ A.MetaInfo noRange emptyScopeInfo Nothing)
 
926
-}
897
927
 
898
928
-- | @checkHeadApplication e t hd args@ checks that @e@ has type @t@,
899
929
-- assuming that @e@ has the form @hd args@. The corresponding
920
950
        [ text "checkHeadApplication inferred" <+>
921
951
          prettyTCM c <+> text ":" <+> prettyTCM t0
922
952
        ]
923
 
      checkArguments' ExpandLast (getRange hd) args t0 t e $ \vs t1 -> do
 
953
      checkArguments' ExpandLast ExpandInstanceArguments (getRange hd) args t0 t e $ \vs t1 -> do
924
954
        TelV eTel eType <- telView t
925
955
        -- If the expected type @eType@ is a metavariable we have to make
926
956
        -- sure it's instantiated to the proper pi type
950
980
          "coinductive constructor in the scope of a let-bound variable"
951
981
 
952
982
      -- The name of the fresh function.
953
 
      i <- fresh :: TCM Integer
 
983
      i <- fresh :: TCM Int
954
984
      let name = filter (/= '_') (show $ A.qnameName c) ++ "-" ++ show i
955
 
      c' <- liftM2 qualify (killRange <$> currentModule) (freshName_ name)
 
985
      c' <- setRange (getRange c) <$>
 
986
              liftM2 qualify (killRange <$> currentModule)
 
987
                             (freshName_ name)
956
988
 
957
989
      -- The application of the fresh function to the relevant
958
990
      -- arguments.
960
992
 
961
993
      -- Add the type signature of the fresh function to the
962
994
      -- signature.
963
 
      i   <- currentMutualBlock
 
995
      i   <- currentOrFreshMutualBlock
964
996
      tel <- getContextTelescope
965
997
      -- If we are in irrelevant position, add definition irrelevantly.
966
998
      -- TODO: is this sufficient?
967
999
      rel <- asks envRelevance
968
 
      addConstant c' (Defn rel c' t (defaultDisplayForm c') i noCompiledRep $ Axiom)
 
1000
      addConstant c' (Defn rel c' t [] [] (defaultDisplayForm c') i noCompiledRep $ Axiom)
969
1001
 
970
1002
      -- Define and type check the fresh function.
971
1003
      ctx <- getContext
972
1004
      let info   = A.mkDefInfo (A.nameConcrete $ A.qnameName c') defaultFixity'
973
1005
                               PublicAccess ConcreteDef noRange
974
 
          pats   = map (fmap $ \(n, _) -> Named Nothing (A.VarP n)) $
 
1006
          pats   = map (\ (Dom h r (n, _)) -> Arg h r $ Named Nothing $ A.VarP n) $
975
1007
                       reverse ctx
976
 
          clause = A.Clause (A.LHS (A.LHSRange noRange) c' pats [])
 
1008
          clause = A.Clause (A.LHS (A.LHSRange noRange) (A.LHSHead c' pats) [])
977
1009
                            (A.RHS $ unAppView (A.Application (A.Con (AmbQ [c])) args))
978
1010
                            []
979
1011
 
988
1020
          , nest 2 $ prettyA clause <> text "."
989
1021
          ]
990
1022
 
991
 
      escapeContext (size ctx) $ checkFunDef Delayed info c' [clause]
 
1023
      escapeContextToTopLevel $ checkFunDef Delayed info c' [clause]
992
1024
 
993
1025
      reportSDoc "tc.term.expr.coind" 15 $ do
994
1026
        def <- theDef <$> getConstInfo c'
1001
1033
  where
1002
1034
  defaultResult = do
1003
1035
    (f, t0) <- inferHead hd
1004
 
    checkArguments' ExpandLast (getRange hd) args t0 t e $ \vs t1 ->
1005
 
      blockTerm t $ f vs <$ leqType_ t1 t
1006
 
 
1007
 
data ExpandHidden = ExpandLast | DontExpandLast
 
1036
    checkArguments' ExpandLast ExpandInstanceArguments (getRange hd) args t0 t e $ \vs t1 ->
 
1037
      coerce (f vs) t1 t
1008
1038
 
1009
1039
instance Error Type where
1010
1040
  strMsg _ = __IMPOSSIBLE__
1028
1058
--   that have to be solved for everything to be well-formed.
1029
1059
--
1030
1060
--   TODO: doesn't do proper blocking of terms
1031
 
checkArguments :: ExpandHidden -> Range -> [NamedArg A.Expr] -> Type -> Type ->
 
1061
checkArguments :: ExpandHidden -> ExpandInstances -> Range -> [NamedArg A.Expr] -> Type -> Type ->
1032
1062
                  ErrorT Type TCM (Args, Type)
1033
 
checkArguments DontExpandLast _ [] t0 t1 = return ([], t0)
1034
 
checkArguments exh r [] t0 t1 =
 
1063
checkArguments DontExpandLast _ _ [] t0 t1 = return ([], t0)
 
1064
checkArguments exh    expandIFS r [] t0 t1 =
 
1065
    traceCallE (CheckArguments r [] t0 t1) $ lift $ do
 
1066
      t1' <- unEl <$> reduce t1
 
1067
      implicitArgs (-1) (expand t1') t0
 
1068
    where
 
1069
      expand (Pi  (Dom h   _ _) _) Hidden = h /= Hidden
 
1070
      expand _                     Hidden = True
 
1071
      expand (Pi  (Dom h _ _) _) Instance = h /= Instance && expandIFS == ExpandInstanceArguments
 
1072
      expand _                   Instance = expandIFS == ExpandInstanceArguments
 
1073
      expand _                  NotHidden = False
 
1074
 
 
1075
{- OLD CODE
 
1076
checkArguments exh expandIFS r [] t0 t1 =
1035
1077
    traceCallE (CheckArguments r [] t0 t1) $ do
1036
1078
        t0' <- lift $ reduce t0
1037
1079
        t1' <- lift $ reduce t1
1038
 
        case unEl t0' of
1039
 
            Pi (Arg Hidden rel a) _ | notHPi Hidden $ unEl t1'  -> do
1040
 
                v  <- lift $ applyRelevanceToContext rel $ newValueMeta a
 
1080
        case ignoreSharing $ unEl t0' of
 
1081
            Pi (Dom Hidden rel a) _ | notHPi Hidden $ unEl t1'  -> do
 
1082
                v  <- lift $ applyRelevanceToContext rel $ newValueMeta RunMetaOccursCheck a
1041
1083
                let arg = Arg Hidden rel v
1042
 
                (vs, t0'') <- checkArguments exh r [] (piApply t0' [arg]) t1'
 
1084
                (vs, t0'') <- checkArguments exh expandIFS r [] (piApply t0' [arg]) t1'
1043
1085
                return (arg : vs, t0'')
1044
 
            Pi (Arg Instance rel a) _ | notHPi Instance $ unEl t1'  -> do
 
1086
            Pi (Dom Instance rel a) _ | expandIFS == ExpandInstanceArguments &&
 
1087
                                        (notHPi Instance $ unEl t1')  -> do
1045
1088
                lift $ reportSLn "tc.term.args.ifs" 15 $ "inserting implicit meta for type " ++ show a
1046
 
                v <- lift $ applyRelevanceToContext rel $ newIFSMeta a
 
1089
                v <- lift $ applyRelevanceToContext rel $ initializeIFSMeta a
1047
1090
                let arg = Arg Instance rel v
1048
 
                (vs, t0'') <- checkArguments exh r [] (piApply t0' [arg]) t1'
 
1091
                (vs, t0'') <- checkArguments exh expandIFS r [] (piApply t0' [arg]) t1'
1049
1092
                return (arg : vs, t0'')
1050
1093
            _ -> return ([], t0')
1051
1094
    where
1052
 
        notHPi h (Pi  (Arg h' _ _) _) | h == h' = False
 
1095
        notHPi h (Pi  (Dom h' _ _) _) | h == h' = False
 
1096
        notHPi h (Shared p) = notHPi h $ derefPtr p
1053
1097
        notHPi _ _                      = True
 
1098
-}
1054
1099
 
1055
 
checkArguments exh r args0@(Arg h _ e : args) t0 t1 =
 
1100
checkArguments exh expandIFS r args0@(Arg h _ e : args) t0 t1 =
1056
1101
    traceCallE (CheckArguments r args0 t0 t1) $ do
 
1102
      lift $ reportSDoc "tc.term.args" 30 $ sep
 
1103
        [ text "checkArguments"
 
1104
--        , text "  args0 =" <+> prettyA args0
 
1105
        , nest 2 $ vcat
 
1106
          [ text "e     =" <+> prettyA e
 
1107
          , text "t0    =" <+> prettyTCM t0
 
1108
          , text "t1    =" <+> prettyTCM t1
 
1109
          ]
 
1110
        ]
1057
1111
      t0b <- lift $ reduceB t0
 
1112
      let isMeta t = case ignoreSharing $ unEl t of { MetaV{} -> True; _ -> False }
1058
1113
      case t0b of
1059
 
        Blocked{}                 -> throwError $ ignoreBlocking t0b
1060
 
        NotBlocked (El _ MetaV{}) -> throwError $ ignoreBlocking t0b
 
1114
        Blocked{}                   -> throwError $ ignoreBlocking t0b
 
1115
        NotBlocked t0' | isMeta t0' -> throwError $ ignoreBlocking t0b
1061
1116
        NotBlocked t0' -> do
1062
1117
          -- (t0', cs) <- forcePi h (name e) t0
1063
1118
          e' <- return $ namedThing e
1064
 
          case unEl t0' of
1065
 
              Pi (Arg h' rel a) _ |
 
1119
          case ignoreSharing $ unEl t0' of
 
1120
              Pi (Dom h' rel a) _ |
1066
1121
                h == h' && (h == NotHidden || sameName (nameOf e) (nameInPi $ unEl t0')) -> do
1067
1122
                  u  <- lift $ applyRelevanceToContext rel $ checkExpr e' a
1068
1123
                  let arg = Arg h rel u  -- save relevance info in argument
1069
 
                  (us, t0'') <- checkArguments exh (fuseRange r e) args (piApply t0' [arg]) t1
1070
 
                  return (nukeIfIrrelevant arg : us, t0'')
 
1124
                  (us, t0'') <- checkArguments exh expandIFS (fuseRange r e) args (piApply t0' [arg]) t1
 
1125
                  return (arg : us, t0'')
 
1126
{- UNUSED.  2012-04-02 do not insert DontCare (is redundant anyway)
1071
1127
                         where nukeIfIrrelevant arg =
1072
1128
                                 if argRelevance arg == Irrelevant then
1073
1129
   -- Andreas, 2011-09-09 keep irr. args. until after termination checking
1074
1130
                                   arg { unArg = DontCare $ unArg arg }
1075
1131
                                  else arg
1076
 
              Pi (Arg Instance rel a) _ -> insertIFSUnderscore rel a
1077
 
              Pi (Arg Hidden rel a) _   -> insertUnderscore rel
1078
 
              Pi (Arg NotHidden _ _) _  -> lift $ typeError $ WrongHidingInApplication t0'
 
1132
-}
 
1133
              Pi (Dom Instance rel a) b | expandIFS == ExpandInstanceArguments ->
 
1134
                insertIFSUnderscore rel (absName b) a
 
1135
              Pi (Dom Hidden rel a) b   -> insertUnderscore rel (absName b)
 
1136
              Pi (Dom NotHidden _ _) _  -> lift $ typeError $ WrongHidingInApplication t0'
1079
1137
              _ -> lift $ typeError $ ShouldBePi t0'
1080
1138
    where
1081
 
        insertIFSUnderscore rel a = do v <- lift $ applyRelevanceToContext rel $ newIFSMeta a
1082
 
                                       lift $ reportSLn "tc.term.args.ifs" 15 $ "inserting implicit meta (2) for type " ++ show a
1083
 
                                       let arg = Arg Instance rel v
1084
 
                                       (vs, t0'') <- checkArguments exh r args0 (piApply t0 [arg]) t1
1085
 
                                       return (arg : vs, t0'')
1086
 
        insertUnderscore rel = do
 
1139
        insertIFSUnderscore rel x a = do
 
1140
          lift $ reportSLn "tc.term.args.ifs" 15 $ "inserting implicit meta (2) for type " ++ show a
 
1141
          v <- lift $ applyRelevanceToContext rel $ initializeIFSMeta x a
 
1142
          let arg = Arg Instance rel v
 
1143
          (vs, t0'') <- checkArguments exh expandIFS r args0 (piApply t0 [arg]) t1
 
1144
          return (arg : vs, t0'')
 
1145
 
 
1146
        insertUnderscore rel x = do
1087
1147
          scope <- lift $ getScope
1088
1148
          let m = A.Underscore $ A.MetaInfo
1089
1149
                  { A.metaRange  = r
1090
1150
                  , A.metaScope  = scope
1091
1151
                  , A.metaNumber = Nothing
 
1152
                  , A.metaNameSuggestion = x
1092
1153
                  }
1093
 
          checkArguments exh r (Arg Hidden rel (unnamed m) : args0) t0 t1
 
1154
          checkArguments exh expandIFS r (Arg Hidden rel (unnamed m) : args0) t0 t1
1094
1155
 
1095
1156
        name (Named _ (A.Var x)) = show x
1096
1157
        name (Named (Just x) _)    = x
1099
1160
        sameName Nothing _  = True
1100
1161
        sameName n1      n2 = n1 == n2
1101
1162
 
1102
 
        nameInPi (Pi _ b)  = Just $ absName b
1103
 
        nameInPi _         = __IMPOSSIBLE__
 
1163
        nameInPi (Pi _ b)   = Just $ absName b
 
1164
        nameInPi (Shared p) = nameInPi (derefPtr p)
 
1165
        nameInPi _          = __IMPOSSIBLE__
1104
1166
 
1105
1167
 
1106
1168
-- | Check that a list of arguments fits a telescope.
1107
1169
checkArguments_ :: ExpandHidden -> Range -> [NamedArg A.Expr] -> Telescope -> TCM Args
1108
1170
checkArguments_ exh r args tel = do
1109
 
    z <- runErrorT $ checkArguments exh r args (telePi tel $ sort Prop) (sort Prop)
 
1171
    z <- runErrorT $ checkArguments exh ExpandInstanceArguments r args (telePi tel $ sort Prop) (sort Prop)
1110
1172
    case z of
1111
1173
      Right (args, _) -> return args
1112
1174
      Left _          -> __IMPOSSIBLE__
1113
1175
 
1114
1176
 
1115
1177
-- | Infer the type of an expression. Implemented by checking against a meta
 
1178
--   variable.  Except for neutrals, for them a polymorphic type is inferred.
1116
1179
inferExpr :: A.Expr -> TCM (Term, Type)
1117
 
inferExpr e = do
1118
 
    -- Andreas, 2011-04-27
1119
 
    t <- workOnTypes $ newTypeMeta_
1120
 
    v <- checkExpr e t
1121
 
    return (v,t)
 
1180
inferExpr e = inferOrCheck e Nothing
 
1181
{-
 
1182
case e of
 
1183
  _ | Application hd args <- appView e, defOrVar hd -> traceCall (InferExpr e) $ do
 
1184
    (f, t0) <- inferHead hd
 
1185
    res <- runErrorT $ checkArguments DontExpandLast ExpandInstanceArguments (getRange hd) args t0 (sort Prop)
 
1186
    case res of
 
1187
      Right (vs, t1) -> return (f vs, t1)
 
1188
      Left t1 -> fallback -- blocked on type t1
 
1189
  _ -> fallback
 
1190
  where
 
1191
    fallback = do
 
1192
      t <- workOnTypes $ newTypeMeta_
 
1193
      v <- checkExpr e t
 
1194
      return (v,t)
 
1195
-}
 
1196
 
 
1197
defOrVar :: A.Expr -> Bool
 
1198
defOrVar A.Var{} = True
 
1199
defOrVar A.Def{} = True
 
1200
defOrVar _     = False
 
1201
 
 
1202
inferOrCheck :: A.Expr -> Maybe Type -> TCM (Term, Type)
 
1203
inferOrCheck e mt = case e of
 
1204
  _ | Application hd args <- appView e, defOrVar hd -> traceCall (InferExpr e) $ do
 
1205
    (f, t0) <- inferHead hd
 
1206
    res <- runErrorT $ checkArguments DontExpandLast ExpandInstanceArguments (getRange hd) args t0 $ maybe (sort Prop) id mt
 
1207
    case res of
 
1208
      Right (vs, t1) -> maybe (return (f vs, t1))
 
1209
                              (\ t -> (,t) <$> coerce (f vs) t1 t)
 
1210
                              mt
 
1211
      Left t1        -> fallback -- blocked on type t1
 
1212
  _ -> fallback
 
1213
  where
 
1214
    fallback = do
 
1215
      t <- maybe (workOnTypes $ newTypeMeta_) return mt
 
1216
      v <- checkExpr e t
 
1217
      return (v,t)
 
1218
 
 
1219
-- | Infer the type of an expression, and if it is of the form
 
1220
--   @{tel} -> D vs@ for some datatype @D@ then insert the hidden
 
1221
--   arguments.  Otherwise, leave the type polymorphic.
 
1222
inferExprForWith :: A.Expr -> TCM (Term, Type)
 
1223
inferExprForWith e = do
 
1224
  (v, t) <- inferExpr e
 
1225
  TelV tel t0 <- telViewUpTo' (-1) ((NotHidden /=) . domHiding) t
 
1226
  case ignoreSharing $ unEl t0 of
 
1227
    Def d vs -> do
 
1228
      res <- isDataOrRecordType d
 
1229
      case res of
 
1230
        Nothing -> return (v, t)
 
1231
        Just{}  -> do
 
1232
          (args, t1) <- implicitArgs (-1) (NotHidden /=) t
 
1233
          return (v `apply` args, t1)
 
1234
    _ -> return (v, t)
1122
1235
 
1123
1236
checkTerm :: Term -> Type -> TCM Term
1124
1237
checkTerm tm ty = do atm <- reify tm
1133
1245
checkLetBindings = foldr (.) id . map checkLetBinding
1134
1246
 
1135
1247
checkLetBinding :: A.LetBinding -> TCM a -> TCM a
 
1248
 
1136
1249
checkLetBinding b@(A.LetBind i rel x t e) ret =
1137
1250
  traceCallCPS_ (CheckLetBinding b) ret $ \ret -> do
1138
1251
    t <- isType_ t
1139
1252
    v <- applyRelevanceToContext rel $ checkExpr e t
1140
1253
    addLetBinding rel x v t ret
 
1254
 
 
1255
checkLetBinding b@(A.LetPatBind i p e) ret =
 
1256
  traceCallCPS_ (CheckLetBinding b) ret $ \ret -> do
 
1257
    (v, t) <- inferExpr e
 
1258
    let -- construct a type  t -> dummy  for use in checkLeftHandSide
 
1259
        t0 = El (getSort t) $ Pi (Dom NotHidden Relevant t) (NoAbs "_" typeDontCare)
 
1260
        p0 = Arg NotHidden Relevant (Named Nothing p)
 
1261
    reportSDoc "tc.term.let.pattern" 10 $ vcat
 
1262
      [ text "let-binding pattern p at type t"
 
1263
      , nest 2 $ vcat
 
1264
        [ text "p (A) =" <+> text (show p) -- prettyTCM p
 
1265
        , text "t     =" <+> prettyTCM t
 
1266
        ]
 
1267
      ]
 
1268
    checkLeftHandSide (CheckPattern p EmptyTel t) [p0] t0 $ \ mgamma delta sub xs ps t' perm -> do
 
1269
      -- A single pattern in internal syntax is returned.
 
1270
      let p = case ps of [p] -> unArg p; _ -> __IMPOSSIBLE__
 
1271
      reportSDoc "tc.term.let.pattern" 20 $ nest 2 $ vcat
 
1272
        [ text "p (I) =" <+> text (show p)
 
1273
        , text "delta =" <+> text (show delta)
 
1274
        ]
 
1275
      -- We translate it into a list of projections.
 
1276
      fs <- recordPatternToProjections p
 
1277
      -- We remove the bindings for the pattern variables from the context.
 
1278
      cxt0 <- getContext
 
1279
      let (binds, cxt) = splitAt (size delta) cxt0
 
1280
      escapeContext (length binds) $ do
 
1281
        reportSDoc "tc.term.let.pattern" 20 $ nest 2 $ vcat
 
1282
          [ text "delta =" <+> prettyTCM delta
 
1283
          , text "binds =" <+> text (show binds) -- prettyTCM binds
 
1284
          ]
 
1285
{- WE CANNOT USE THIS BINDING
 
1286
       -- We add a first let-binding for the value of e.
 
1287
       x <- freshNoName (getRange e)
 
1288
       addLetBinding Relevant x v t $ do
 
1289
 -}
 
1290
        -- We create a substitution for the let-bound variables
 
1291
        -- (unfortunately, we cannot refer to x in internal syntax
 
1292
        -- so we have to copy v).
 
1293
        let sigma = zipWith ($) fs (repeat v)
 
1294
        -- We apply the types of the let bound-variables to this substitution.
 
1295
        -- The 0th variable in a context is the last one, so we reverse.
 
1296
        -- Further, we need to lower all other de Bruijn indices by
 
1297
        -- the size of delta, so we append the identity substitution.
 
1298
        let sub    = parallelS (reverse sigma)
 
1299
        let fdelta = flattenTel delta
 
1300
        reportSDoc "tc.term.let.pattern" 20 $ nest 2 $ vcat
 
1301
          [ text "fdelta =" <+> text (show fdelta)
 
1302
          ]
 
1303
        let tsl  = applySubst sub fdelta
 
1304
        -- We get a list of types
 
1305
        let ts   = map unDom tsl
 
1306
        -- and relevances.
 
1307
        let rels = map domRelevance tsl
 
1308
        -- We get list of names of the let-bound vars from the context.
 
1309
        let xs   = map (fst . unDom) (reverse binds)
 
1310
        -- We add all the bindings to the context.
 
1311
        foldr (uncurry4 addLetBinding) ret $ zip4 rels xs sigma ts
 
1312
 
1141
1313
checkLetBinding (A.LetApply i x modapp rd rm) ret = do
1142
1314
  -- Any variables in the context that doesn't belong to the current
1143
1315
  -- module should go with the new module.