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

« back to all changes in this revision

Viewing changes to src/full/Agda/Syntax/Translation/ConcreteToAbstract.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
1
{-# LANGUAGE CPP, MultiParamTypeClasses, FunctionalDependencies,
2
 
             FlexibleInstances, UndecidableInstances, OverlappingInstances
 
2
             FlexibleInstances, UndecidableInstances, OverlappingInstances,
 
3
             ScopedTypeVariables
3
4
  #-}
4
5
 
5
6
{-| Translation from "Agda.Syntax.Concrete" to "Agda.Syntax.Abstract". Involves scope analysis,
26
27
import Control.Monad.Reader hiding (mapM)
27
28
import Control.Monad.Error hiding (mapM)
28
29
import Data.Typeable
29
 
import Data.Traversable (mapM)
30
 
import Data.List ((\\), nub)
 
30
import Data.Traversable (mapM, traverse)
 
31
import Data.List ((\\), nub, foldl')
31
32
import qualified Data.Map as Map
32
33
 
33
34
import Agda.Syntax.Concrete as C hiding (topLevelModuleName)
34
35
import Agda.Syntax.Concrete.Operators
 
36
-- import qualified Agda.Syntax.Concrete.Copatterns as Cop -- merged into Operators
35
37
import Agda.Syntax.Abstract as A
 
38
import Agda.Syntax.Abstract.Copatterns
36
39
import Agda.Syntax.Position
37
40
import Agda.Syntax.Common
38
41
import Agda.Syntax.Info
39
42
import Agda.Syntax.Concrete.Definitions as C
40
 
import Agda.Syntax.Concrete.Operators
41
43
import Agda.Syntax.Concrete.Pretty
42
44
import Agda.Syntax.Abstract.Pretty
43
45
import Agda.Syntax.Fixity
44
46
import Agda.Syntax.Notation
45
47
import Agda.Syntax.Scope.Base
46
48
import Agda.Syntax.Scope.Monad
47
 
import Agda.Syntax.Strict
48
49
 
49
50
import Agda.TypeChecking.Monad.Base (TypeError(..), Call(..), typeError,
50
 
                                     TCErr(..), TCErr'(..), extendlambdaname)
 
51
                                     TCErr(..), extendlambdaname)
51
52
import Agda.TypeChecking.Monad.Trace (traceCall, traceCallCPS, setCurrentRange)
52
53
import Agda.TypeChecking.Monad.State
53
54
import Agda.TypeChecking.Monad.Options
85
86
printScope :: String -> Int -> String -> ScopeM ()
86
87
printScope tag v s = verboseS ("scope." ++ tag) v $ do
87
88
  scope <- getScope
88
 
  reportSLn "" 0 $ s ++ " " ++ show scope
 
89
  reportSDoc "" 0 $ return $ vcat [ text s, text $ show scope ]
89
90
 
90
91
{--------------------------------------------------------------------------
91
92
    Helpers
92
93
 --------------------------------------------------------------------------}
93
94
 
94
 
lhsArgs :: C.Pattern -> (C.Name, [NamedArg C.Pattern])
95
 
lhsArgs p = case appView p of
96
 
    Arg _ _ (Named _ (IdentP (C.QName x))) : ps -> (x, ps)
97
 
    _                                         -> __IMPOSSIBLE__
98
 
    where
99
 
        mkHead    = Arg NotHidden Relevant . unnamed
100
 
        notHidden = Arg NotHidden Relevant . unnamed
101
 
        appView p = case p of
102
 
            AppP p arg    -> appView p ++ [arg]
103
 
            OpAppP _ x ps -> mkHead (IdentP $ C.QName x) : map notHidden ps
104
 
            ParenP _ p    -> appView p
105
 
            RawAppP _ _   -> __IMPOSSIBLE__
106
 
            _             -> [ mkHead p ]
107
 
 
108
95
annotateDecl :: ScopeM A.Declaration -> ScopeM A.Declaration
109
96
annotateDecl m = annotateDecls $ (:[]) <$> m
110
97
 
134
121
    xs = concatMap vars ps
135
122
    vars :: A.Pattern' e -> [C.Name]
136
123
    vars p = case p of
137
 
      A.VarP x        -> [nameConcrete x]
138
 
      A.ConP _ _ args -> concatMap (vars . namedThing . unArg) args
139
 
      A.WildP _       -> []
140
 
      A.AsP _ x p     -> nameConcrete x : vars p
141
 
      A.DotP _ _      -> []
142
 
      A.AbsurdP _     -> []
143
 
      A.LitP _        -> []
144
 
      A.DefP _ _ args -> __IMPOSSIBLE__
145
 
      A.ImplicitP _   -> __IMPOSSIBLE__
 
124
      A.VarP x               -> [nameConcrete x]
 
125
      A.ConP _ _ args        -> concatMap (vars . namedArg) args
 
126
      A.WildP _              -> []
 
127
      A.AsP _ x p            -> nameConcrete x : vars p
 
128
      A.DotP _ _             -> []
 
129
      A.AbsurdP _            -> []
 
130
      A.LitP _               -> []
 
131
      A.DefP _ _ args        -> concatMap (vars . namedArg) args
 
132
        -- Projection pattern, @args@ should be empty unless we have
 
133
        -- indexed records.
 
134
      A.ImplicitP _          -> __IMPOSSIBLE__
 
135
      A.PatternSynP _ _ args -> concatMap (vars . namedArg) args
146
136
 
147
137
-- | Compute the type of the record constructor (with bogus target type)
148
138
recordConstructorType :: [NiceDeclaration] -> C.Expr
156
146
    build (NiceField r f _ _ x (Arg h rel e) : fs) =
157
147
        C.Pi [C.TypedBindings r $ Arg h rel (C.TBind r [BName x f] e)] $ build fs
158
148
      where r = getRange x
159
 
    build (d : fs)                     = C.Let noRange (notSoNiceDeclarations [d]) $ build fs
 
149
    build (d : fs)                     = C.Let noRange [killRange $ notSoNiceDeclaration d] $
 
150
                                           build fs
160
151
    build []                           = C.SetN noRange 0 -- todo: nicer
161
152
 
162
153
checkModuleApplication (C.SectionApp _ tel e) m0 x dir' =
180
171
    printScope "mod.inst" 20 "copied source module"
181
172
    reportSLn "scope.mod.inst" 30 $ "renamings:\n  " ++ show renD ++ "\n  " ++ show renM
182
173
    return ((A.SectionApp tel' m1 args'), renD, renM)
183
 
checkModuleApplication (C.RecordModuleIFS _ rec) m0 x dir' =
 
174
checkModuleApplication (C.RecordModuleIFS _ recN) m0 x dir' =
184
175
  withCurrentModule m0 $ do
185
 
    m1 <- toAbstract $ OldModuleName rec
 
176
    m1 <- toAbstract $ OldModuleName recN
186
177
    s <- getNamedScope m1
187
178
    (s', (renM, renD)) <- copyScope m0 s
188
 
    s' <- applyImportDirectiveM rec dir' s'
 
179
    s' <- applyImportDirectiveM recN dir' s'
189
180
    modifyCurrentScope $ const s'
190
181
 
191
182
    printScope "mod.inst" 20 "copied record module"
318
309
nameExpr :: AbstractName -> A.Expr
319
310
nameExpr d = mk (anameKind d) $ anameName d
320
311
  where
321
 
    mk DefName = Def
322
 
    mk ConName = Con . AmbQ . (:[])
 
312
    mk DefName        = Def
 
313
    mk FldName        = Def
 
314
    mk ConName        = Con . AmbQ . (:[])
 
315
    mk PatternSynName = A.PatternSyn
323
316
 
324
317
instance ToAbstract OldQName A.Expr where
325
318
  toAbstract (OldQName x) = do
326
319
    qx <- resolveName x
327
320
    reportSLn "scope.name" 10 $ "resolved " ++ show x ++ ": " ++ show qx
328
321
    case qx of
329
 
      VarName x'         -> return $ A.Var x'
330
 
      DefinedName _ d    -> return $ nameExpr d
331
 
      ConstructorName ds -> return $ A.Con $ AmbQ (map anameName ds)
332
 
      UnknownName        -> notInScope x
 
322
      VarName x'          -> return $ A.Var x'
 
323
      DefinedName _ d     -> return $ nameExpr d
 
324
      FieldName     d     -> return $ nameExpr d
 
325
      ConstructorName ds  -> return $ A.Con $ AmbQ (map anameName ds)
 
326
      UnknownName         -> notInScope x
 
327
      PatternSynResName d -> return $ nameExpr d
333
328
 
334
329
data APatName = VarPatName A.Name
335
330
              | ConPatName [AbstractName]
 
331
              | PatternSynPatName AbstractName
336
332
 
337
333
instance ToAbstract PatName APatName where
338
334
  toAbstract (PatName x) = do
341
337
    z  <- case (rx, x) of
342
338
      -- TODO: warn about shadowing
343
339
      (VarName y,       C.QName x)                          -> return $ Left x -- typeError $ RepeatedVariableInPattern y x
 
340
      (FieldName d,     C.QName x)                          -> return $ Left x
344
341
      (DefinedName _ d, C.QName x) | DefName == anameKind d -> return $ Left x
345
342
      (UnknownName,     C.QName x)                          -> return $ Left x
346
 
      (ConstructorName ds, _)                               -> return $ Right ds
 
343
      (ConstructorName ds, _)                               -> return $ Right (Left ds)
 
344
      (PatternSynResName d, _)                              -> return $ Right (Right d)
347
345
      _                                                     ->
348
346
        typeError $ GenericError $
349
347
          "Cannot pattern match on " ++ show x ++ ", because it is not a constructor"
353
351
        p <- VarPatName <$> toAbstract (NewName x)
354
352
        printLocals 10 "bound it:"
355
353
        return p
356
 
      Right cs -> do
357
 
        reportSLn "scope.pat" 10 $ "it was a con: " ++ show (map anameName cs)
358
 
        return $ ConPatName cs
 
354
      Right (Left ds) -> do
 
355
        reportSLn "scope.pat" 10 $ "it was a con: " ++ show (map anameName ds)
 
356
        return $ ConPatName ds
 
357
      Right (Right d) -> do
 
358
        reportSLn "scope.pat" 10 $ "it was a pat syn: " ++ show (anameName d)
 
359
        return $ PatternSynPatName d
 
360
 
359
361
 
360
362
-- Should be a defined name.
361
363
instance ToAbstract OldName A.QName where
375
377
checkForModuleClash :: C.Name -> ScopeM ()
376
378
checkForModuleClash x = do
377
379
  ms <- scopeLookup (C.QName x) <$> getScope
378
 
  unless (null ms) $
 
380
  unless (null ms) $ do
 
381
    reportSLn "scope.clash" 20 $ "clashing modules ms = " ++ show ms
379
382
    setCurrentRange (getRange x) $
380
 
    typeError $ ShadowedModule $
 
383
      typeError $ ShadowedModule x $
381
384
                map ((`withRangeOf` x) . amodName) ms
382
385
 
383
386
instance ToAbstract NewModuleName A.ModuleName where
385
388
    checkForModuleClash x
386
389
    m <- getCurrentModule
387
390
    y <- freshQModule m x
388
 
    createModule y
 
391
    createModule False y
389
392
    return y
390
393
 
391
394
instance ToAbstract NewModuleQName A.ModuleName where
393
396
    where
394
397
      toAbs m (C.QName x)  = do
395
398
        y <- freshQModule m x
396
 
        createModule y
 
399
        createModule False y
397
400
        return y
398
401
      toAbs m (C.Qual x q) = do
399
402
        m' <- freshQModule m x
477
480
                    { metaRange  = r
478
481
                    , metaScope  = scope
479
482
                    , metaNumber = n
 
483
                    , metaNameSuggestion = ""
480
484
                    }
481
485
      C.Underscore r n -> do
482
486
        scope <- getScope
483
487
        return $ A.Underscore $ MetaInfo
484
488
                    { metaRange  = r
485
489
                    , metaScope  = scope
486
 
                    , metaNumber = n
 
490
                    , metaNumber = maybe Nothing __IMPOSSIBLE__ n
 
491
                    , metaNameSuggestion = maybe "" id n
487
492
                    }
488
493
 
489
494
  -- Raw application
537
542
            insertApp _ = __IMPOSSIBLE__
538
543
            insertHead (C.LHS p wps eqs with) = C.LHS (insertApp p) wps eqs with
539
544
            insertHead (C.Ellipsis r wps eqs with) = C.Ellipsis r wps eqs with
540
 
        scdef <- toAbstract (C.FunDef r [] defaultFixity' ConcreteDef cname
 
545
        scdef <- toAbstract (C.FunDef r [] defaultFixity' ConcreteDef True cname
541
546
                               (map (\(lhs,rhs,wh) -> -- wh = NoWhere, see parser for more info
542
547
                                      C.Clause cname (insertHead lhs) rhs wh []) cs))
543
548
        case scdef of
544
 
          (A.ScopedDecl si [A.FunDef di qname' cs]) -> do
 
549
          (A.ScopedDecl si [A.FunDef di qname' NotDelayed cs]) -> do
545
550
            setScope si
546
551
            return $ A.ExtendedLam (ExprRange r) di qname' cs
547
552
          _ -> __IMPOSSIBLE__
557
562
-- Irrelevant non-dependent function type
558
563
 
559
564
      C.Fun r e1 e2 -> do
560
 
        Arg h rel (e0, dotted) <- fmapM (toAbstractDot FunctionSpaceDomainCtx) $ mkArg e1
 
565
        Arg h rel (e0, dotted) <- traverse (toAbstractDot FunctionSpaceDomainCtx) $ mkArg e1
561
566
        let e1 = Arg h (if dotted then Irrelevant else rel) e0
562
567
        e2 <- toAbstractCtx TopCtx e2
563
568
        let info = ExprRange r
698
703
-- | runs Syntax.Concrete.Definitions.niceDeclarations on main module
699
704
niceDecls :: [C.Declaration] -> ScopeM [NiceDeclaration]
700
705
niceDecls ds = case runNice $ niceDeclarations ds of
701
 
  Left e   -> throwError $ TCErr Nothing $ Exception (getRange e) (show e)
 
706
  Left e   -> throwError $ Exception (getRange e) (show e)
702
707
  Right ds -> return ds
703
708
 
704
709
instance ToAbstract [C.Declaration] [A.Declaration] where
705
 
  toAbstract ds = toAbstract =<< niceDecls ds
 
710
  toAbstract ds = do
 
711
    -- don't allow to switch off termination checker in --safe mode
 
712
    ds <- ifM (optSafe <$> commandLineOptions) (mapM noNoTermCheck ds) (return ds)
 
713
    toAbstract =<< niceDecls ds
 
714
   where
 
715
    noNoTermCheck (C.Pragma (NoTerminationCheckPragma r)) =
 
716
      typeError $ SafeFlagNoTerminationCheck
 
717
    noNoTermCheck d = return d
706
718
 
707
719
newtype LetDefs = LetDefs [C.Declaration]
708
720
newtype LetDef = LetDef NiceDeclaration
714
726
instance ToAbstract LetDef [A.LetBinding] where
715
727
    toAbstract (LetDef d) =
716
728
        case d of
717
 
            NiceMutual _ d@[C.FunSig _ fx _ rel x t, C.FunDef _ _ _ abstract _ [cl]] ->
 
729
            NiceMutual _ _ d@[C.FunSig _ fx _ rel _ x t, C.FunDef _ _ _ abstract _ _ [cl]] ->
718
730
                do  when (abstract == AbstractDef) $ do
719
731
                      typeError $ GenericError $ "abstract not allowed in let expressions"
720
732
                    e <- letToAbstract cl
722
734
                    x <- toAbstract (NewName $ C.BName x fx)
723
735
                    return [ A.LetBind (LetRange $ getRange d) rel x t e ]
724
736
 
 
737
            -- irrefutable let binding, like  (x , y) = rhs
 
738
            NiceFunClause r PublicAccess ConcreteDef termCheck d@(C.FunClause (C.LHS p [] [] []) (C.RHS rhs) NoWhere) -> do
 
739
              rhs <- toAbstract rhs
 
740
              p   <- parsePattern p
 
741
              p   <- toAbstract p
 
742
              checkPatternLinearity [p]
 
743
              p   <- toAbstract p
 
744
              return [ A.LetPatBind (LetRange r) p rhs ]
 
745
 
725
746
            -- You can't open public in a let
726
747
            NiceOpen r x dirs | not (C.publicOpen dirs) -> do
727
748
              m       <- toAbstract (OldModuleName x)
743
764
            _   -> notAValidLetBinding d
744
765
        where
745
766
            letToAbstract (C.Clause top clhs@(C.LHS p [] [] []) (C.RHS rhs) NoWhere []) = do
746
 
                p    <- parseLHS (Just top) p
 
767
{-
 
768
                p    <- parseLHS top p
747
769
                localToAbstract (snd $ lhsArgs p) $ \args ->
 
770
-}
 
771
                (x, args) <- do
 
772
                  res <- parseLHS top p
 
773
                  case res of
 
774
                    C.LHSHead x args -> return (x, args)
 
775
                    C.LHSProj{} -> typeError $ GenericError $ "copatterns not allowed in let bindings"
 
776
 
 
777
                localToAbstract args $ \args ->
748
778
                    do  rhs <- toAbstract rhs
749
779
                        foldM lambda rhs (reverse args)  -- just reverse because these DomainFree
750
780
            letToAbstract _ = notAValidLetBinding d
770
800
 
771
801
  -- Axiom
772
802
    C.Axiom r f p rel x t -> do
 
803
      -- check that we do not postulate in --safe mode
773
804
      clo <- commandLineOptions
774
805
      when (optSafe clo) (typeError (SafeFlagPostulate x))
775
 
      t' <- toAbstractCtx TopCtx t
776
 
      y  <- freshAbstractQName f x
777
 
      bindName p DefName x y
778
 
      return [ A.Axiom (mkDefInfo x f p ConcreteDef r) rel y t' ]
 
806
      -- check the postulate
 
807
      toAbstractNiceAxiom d
779
808
 
780
809
  -- Fields
781
810
    C.NiceField r f p a x t -> do
 
811
      unless (p == PublicAccess) $ typeError $ GenericError "Record fields can not be private"
782
812
      t' <- toAbstractCtx TopCtx t
783
813
      y  <- freshAbstractQName f x
784
814
      irrProj <- optIrrelevantProjections <$> pragmaOptions
786
816
        -- Andreas, 2010-09-24: irrelevant fields are not in scope
787
817
        -- this ensures that projections out of irrelevant fields cannot occur
788
818
        -- Ulf: unless you turn on --irrelevant-projections
789
 
        bindName p DefName x y
 
819
        bindName p FldName x y
790
820
      return [ A.Field (mkDefInfo x f p a r) y t' ]
791
821
 
792
822
  -- Primitive function
797
827
      return [ A.Primitive (mkDefInfo x f p a r) y t' ]
798
828
 
799
829
  -- Definitions (possibly mutual)
800
 
    NiceMutual r ds -> do
 
830
    NiceMutual r termCheck ds -> do
801
831
      ds' <- toAbstract ds
802
 
      return [ A.Mutual (DeclInfo C.noName_ r) ds' ]
803
 
                          -- TODO: what does the info mean here?
 
832
      return [ A.Mutual (MutualInfo termCheck r) ds' ]
804
833
 
805
834
    C.NiceRecSig r f a x ls t -> withLocalVars $ do
806
835
        let toTypeBinding :: C.LamBinding -> C.TypedBindings
820
849
               _            -> __IMPOSSIBLE__
821
850
        ls' <- toAbstract (map toTypeBinding ls)
822
851
        x'  <- freshAbstractQName f x
 
852
        {- -- Andreas, 2012-01-16: remember number of parameters
 
853
        bindName a (DataName (length ls)) x x' -}
823
854
        bindName a DefName x x'
824
855
        t' <- toAbstract t
825
856
        return [ A.DataSig (mkDefInfo x f a ConcreteDef r) x' ls' t' ]
826
857
  -- Type signatures
827
 
    C.FunSig r f p rel x t -> (:[]) <$> toAbstract (C.Axiom r f p rel x t)
 
858
    C.FunSig r f p rel tc x t -> toAbstractNiceAxiom (C.Axiom r f p rel x t)
828
859
  -- Function definitions
829
 
    C.FunDef r ds f a x cs -> do
 
860
    C.FunDef r ds f a tc x cs -> do
830
861
        printLocals 10 $ "checking def " ++ show x
831
 
        (x',cs') <- toAbstract (OldName x,cs)
832
 
        return [ A.FunDef (mkDefInfo x f PublicAccess a r) x' cs' ]
 
862
        (x',cs) <- toAbstract (OldName x,cs)
 
863
        (delayed, cs) <- translateCopatternClauses cs
 
864
        return [ A.FunDef (mkDefInfo x f PublicAccess a r) x' delayed cs ]
 
865
 
 
866
  -- Uncategorized function clauses
 
867
    C.NiceFunClause r acc abs termCheck (C.FunClause lhs rhs wcls) ->
 
868
      typeError $ GenericError $
 
869
        "Missing type signature for left hand side " ++ show lhs
 
870
    C.NiceFunClause{} -> __IMPOSSIBLE__
833
871
 
834
872
  -- Data definitions
835
873
    C.DataDef r f a x pars cons -> withLocalVars $ do
848
886
        -- Create the module for the qualified constructors
849
887
        checkForModuleClash x -- disallow shadowing previously defined modules
850
888
        let m = mnameFromList $ qnameToList x'
851
 
        createModule m
 
889
        createModule True m
852
890
        bindModule p x m  -- make it a proper module
853
891
        cons <- toAbstract (map (ConstrDecl NoRec m a p) cons)
854
892
        -- Open the module
860
898
        conName _ = __IMPOSSIBLE__
861
899
 
862
900
  -- Record definitions (mucho interesting)
863
 
    C.RecDef r f a x cm pars fields ->
 
901
    C.RecDef r f a x ind cm pars fields ->
864
902
      withLocalVars $ do
865
903
        -- Check that the generated module doesn't clash with a previously
866
904
        -- defined module
872
910
        m0     <- getCurrentModule
873
911
        let m = A.qualifyM m0 $ mnameFromList $ (:[]) $ last $ qnameToList x'
874
912
        printScope "rec" 15 "before record"
875
 
        createModule m
 
913
        createModule False m
876
914
        afields <- withCurrentModule m $ do
877
915
          afields <- toAbstract fields
878
916
          printScope "rec" 15 "checked fields"
880
918
        bindModule p x m
881
919
        cm' <- mapM (\(ThingWithFixity c f) -> bindConstructorName m c f a p YesRec) cm
882
920
        printScope "rec" 15 "record complete"
883
 
        return [ A.RecDef (mkDefInfo x f PublicAccess a r) x' cm' pars contel afields ]
 
921
        return [ A.RecDef (mkDefInfo x f PublicAccess a r) x' ind cm' pars contel afields ]
884
922
 
 
923
    -- Andreas, 2012-10-30 anonymous modules are like Coq sections
885
924
    NiceModule r p a (C.QName name) tel ds ->
886
925
      traceCall (ScopeCheckDeclaration $ NiceModule r p a (C.QName name) tel []) $ do
 
926
      (name, p, isSection) <- if not (C.isNoName name)
 
927
        then return (name, p, False)
 
928
        else do
 
929
          (i :: NameId) <- fresh
 
930
          return (C.NoName (getRange name) i, PrivateAccess, True)
887
931
      aname <- toAbstract (NewModuleName name)
888
 
      x <- snd <$> scopeCheckModule r (C.QName name) aname tel ds
 
932
      ds <- snd <$> scopeCheckModule r (C.QName name) aname tel ds
889
933
      bindModule p name aname
890
 
      return x
 
934
      -- if the module was anonymous open it public
 
935
      when isSection $
 
936
        openModule_ (C.QName name) $
 
937
          defaultImportDir { publicOpen = True }
 
938
      return ds
891
939
 
892
940
    NiceModule _ _ _ C.Qual{} _ _ -> __IMPOSSIBLE__
893
941
 
962
1010
                           })
963
1011
                        m ]
964
1012
 
 
1013
    NicePatternSyn r fx n as p -> do
 
1014
      reportSLn "scope.pat" 10 $ "found nice pattern syn: " ++ show r
 
1015
 
 
1016
      isparameterised <- not . null <$> getLocalVars
 
1017
      when isparameterised $ typeError $ NotSupported
 
1018
          "pattern synonym in parameterised module"
 
1019
 
 
1020
      y <- freshAbstractQName fx n
 
1021
      bindName PublicAccess PatternSynName n y
 
1022
      defn <- withLocalVars $ do
 
1023
               p'   <- killRange <$> (toAbstract =<< toAbstract =<< parsePatternSyn p)
 
1024
               as'  <- mapM (\a -> unVarName =<< resolveName (C.QName a)) as
 
1025
               return (as', p')
 
1026
      modifyPatternSyns (Map.insert y defn)
 
1027
      return []
 
1028
      where unVarName (VarName a) = return a
 
1029
            unVarName _           = typeError $ UnusedVariableInPatternSynonym
 
1030
 
 
1031
    where
 
1032
      -- checking postulate or type sig. without checking safe flag
 
1033
      toAbstractNiceAxiom (C.Axiom r f p rel x t) = do
 
1034
        t' <- toAbstractCtx TopCtx t
 
1035
        y  <- freshAbstractQName f x
 
1036
        bindName p DefName x y
 
1037
        return [ A.Axiom (mkDefInfo x f p ConcreteDef r) rel y t' ]
 
1038
      toAbstractNiceAxiom _ = __IMPOSSIBLE__
 
1039
 
965
1040
 
966
1041
data IsRecordCon = YesRec | NoRec
967
1042
data ConstrDecl = ConstrDecl IsRecordCon A.ModuleName IsAbstract Access C.NiceDeclaration
968
1043
 
969
 
bindConstructorName m x f a p rec = do
 
1044
bindConstructorName m x f a p record = do
970
1045
  -- The abstract name is the qualified one
971
1046
  y <- withCurrentModule m $ freshAbstractQName f x
972
1047
  -- Bind it twice, once unqualified and once qualified
979
1054
    p' = case a of
980
1055
           AbstractDef -> PrivateAccess
981
1056
           _           -> p
982
 
    p'' = case (a, rec) of
 
1057
    p'' = case (a, record) of
983
1058
            (AbstractDef, _) -> PrivateAccess
984
1059
            (_, YesRec)      -> OnlyQualified   -- record constructors aren't really in the record module
985
1060
            _                -> PublicAccess
986
1061
 
987
1062
instance ToAbstract ConstrDecl A.Declaration where
988
 
  toAbstract (ConstrDecl rec m a p (C.Axiom r f _ rel x t)) = do -- rel==Relevant
 
1063
  toAbstract (ConstrDecl record m a p (C.Axiom r f _ rel x t)) = do -- rel==Relevant
989
1064
    t' <- toAbstractCtx TopCtx t
990
1065
    -- The abstract name is the qualified one
991
1066
    -- Bind it twice, once unqualified and once qualified
992
 
    y <- bindConstructorName m x f a p rec
 
1067
    y <- bindConstructorName m x f a p record
993
1068
    printScope "con" 15 "bound constructor"
994
1069
    return $ A.Axiom (mkDefInfo x f p ConcreteDef r) rel y t'
995
1070
 
1046
1121
      case e of
1047
1122
        A.Def x -> return [ A.EtaPragma x ]
1048
1123
        _       -> fail "Bad ETA pragma"
 
1124
    -- NO_TERMINATION_CHECK is handled by the nicifier
 
1125
    toAbstract (C.NoTerminationCheckPragma _) = __IMPOSSIBLE__
1049
1126
 
1050
1127
instance ToAbstract C.Clause A.Clause where
1051
1128
    toAbstract (C.Clause top C.Ellipsis{} _ _ _) = fail "bad '...'" -- TODO: errors message
1052
1129
    toAbstract (C.Clause top lhs@(C.LHS p wps eqs with) rhs wh wcs) = withLocalVars $ do
1053
 
      let wcs' = map (expandEllipsis p wps) wcs
 
1130
-- WAS:     let wcs' = map (expandEllipsis p wps) wcs
 
1131
      -- Andreas, 2012-02-14: need to reset local vars before checking subclauses
 
1132
      vars <- getLocalVars
 
1133
      let wcs' = map (\ c -> setLocalVars vars >> do return $ expandEllipsis p wps c) wcs
1054
1134
      lhs' <- toAbstract (LeftHandSide top p wps)
1055
1135
      printLocals 10 "after lhs:"
1056
1136
      let (whname, whds) = case wh of
1085
1165
  bindModule acc m am
1086
1166
  return (x, ds)
1087
1167
 
1088
 
data RightHandSide = RightHandSide [C.Expr] [C.Expr] [C.Clause] C.RHS [C.Declaration]
 
1168
data RightHandSide = RightHandSide
 
1169
  { rhsRewriteEqn :: [C.RewriteEqn]  -- ^ @rewrite e@ (many)
 
1170
  , rhsWithExpr   :: [C.WithExpr]    -- ^ @with e@ (many)
 
1171
  , rhsSubclauses :: [ScopeM C.Clause] -- ^ the subclauses spawned by a with (monadic because we need to reset the local vars before checking these clauses)
 
1172
  , rhs           :: C.RHS
 
1173
  , rhsWhereDecls :: [C.Declaration]
 
1174
  }
 
1175
 
1089
1176
data AbstractRHS = AbsurdRHS'
1090
 
                 | WithRHS' [A.Expr] [C.Clause]  -- ^ The with clauses haven't been translated yet
 
1177
                 | WithRHS' [A.Expr] [ScopeM C.Clause]  -- ^ The with clauses haven't been translated yet
1091
1178
                 | RHS' A.Expr
1092
1179
                 | RewriteRHS' [A.Expr] AbstractRHS [A.Declaration]
1093
1180
 
1110
1197
    return $ RewriteRHS auxs eqs rhs wh
1111
1198
  toAbstract (WithRHS' es cs) = do
1112
1199
    aux <- withFunctionName "with-"
1113
 
    A.WithRHS aux es <$> toAbstract cs
 
1200
    A.WithRHS aux es <$> do toAbstract =<< sequence cs
1114
1201
 
1115
1202
instance ToAbstract RightHandSide AbstractRHS where
1116
1203
  toAbstract (RightHandSide eqs@(_:_) es cs rhs wh) = do
1139
1226
instance ToAbstract LeftHandSide A.LHS where
1140
1227
    toAbstract (LeftHandSide top lhs wps) =
1141
1228
      traceCall (ScopeCheckLHS top lhs) $ do
1142
 
        p <- parseLHS (Just top) lhs
 
1229
        lhscore <- parseLHS top lhs
 
1230
        reportSLn "scope.lhs" 5 $ "parsed lhs: " ++ show lhscore
1143
1231
        printLocals 10 "before lhs:"
1144
 
        let (x, ps) = lhsArgs p
 
1232
        -- error if copattern parsed but no --copatterns option
 
1233
        haveCoPats <- optCopatterns <$> pragmaOptions
 
1234
        unless haveCoPats $
 
1235
          case lhscore of
 
1236
            C.LHSHead x ps -> return ()
 
1237
            C.LHSProj{} -> typeError $ NeedOptionCopatterns
 
1238
        -- scope check patterns except for dot patterns
 
1239
        lhscore <- toAbstract lhscore
 
1240
        reportSLn "scope.lhs" 5 $ "parsed lhs patterns: " ++ show lhscore
 
1241
        wps  <- toAbstract =<< mapM parsePattern wps
 
1242
        checkPatternLinearity $ lhsCoreAllPatterns lhscore ++ wps
 
1243
        printLocals 10 "checked pattern:"
 
1244
        -- scope check dot patterns
 
1245
        lhscore <- toAbstract lhscore
 
1246
        reportSLn "scope.lhs" 5 $ "parsed lhs dot patterns: " ++ show lhscore
 
1247
        wps     <- toAbstract wps
 
1248
        printLocals 10 "checked dots:"
 
1249
        return $ A.LHS (LHSRange $ getRange (lhs, wps)) lhscore wps
 
1250
 
 
1251
-- does not check pattern linearity
 
1252
instance ToAbstract C.LHSCore (A.LHSCore' C.Expr) where
 
1253
    toAbstract (C.LHSHead x ps) = do
1145
1254
        x    <- withLocalVars $ setLocalVars [] >> toAbstract (OldName x)
1146
1255
        args <- toAbstract ps
1147
 
        wps  <- toAbstract =<< mapM (parseLHS Nothing) wps
1148
 
        checkPatternLinearity (map (namedThing . unArg) args ++ wps)
1149
 
        printLocals 10 "checked pattern:"
1150
 
        args <- toAbstract args -- take care of dot patterns
1151
 
        wps  <- toAbstract wps
1152
 
        printLocals 10 "checked dots:"
1153
 
        return $ A.LHS (LHSRange $ getRange (lhs, wps)) x args wps
 
1256
        return $ A.LHSHead x args
 
1257
    toAbstract (C.LHSProj d ps1 l ps2) = do
 
1258
        qx <- resolveName d
 
1259
        d  <- case qx of
 
1260
                FieldName d -> return $ anameName d
 
1261
                UnknownName -> notInScope d
 
1262
                _           -> typeError $ GenericError $
 
1263
                  "head of copattern needs to be a field identifier, but "
 
1264
                  ++ show d ++ " isn't one"
 
1265
        args1 <- toAbstract ps1
 
1266
        l     <- toAbstract l
 
1267
        args2 <- toAbstract ps2
 
1268
        return $ A.LHSProj d args1 l args2
1154
1269
 
1155
1270
instance ToAbstract c a => ToAbstract (Arg c) (Arg a) where
1156
1271
    toAbstract (Arg h r e) = Arg h r <$> toAbstractCtx (hiddenArgumentCtx h) e
1158
1273
instance ToAbstract c a => ToAbstract (Named name c) (Named name a) where
1159
1274
    toAbstract (Named n e) = Named n <$> toAbstract e
1160
1275
 
 
1276
{- DOES NOT WORK ANYMORE with pattern synonyms
 
1277
instance ToAbstract c a => ToAbstract (A.LHSCore' c) (A.LHSCore' a) where
 
1278
    toAbstract = mapM toAbstract
 
1279
-}
 
1280
 
 
1281
instance ToAbstract (A.LHSCore' C.Expr) (A.LHSCore' A.Expr) where
 
1282
    toAbstract (A.LHSHead f ps)             = A.LHSHead f <$> mapM toAbstract ps
 
1283
    toAbstract (A.LHSProj d ps lhscore ps') = A.LHSProj d <$> mapM toAbstract ps
 
1284
      <*> mapM toAbstract lhscore <*> mapM toAbstract ps'
 
1285
 
1161
1286
-- Patterns are done in two phases. First everything but the dot patterns, and
1162
1287
-- then the dot patterns. This is because dot patterns can refer to variables
1163
1288
-- bound anywhere in the pattern.
1164
1289
 
1165
 
instance ToAbstract c a => ToAbstract (A.Pattern' c) (A.Pattern' a) where
1166
 
    toAbstract = mapM toAbstract
 
1290
instance ToAbstract (A.Pattern' C.Expr) (A.Pattern' A.Expr) where
 
1291
    toAbstract (A.VarP x)             = return $ A.VarP x
 
1292
    toAbstract (A.ConP i ds as)       = A.ConP i ds <$> mapM toAbstract as
 
1293
    toAbstract (A.DefP i x as)        = A.DefP i x <$> mapM toAbstract as
 
1294
    toAbstract (A.WildP i)            = return $ A.WildP i
 
1295
    toAbstract (A.AsP i x p)          = A.AsP i x <$> toAbstract p
 
1296
    toAbstract (A.DotP i e)           = A.DotP i <$> toAbstract e
 
1297
    toAbstract (A.AbsurdP i)          = return $ A.AbsurdP i
 
1298
    toAbstract (A.LitP l)             = return $ A.LitP l
 
1299
    toAbstract (A.ImplicitP i)        = return $ A.ImplicitP i
 
1300
    toAbstract (A.PatternSynP i x as) = do
 
1301
        p   <- lookupPatternSyn x
 
1302
        as' <- mapM toAbstract as
 
1303
        instPatternSyn p as'
 
1304
      where
 
1305
        instPatternSyn :: A.PatternSynDefn -> [NamedArg A.Pattern] -> ScopeM A.Pattern
 
1306
        instPatternSyn (ns, p) as
 
1307
            | length ns == length as = return $ substPattern s $ setRange (getRange i) p
 
1308
            | otherwise              = typeError $ PatternSynonymArityMismatch x
 
1309
          where
 
1310
          s = zipWith' (\n a -> (n, namedThing (unArg a))) ns as
 
1311
 
1167
1312
 
1168
1313
instance ToAbstract C.Pattern (A.Pattern' C.Expr) where
1169
1314
 
1170
1315
    toAbstract p@(C.IdentP x) = do
1171
1316
        px <- toAbstract (PatName x)
1172
1317
        case px of
1173
 
            VarPatName y  -> return $ VarP y
1174
 
            ConPatName ds -> return $ ConP (PatRange (getRange p))
1175
 
                                           (AmbQ $ map anameName ds)
1176
 
                                           []
 
1318
            VarPatName y        -> return $ VarP y
 
1319
            ConPatName ds       -> return $ ConP (PatRange (getRange p))
 
1320
                                                 (AmbQ $ map anameName ds)
 
1321
                                                 []
 
1322
            PatternSynPatName d -> return $ PatternSynP (PatRange (getRange p))
 
1323
                                                        (anameName d) []
1177
1324
 
1178
1325
    toAbstract p0@(AppP p q) = do
1179
1326
        (p', q') <- toAbstract (p,q)
1180
1327
        case p' of
1181
 
            ConP _ x as -> return $ ConP info x (as ++ [q'])
1182
 
            DefP _ x as -> return $ DefP info x (as ++ [q'])
1183
 
            _           -> typeError $ InvalidPattern p0
 
1328
            ConP _ x as        -> return $ ConP info x (as ++ [q'])
 
1329
            DefP _ x as        -> return $ DefP info x (as ++ [q'])
 
1330
            PatternSynP _ x as -> return $ PatternSynP info x (as ++ [q'])
 
1331
            _                  -> typeError $ InvalidPattern p0
1184
1332
        where
1185
1333
            r = getRange p0
1186
1334
            info = PatSource r $ \pr -> if appBrackets pr then ParenP r p0 else p0
1187
1335
 
1188
1336
    toAbstract p0@(OpAppP r op ps) = do
1189
 
        p <- toAbstract (IdentP $ C.QName op)
 
1337
        p <- toAbstract (IdentP op)
1190
1338
        ps <- toAbstract ps
1191
1339
        case p of
1192
 
          ConP _ x as -> return $ ConP info x (as ++ map (Arg NotHidden Relevant . unnamed) ps)
1193
 
          DefP _ x as -> return $ DefP info x (as ++ map (Arg NotHidden Relevant. unnamed) ps)
1194
 
          _           -> __IMPOSSIBLE__
 
1340
          ConP        _ x as -> return $ ConP info x
 
1341
                                    (as ++ map (Arg NotHidden Relevant . unnamed) ps)
 
1342
          DefP        _ x as -> return $ DefP info x
 
1343
                                    (as ++ map (Arg NotHidden Relevant . unnamed) ps)
 
1344
          PatternSynP _ x as -> return $ PatternSynP info x
 
1345
                                    (as ++ map (Arg NotHidden Relevant . unnamed) ps)
 
1346
          _                  -> __IMPOSSIBLE__
1195
1347
        where
1196
 
            r = getRange p0
 
1348
            r    = getRange p0
1197
1349
            info = PatSource r $ \pr -> if appBrackets pr then ParenP r p0 else p0
1198
1350
 
1199
1351
    -- Removed when parsing
1200
 
    toAbstract (HiddenP _ _) = __IMPOSSIBLE__
 
1352
    toAbstract (HiddenP _ _)   = __IMPOSSIBLE__
1201
1353
    toAbstract (InstanceP _ _) = __IMPOSSIBLE__
1202
 
    toAbstract (RawAppP _ _) = __IMPOSSIBLE__
 
1354
    toAbstract (RawAppP _ _)   = __IMPOSSIBLE__
1203
1355
 
1204
1356
    toAbstract p@(C.WildP r)    = return $ A.WildP (PatSource r $ const p)
1205
1357
    toAbstract (C.ParenP _ p)   = toAbstract p
1216
1368
    toAbstract p0@(C.DotP r e) = return $ A.DotP info e
1217
1369
        where info = PatSource r $ \_ -> p0
1218
1370
    toAbstract p0@(C.AbsurdP r) = return $ A.AbsurdP info
1219
 
        where
1220
 
            info = PatSource r $ \_ -> p0
 
1371
        where info = PatSource r $ \_ -> p0
1221
1372
 
1222
1373
-- | Turn an operator application into abstract syntax. Make sure to record the
1223
1374
-- right precedences for the various arguments.
1224
 
toAbstractOpApp :: C.Name -> [OpApp C.Expr] -> ScopeM A.Expr
1225
 
toAbstractOpApp op@(C.NoName _ _) es = __IMPOSSIBLE__
1226
 
toAbstractOpApp op@(C.Name _ _) es = do
1227
 
    f  <- getFixity (C.QName op)
 
1375
toAbstractOpApp :: C.QName -> [OpApp C.Expr] -> ScopeM A.Expr
 
1376
toAbstractOpApp op es = do
 
1377
    f  <- getFixity op
1228
1378
    let (_,_,parts) = oldToNewNotation $ (op, f)
1229
 
    op <- toAbstract (OldQName $ C.QName op)
1230
 
    foldl app op <$> left (theFixity f) [p | p <- parts, not (isBindingHole p)] es
 
1379
    op <- toAbstract (OldQName op)
 
1380
    foldl' app op <$> left (theFixity f) [p | p <- parts, not (isBindingHole p)] es
1231
1381
    where
1232
1382
        app e arg = A.App (ExprRange (fuseRange e arg)) e
1233
1383
                  $ Arg NotHidden Relevant $ unnamed arg