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

« back to all changes in this revision

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

  • Committer: Package Import Robot
  • Author(s): Iain Lane, d5cf60f
  • Date: 2015-05-20 13:08:33 UTC
  • mfrom: (1.1.7)
  • Revision ID: package-import@ubuntu.com-20150520130833-cdcmhagwsouna237
Tags: 2.4.2.2-2
[d5cf60f] Depend on ${shlibs:Depends}, to get libc (& maybe other) deps

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
{-# LANGUAGE CPP #-}
 
1
{-# LANGUAGE CPP           #-}
2
2
{-# LANGUAGE PatternGuards #-}
3
3
 
4
4
module Agda.TypeChecking.Rules.Def where
7
7
import Control.Arrow ((***))
8
8
import Control.Applicative
9
9
import Control.Monad.State hiding (forM, mapM)
10
 
import Control.Monad.Error hiding (forM, mapM)
 
10
import Control.Monad.Reader hiding (forM, mapM)
11
11
 
12
12
import Data.Function
13
13
import Data.List hiding (sort)
46
46
import Agda.TypeChecking.CompiledClause.Compile
47
47
 
48
48
import Agda.TypeChecking.Rules.Term                ( checkExpr, inferExpr, inferExprForWith, checkDontExpandLast, checkTelescope_, ConvColor(..) )
49
 
import Agda.TypeChecking.Rules.LHS                 ( checkLeftHandSide )
 
49
import Agda.TypeChecking.Rules.LHS                 ( checkLeftHandSide, LHSResult(..) )
50
50
import {-# SOURCE #-} Agda.TypeChecking.Rules.Decl ( checkDecls )
51
51
 
 
52
import Agda.Utils.Except ( MonadError(catchError, throwError) )
 
53
import Agda.Utils.Lens
52
54
import Agda.Utils.Size
53
55
import Agda.Utils.Permutation
54
56
import Agda.Utils.Monad
55
57
 
56
 
#include "../../undefined.h"
 
58
#include "undefined.h"
57
59
import Agda.Utils.Impossible
58
60
 
59
61
---------------------------------------------------------------------------
140
142
                      , funTerminates     = Nothing
141
143
                      , funExtLam         = Nothing
142
144
                      , funWith           = Nothing
 
145
                      , funCopatternLHS   = False
143
146
                      }
144
147
  reportSDoc "tc.def.alias" 20 $ text "checkAlias: leaving"
145
148
 
238
241
              ]
239
242
 
240
243
        -- Add the definition
241
 
        addConstant name $
242
 
          defaultDefn ai name t $
 
244
        addConstant name =<< do
 
245
          -- If there was a pragma for this definition, we can set the
 
246
          -- funTerminates field directly.
 
247
          useTerPragma $ defaultDefn ai name t $
243
248
             Function
244
249
             { funClauses        = cs
245
250
             , funCompiled       = Just cc
253
258
             , funTerminates     = Nothing
254
259
             , funExtLam         = extlam
255
260
             , funWith           = with
 
261
             , funCopatternLHS   = isCopatternLHS cs
256
262
             }
257
263
 
258
264
        -- Andreas 2012-02-13: postpone polarity computation until after positivity check
265
271
    where
266
272
        npats = size . clausePats
267
273
 
268
 
{- BEGIN RETIRING implicit argument insertion
269
 
 
270
 
{- | Ensure that all clauses have the same number of trailing implicits.
271
 
Example:
272
 
 
273
 
@
274
 
  test : Bool → {A B : Set} → Set
275
 
  test true  {A}     = A
276
 
  test false {B = B} = B
277
 
@
278
 
 
279
 
@trailingImplicits@ patches these clauses to
280
 
 
281
 
@
282
 
  test : Bool → {A B : Set} → Set
283
 
  test true  {A} {_}     = A
284
 
  test false {_} {B = B} = B
285
 
@
286
 
 
287
 
such that the arity of the clauses of @test@ is uniform.
288
 
-}
289
 
trailingImplicits :: Type -> [A.SpineClause] -> TCM [A.SpineClause]
290
 
trailingImplicits t []       = __IMPOSSIBLE__
291
 
trailingImplicits t cs | hasProjP cs = return cs
292
 
  where
293
 
    hasProjP = any (any (isJust . A.isProjP) . A.spLhsPats . A.clauseLHS)
294
 
trailingImplicits t cs@(c:_) = do
295
 
  pps@((ps,ips):_) <- mapM splitTrailingImplicits cs
296
 
  -- compute the trailing implicits from type t
297
 
  TelV tel t0 <- telView t
298
 
  let -- number of non-hidden patterns
299
 
      nh  = genericLength $ filter ((NotHidden ==) . getHiding) ps
300
 
      -- drop nh non-hidden domains from t
301
 
      l   = dropNonHidden nh $ telToList tel
302
 
      -- take the hidden domains immediately after the dropped stuff
303
 
      is   = takeWhile ((NotHidden /=) . getHiding) l
304
 
      itel = telFromList is
305
 
      -- get the trailing implicit patterns
306
 
      ipss = map snd pps
307
 
  -- complete the implicit pattern lists
308
 
  ipss <- mapM (\ ps -> insertImplicitPatterns DontExpandLast ps itel) ipss
309
 
  let longest = head $ sortBy (compare `on` ((0-) . length)) ipss
310
 
      pps' = zip (map fst pps) ipss
311
 
  return $ zipWith (patchUpTrailingImplicits longest) pps' cs
312
 
 
313
 
dropNonHidden :: Nat -> [I.Dom (String, Type)] -> [I.Dom (String, Type)]
314
 
dropNonHidden 0 l = l
315
 
dropNonHidden n l = case dropWhile ((NotHidden /=) . getHiding) l of
316
 
  []    -> [] -- or raise a type checking error "too many arguments in lhs"
317
 
  (_:l) -> dropNonHidden (n-1) l
318
 
 
319
 
splitTrailingImplicits :: A.SpineClause -> TCM (A.Patterns, A.Patterns)
320
 
splitTrailingImplicits (A.Clause (A.SpineLHS _ _ _ wps@(_ : _)) _ _) =
321
 
  typeError $ UnexpectedWithPatterns wps
322
 
splitTrailingImplicits (A.Clause (A.SpineLHS _ _ aps []) _ _) = do
323
 
  let (ips, ps) = span isHidden $ reverse aps
324
 
  return (reverse ps, reverse ips)
325
 
 
326
 
patchUpTrailingImplicits :: A.Patterns -> (A.Patterns, A.Patterns) -> A.SpineClause -> A.SpineClause
327
 
patchUpTrailingImplicits should (ps, is) c | length is >= length should = c
328
 
patchUpTrailingImplicits should (ps, is) (A.Clause (A.SpineLHS i x aps []) rhs0 wh) =
329
 
  let imp  = hide $ defaultArg $ Named Nothing $ A.ImplicitP $ Info.patNoRange
330
 
      imps = replicate (length should - length is) imp
331
 
  in  A.Clause (A.SpineLHS i x (ps ++ is ++ imps) []) rhs0 wh
332
 
patchUpTrailingImplicits _ _ _ = __IMPOSSIBLE__
333
 
 
 
274
-- | Set 'funTerminates' according to termination info in 'TCEnv',
 
275
--   which comes from a possible termination pragma.
 
276
useTerPragma :: Definition -> TCM Definition
 
277
useTerPragma def@Defn{ defName = name, theDef = fun@Function{}} = do
 
278
  tc <- asks envTerminationCheck
 
279
  let terminates = case tc of
 
280
        NonTerminating -> Just False
 
281
        Terminating    -> Just True
 
282
        _              -> Nothing
 
283
  reportSLn "tc.fundef" 30 $ unlines $
 
284
    [ "funTerminates of " ++ show name ++ " set to " ++ show terminates
 
285
    , "  tc = " ++ show tc
 
286
    ]
 
287
  return $ def { theDef = fun { funTerminates = terminates }}
 
288
useTerPragma def = return def
 
289
 
334
290
 
335
291
-- | Insert some patterns in the in with-clauses LHS of the given RHS
336
292
insertPatterns :: [A.Pattern] -> A.RHS -> A.RHS
337
293
insertPatterns pats (A.WithRHS aux es cs) = A.WithRHS aux es (map insertToClause cs)
338
294
    where insertToClause (A.Clause (A.LHS i lhscore ps) rhs ds)
339
295
              = A.Clause (A.LHS i lhscore (pats ++ ps)) (insertPatterns pats rhs) ds
340
296
insertPatterns pats (A.RewriteRHS qs eqs rhs wh) = A.RewriteRHS qs eqs (insertPatterns pats rhs) wh
341
297
insertPatterns pats rhs = rhs
376
316
    }
377
317
 
378
318
-- | Type check a function clause.
379
 
{-
380
 
checkClause :: Type -> A.Clause -> TCM Clause
381
 
checkClause t c@(A.Clause (A.LHS i (A.LHSProj{}) []) rhs0 wh) =
382
 
  typeError $ NotImplemented "type checking definitions by copatterns"
383
 
checkClause t c@(A.Clause (A.LHS i (A.LHSHead x aps) []) rhs0 wh) =
384
 
-}
385
319
checkClause :: Type -> A.SpineClause -> TCM Clause
386
 
{-
387
 
checkClause t c@(A.Clause lhs rhs0 wh) = do
388
 
    let A.SpineLHS i x aps withPats = A.lhsToSpine lhs
389
 
-}
390
320
checkClause t c@(A.Clause (A.SpineLHS i x aps withPats) rhs0 wh) = do
391
321
    unless (null withPats) $
392
322
      typeError $ UnexpectedWithPatterns withPats
393
323
    traceCall (CheckClause t c) $ do
394
324
    aps <- (traverse . traverse . traverse) expandPatternSynonyms aps
395
 
    checkLeftHandSide (CheckPatternShadowing c) (Just x) aps t $ \ mgamma delta sub xs ps trhs perm -> do
 
325
    checkLeftHandSide (CheckPatternShadowing c) (Just x) aps t $ \ (LHSResult mgamma delta sub xs ps trhs perm) -> do
396
326
      -- Note that we might now be in irrelevant context,
397
327
      -- in case checkLeftHandSide walked over an irrelevant projection pattern.
398
328
      let mkBody v = foldr (\x t -> Bind $ Abs x t) (Body $ applySubst sub v) xs
433
363
                          -- 1. rewriting with a reflexive equality to happen rarely,
434
364
                          -- 2. especially with ?-holes in the rewrite expression
435
365
                          -- 3. and a large overall number of ?s.
436
 
                          let sameIP = (==) `on` stInteractionPoints
 
366
                          let sameIP = (==) `on` (^.stInteractionPoints)
437
367
                          when (sameIP st st') $ put st
438
368
                          handleRHS $ A.RewriteRHS names eqs rhs wh
439
369
 
446
376
                     equality <- primEqualityName
447
377
                     Con reflCon [] <- ignoreSharing <$> primRefl
448
378
 
449
 
                     -- Andreas, 2014-05-17  Issue 1110:
450
 
                     -- Rewriting with REFL has no effect, but gives an
451
 
                     -- incomprehensible error message about the generated
452
 
                     -- with clause. Thus, we rather do simply nothing if
453
 
                     -- rewriting with REFL is attempted.
454
 
 
455
 
                     -- OBSOLETE:
456
 
                     -- let isRefl v = isRefl' . ignoreSharing =<< reduce v
457
 
                     --     isRefl' (Con c _) | c == reflCon = return True
458
 
                     --     isRefl' (Lam h t)                = isRefl $ unAbs t
459
 
                     --     isRefl' (DontCare t)             = isRefl t
460
 
                     --     isRefl' _                        = return False
461
 
 
462
 
                     -- ifM (isRefl proof) recurse $ {- else -} do
463
 
 
464
379
                     -- Check that the type is actually an equality (lhs ≡ rhs)
465
380
                     -- and extract lhs, rhs, and their type.
466
381
 
509
424
                                    -- is defined by induction on eqs.
510
425
                                    (A.RewriteRHS names eqs (insertPatterns pats rhs) inner)
511
426
                                    outer]
512
 
                         pats = [A.DotP patNoRange underscore, -- rewriteToExpr,
513
 
                                 A.ConP cinfo (AmbQ [conName reflCon]) []]
 
427
                         pats = [ A.DotP patNoRange underscore
 
428
                                , A.ConP cinfo (AmbQ [conName reflCon]) []]
514
429
                     reportSDoc "tc.rewrite.top" 25 $ vcat
515
430
                                         [ text "rewrite"
516
431
                                         , text "  from  = " <+> prettyTCM rewriteFromExpr
528
443
                    ]
529
444
                  reportSDoc "tc.with.top" 30 $
530
445
                    prettyA c
 
446
                  reportSDoc "tc.with.top" 20 $ do
 
447
                    m  <- currentModule
 
448
                    nfv <- getModuleFreeVars m
 
449
                    sep [ text "with function module:" <+>
 
450
                          prettyList (map prettyTCM $ mnameToList m)
 
451
                        ,  text $ "free variables: " ++ show nfv
 
452
                        ]
 
453
 
531
454
                  -- Infer the types of the with expressions
532
 
                  vas <- mapM inferExprForWith es
533
 
                  (vs0, as) <- instantiateFull (unzip vas)
 
455
                  (vs0, as) <- unzip <$> mapM inferExprForWith es
534
456
                  (vs, as)  <- normalise (vs0, as)
535
457
 
536
 
                  -- Invent a clever name for the with function
537
 
                  m <- currentModule
538
 
                  reportSDoc "tc.with.top" 20 $ text "with function module:" <+> prettyList (map prettyTCM $ mnameToList m)
539
 
 
540
458
                  -- Split the telescope into the part needed to type the with arguments
541
459
                  -- and all the other stuff
542
460
                  let fv = allVars $ freeVars (vs, as)
561
479
                    ]
562
480
 
563
481
                  -- Create the body of the original function
564
 
{- OLD
565
 
                  ctx <- getContextTelescope
566
 
                  let n    = size ctx
567
 
                      m    = size delta
568
 
                      -- All the context variables
569
 
                      us   = [ Arg h r (var i) | (i, Arg h r _) <- zip [n - 1,n - 2..0] $ telToList ctx ]
570
 
-}
 
482
 
571
483
                  -- All the context variables
572
484
                  us <- getContextArgs
573
 
                  let n    = size us
574
 
                      m    = size delta
 
485
                  let n = size us
 
486
                      m = size delta
575
487
                      -- First the variables bound outside this definition
576
488
                      (us0, us1') = genericSplitAt (n - m) us
577
489
                      -- Then permute the rest and grab those needed to for the with arguments
584
496
                  -- and Δ₁ ⊢ vs : as
585
497
                  (vs, as) <- do
586
498
                    let -- We know that as does not depend on Δ₂
587
 
                        rho = parallelS (replicate (size delta2) __IMPOSSIBLE__)
 
499
                        rho = compactS __IMPOSSIBLE__ (replicate (size delta2) Nothing)
588
500
                    return $ applySubst rho $ renameP (reverseP perm') (vs, as)
589
501
 
590
502
 
591
503
                  -- Andreas, 2013-02-26 add with-name to signature for printing purposes
592
 
                  addConstant aux (Defn defaultArgInfo aux typeDontCare [] [] [] 0 noCompiledRep emptyFunction)
 
504
                  addConstant aux =<< do
 
505
                    useTerPragma $ Defn defaultArgInfo aux typeDontCare [] [] [] 0 noCompiledRep [] Nothing emptyFunction
593
506
 
594
507
                  -- Andreas, 2013-02-26 separate msgs to see which goes wrong
595
508
                  reportSDoc "tc.with.top" 20 $
607
520
                  reportSDoc "tc.with.top" 20 $
608
521
                    text "              body" <+> (addCtxTel delta $ prettyTCM $ mkBody v)
609
522
 
610
 
{-
611
 
                  reportSDoc "tc.with.top" 20 $ vcat
612
 
                    [ text "    with arguments" <+> do escapeContext (size delta2) $ prettyList (map prettyTCM vs)
613
 
                    , text "             types" <+> do escapeContext (size delta2) $ prettyList (map prettyTCM as)
614
 
                    , text "with function call" <+> prettyTCM v
615
 
                    , text "           context" <+> (prettyTCM =<< getContextTelescope)
616
 
                    , text "             delta" <+> do escapeContext (size delta) $ prettyTCM delta
617
 
                    , text "                fv" <+> text (show fv)
618
 
                    , text "              body" <+> (addCtxTel delta $ prettyTCM $ mkBody v)
619
 
                    ]
620
 
-}
621
523
                  gamma <- maybe (typeError $ NotImplemented "with clauses for functions with unfolding arity") return mgamma
622
524
                  return (mkBody v, WithFunction x aux gamma delta1 delta2 vs as t' ps perm' perm finalPerm cs)
623
525
          in handleRHS rhs0
642
544
               , clauseBody      = body
643
545
               , clauseType      = Just trhs
644
546
               }
645
 
{-
646
 
checkClause t (A.Clause (A.LHS _ _ ps@(_ : _)) _ _) = typeError $ UnexpectedWithPatterns ps
647
 
-}
 
547
 
648
548
 
649
549
checkWithFunction :: WithFunctionProblem -> TCM ()
650
550
checkWithFunction NoWithFunction = return ()
674
574
  reportSLn "tc.with.top" 20 "created with display form"
675
575
 
676
576
  -- Generate the type of the with function
 
577
  delta1 <- normalise delta1 -- Issue 1332: checkInternal is picky about argInfo
 
578
                             -- but module application is sloppy.
 
579
                             -- We normalise to get rid of Def's coming
 
580
                             -- from module applications.
677
581
  candidateType <- withFunctionType delta1 vs as delta2 b
678
582
  reportSDoc "tc.with.type" 10 $ sep [ text "candidate type:", nest 2 $ prettyTCM candidateType ]
679
583
  reportSDoc "tc.with.type" 50 $ sep [ text "candidate type:", nest 2 $ text $ show candidateType ]
720
624
      , prettyList $ map prettyTCM ts
721
625
      , prettyTCM dt
722
626
      ]
723
 
  addConstant aux (Defn defaultArgInfo aux auxType [] [] [df] 0 noCompiledRep emptyFunction)
 
627
  addConstant aux =<< do
 
628
    useTerPragma $ Defn defaultArgInfo aux auxType [] [] [df] 0 noCompiledRep [] Nothing emptyFunction
724
629
  -- solveSizeConstraints -- Andreas, 2012-10-16 does not seem necessary
725
630
 
726
631
  reportSDoc "tc.with.top" 10 $ sep
773
678
    A.ConP _ _ ps -> any (containsAbsurdPattern . namedArg) ps
774
679
    A.DefP _ _ _  -> False  -- projection pattern
775
680
    A.PatternSynP _ _ _ -> __IMPOSSIBLE__ -- False
776
 
 
777
 
{- UNUSED
778
 
actualConstructor :: QName -> TCM QName
779
 
actualConstructor c = do
780
 
    v <- constructorForm =<< getConTerm c
781
 
    case ignoreSharing v of
782
 
        Con c _ -> return $ conName c
783
 
        _       -> actualConstructor =<< stripLambdas v
784
 
    where
785
 
        stripLambdas v = case ignoreSharing v of
786
 
            Con c _ -> return c
787
 
            Lam info b -> do
788
 
                x <- freshName_ $ absName b
789
 
                addCtx x (Dom info $ sort Prop) $
790
 
                         stripLambdas (absBody b)
791
 
            _       -> typeError $ GenericError $ "Not a constructor: " ++ show c
792
 
-}