on 031ffb4 help sign in
Idris-dev/src/Idris/AbsSyntax.hs
1301 lines 54 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntax(module Idris.AbsSyntax, module Idris.AbsSyntaxTree) where
6import Core.TT
7import Core.Evaluate
8import Core.Elaborate hiding (Tactic(..))
9import Core.Typecheck
10import Idris.AbsSyntaxTree
11import Idris.IdeSlave
12import IRTS.CodegenCommon
13import Util.DynamicLinker
15import Paths_idris
17import System.Console.Haskeline
19import Control.Monad.State
21import Data.List
22import Data.Char
23import Data.Either
25import Debug.Trace
27import Util.Pretty
28import Util.System
30getContext :: Idris Context
31getContext = do i <- getIState; return (tt_ctxt i)
33forTarget :: Target -> [(Target, a)] -> [a]
34forTarget tgt xs = [x | (tgt', x) <- xs, tgt == tgt']
36getObjectFiles :: Target -> Idris [FilePath]
37getObjectFiles tgt = do i <- getIState; return (forTarget tgt $ idris_objs i)
39addObjectFile :: Target -> FilePath -> Idris ()
40addObjectFile tgt f = do i <- getIState; putIState $ i { idris_objs = (tgt, f) : idris_objs i }
42getLibs :: Target -> Idris [String]
43getLibs tgt = do i <- getIState; return (forTarget tgt $ idris_libs i)
45addLib :: Target -> String -> Idris ()
46addLib tgt f = do i <- getIState; putIState $ i { idris_libs = (tgt, f) : idris_libs i }
48addDyLib :: [String] -> Idris (Either DynamicLib String)
49addDyLib libs = do i <- getIState
50 handle <- lift $ mapM (\l -> catchIO (tryLoadLib l) (\_ -> return Nothing)) libs
51 case msum handle of
52 Nothing -> return (Right $ "Could not load dynamic alternatives \"" ++
53 concat (intersperse "," libs) ++ "\"")
54 Just x -> do let ls = idris_dynamic_libs i
55 putIState $ i { idris_dynamic_libs = x:ls }
56 return (Left x)
58addHdr :: Target -> String -> Idris ()
59addHdr tgt f = do i <- getIState; putIState $ i { idris_hdrs = (tgt, f) : idris_hdrs i }
61addLangExt :: LanguageExt -> Idris ()
62addLangExt TypeProviders = do i <- getIState ; putIState $ i { idris_language_extensions = [TypeProviders] }
64totcheck :: (FC, Name) -> Idris ()
65totcheck n = do i <- getIState; putIState $ i { idris_totcheck = idris_totcheck i ++ [n] }
67setFlags :: Name -> [FnOpt] -> Idris ()
68setFlags n fs = do i <- getIState; putIState $ i { idris_flags = addDef n fs (idris_flags i) }
70setAccessibility :: Name -> Accessibility -> Idris ()
71setAccessibility n a
72 = do i <- getIState
73 let ctxt = setAccess n a (tt_ctxt i)
74 putIState $ i { tt_ctxt = ctxt }
76setTotality :: Name -> Totality -> Idris ()
77setTotality n a
78 = do i <- getIState
79 let ctxt = setTotal n a (tt_ctxt i)
80 putIState $ i { tt_ctxt = ctxt }
82getTotality :: Name -> Idris Totality
83getTotality n
84 = do i <- getIState
85 case lookupTotal n (tt_ctxt i) of
86 [t] -> return t
87 _ -> return (Total [])
89-- Get coercions which might return the required type
90getCoercionsTo :: IState -> Type -> [Name]
91getCoercionsTo i ty =
92 let cs = idris_coercions i
93 (fn,_) = unApply (getRetTy ty) in
94 findCoercions fn cs
95 where findCoercions t [] = []
96 findCoercions t (n : ns) =
97 let ps = case lookupTy n (tt_ctxt i) of
98 [ty] -> case unApply (getRetTy ty) of
99 (t', _) ->
100 if t == t' then [n] else []
101 _ -> [] in
102 ps ++ findCoercions t ns
104addToCG :: Name -> CGInfo -> Idris ()
105addToCG n cg
106 = do i <- getIState
107 putIState $ i { idris_callgraph = addDef n cg (idris_callgraph i) }
109addCoercion :: Name -> Idris ()
110addCoercion n = do i <- getIState
111 putIState $ i { idris_coercions = n : idris_coercions i }
113addDocStr :: Name -> String -> Idris ()
114addDocStr n doc
115 = do i <- getIState
116 putIState $ i { idris_docstrings = addDef n doc (idris_docstrings i) }
118addToCalledG :: Name -> [Name] -> Idris ()
119addToCalledG n ns = return () -- TODO
121-- Add a class instance function. Dodgy hack: Put integer instances first in the
122-- list so they are resolved by default.
123-- Dodgy hack 2: put constraint chasers (@@) last
125addInstance :: Bool -> Name -> Name -> Idris ()
126addInstance int n i
127 = do ist <- getIState
128 case lookupCtxt n (idris_classes ist) of
129 [CI a b c d ins] ->
130 do let cs = addDef n (CI a b c d (addI i ins)) (idris_classes ist)
131 putIState $ ist { idris_classes = cs }
132 _ -> do let cs = addDef n (CI (MN 0 "none") [] [] [] [i]) (idris_classes ist)
133 putIState $ ist { idris_classes = cs }
134 where addI i ins | int = i : ins
135 | chaser n = ins ++ [i]
136 | otherwise = insI i ins
137 insI i [] = [i]
138 insI i (n : ns) | chaser n = i : n : ns
139 | otherwise = n : insI i ns
141 chaser (UN ('@':'@':_)) = True
142 chaser (NS n _) = chaser n
143 chaser _ = False
145addClass :: Name -> ClassInfo -> Idris ()
146addClass n i
147 = do ist <- getIState
148 let i' = case lookupCtxt n (idris_classes ist) of
149 [c] -> c { class_instances = class_instances i }
150 _ -> i
151 putIState $ ist { idris_classes = addDef n i' (idris_classes ist) }
153addIBC :: IBCWrite -> Idris ()
154addIBC ibc@(IBCDef n)
155 = do i <- getIState
156 when (notDef (ibc_write i)) $
157 putIState $ i { ibc_write = ibc : ibc_write i }
158 where notDef [] = True
159 notDef (IBCDef n': is) | n == n' = False
160 notDef (_ : is) = notDef is
161addIBC ibc = do i <- getIState; putIState $ i { ibc_write = ibc : ibc_write i }
163clearIBC :: Idris ()
164clearIBC = do i <- getIState; putIState $ i { ibc_write = [] }
166getHdrs :: Target -> Idris [String]
167getHdrs tgt = do i <- getIState; return (forTarget tgt $ idris_hdrs i)
169setErrLine :: Int -> Idris ()
170setErrLine x = do i <- getIState;
171 case (errLine i) of
172 Nothing -> putIState $ i { errLine = Just x }
173 Just _ -> return ()
175clearErr :: Idris ()
176clearErr = do i <- getIState
177 putIState $ i { errLine = Nothing }
179getSO :: Idris (Maybe String)
180getSO = do i <- getIState
181 return (compiled_so i)
183setSO :: Maybe String -> Idris ()
184setSO s = do i <- getIState
185 putIState $ (i { compiled_so = s })
187getIState :: Idris IState
188getIState = get
190putIState :: IState -> Idris ()
191putIState = put
193getName :: Idris Int
194getName = do i <- getIState;
195 let idx = idris_name i;
196 putIState $ (i { idris_name = idx + 1 })
197 return idx
199checkUndefined :: FC -> Name -> Idris ()
200checkUndefined fc n
201 = do i <- getContext
202 case lookupTy n i of
203 (_:_) -> fail $ show fc ++ ":" ++
204 show n ++ " already defined"
205 _ -> return ()
207isUndefined :: FC -> Name -> Idris Bool
208isUndefined fc n
209 = do i <- getContext
210 case lookupTy n i of
211 (_:_) -> return False
212 _ -> return True
214setContext :: Context -> Idris ()
215setContext ctxt = do i <- getIState; putIState $ (i { tt_ctxt = ctxt } )
217updateContext :: (Context -> Context) -> Idris ()
218updateContext f = do i <- getIState; putIState $ (i { tt_ctxt = f (tt_ctxt i) } )
220addConstraints :: FC -> (Int, [UConstraint]) -> Idris ()
221addConstraints fc (v, cs)
222 = do i <- getIState
223 let ctxt = tt_ctxt i
224 let ctxt' = ctxt { uconstraints = cs ++ uconstraints ctxt,
225 next_tvar = v }
226 let ics = zip cs (repeat fc) ++ idris_constraints i
227 putIState $ i { tt_ctxt = ctxt', idris_constraints = ics }
229addDeferred = addDeferred' Ref
230addDeferredTyCon = addDeferred' (TCon 0 0)
232addDeferred' :: NameType -> [(Name, Type)] -> Idris ()
233addDeferred' nt ns
234 = do mapM_ (\(n, t) -> updateContext (addTyDecl n nt (tidyNames [] t))) ns
235 i <- getIState
236 putIState $ i { idris_metavars = map fst ns ++ idris_metavars i }
237 where tidyNames used (Bind (MN i x) b sc)
238 = let n' = uniqueName (UN x) used in
239 Bind n' b $ tidyNames (n':used) sc
240 tidyNames used (Bind n b sc)
241 = let n' = uniqueName n used in
242 Bind n' b $ tidyNames (n':used) sc
243 tidyNames used b = b
245solveDeferred :: Name -> Idris ()
246solveDeferred n = do i <- getIState
247 putIState $ i { idris_metavars = idris_metavars i \\ [n] }
249iResult :: String -> Idris ()
250iResult s = do i <- getIState
251 case idris_outputmode i of
252 RawOutput -> case s of
253 "" -> return ()
254 s -> liftIO $ putStrLn s
255 IdeSlave n ->
256 let good = SexpList [SymbolAtom "ok", toSExp s] in
257 liftIO $ putStrLn $ convSExp "return" good n
259iFail :: String -> Idris ()
260iFail s = do i <- getIState
261 case idris_outputmode i of
262 RawOutput -> case s of
263 "" -> return ()
264 s -> liftIO $ putStrLn s
265 IdeSlave n ->
266 let good = SexpList [SymbolAtom "error", toSExp s] in
267 liftIO $ putStrLn $ convSExp "return" good n
269iputStrLn :: String -> Idris ()
270iputStrLn s = do i <- getIState
271 case idris_outputmode i of
272 RawOutput -> liftIO $ putStrLn s
273 IdeSlave n ->
274 case span (/=':') s of
275 (fn, ':':rest) -> case span isDigit rest of
276 ([], ':':msg) -> write
277 ([], msg) -> write
278 (num, ':':msg) -> iWarn (FC fn (read num)) msg
279 _ -> write
280 where write = liftIO $ putStrLn $ convSExp "write-string" s n
282iWarn :: FC -> String -> Idris ()
283iWarn fc err = do i <- getIState
284 case idris_outputmode i of
285 RawOutput -> liftIO $ putStrLn (show fc ++ ":" ++ err)
286 IdeSlave n -> liftIO $ putStrLn $ convSExp "warning" (fc_fname fc, fc_line fc, err) n
288setLogLevel :: Int -> Idris ()
289setLogLevel l = do i <- getIState
290 let opts = idris_options i
291 let opt' = opts { opt_logLevel = l }
292 putIState $ i { idris_options = opt' }
294setCmdLine :: [Opt] -> Idris ()
295setCmdLine opts = do i <- getIState
296 let iopts = idris_options i
297 putIState $ i { idris_options = iopts { opt_cmdline = opts } }
299getDumpDefun :: Idris (Maybe FilePath)
300getDumpDefun = do i <- getIState
301 return $ findC (opt_cmdline (idris_options i))
302 where findC [] = Nothing
303 findC (DumpDefun x : _) = Just x
304 findC (_ : xs) = findC xs
306getDumpCases :: Idris (Maybe FilePath)
307getDumpCases = do i <- getIState
308 return $ findC (opt_cmdline (idris_options i))
309 where findC [] = Nothing
310 findC (DumpCases x : _) = Just x
311 findC (_ : xs) = findC xs
313logLevel :: Idris Int
314logLevel = do i <- getIState
315 return (opt_logLevel (idris_options i))
317setErrContext :: Bool -> Idris ()
318setErrContext t = do i <- getIState
319 let opts = idris_options i
320 let opt' = opts { opt_errContext = t }
321 putIState $ i { idris_options = opt' }
323errContext :: Idris Bool
324errContext = do i <- getIState
325 return (opt_errContext (idris_options i))
327useREPL :: Idris Bool
328useREPL = do i <- getIState
329 return (opt_repl (idris_options i))
331setREPL :: Bool -> Idris ()
332setREPL t = do i <- getIState
333 let opts = idris_options i
334 let opt' = opts { opt_repl = t }
335 putIState $ i { idris_options = opt' }
337setQuiet :: Bool -> Idris ()
338setQuiet q = do i <- getIState
339 let opts = idris_options i
340 let opt' = opts { opt_quiet = q }
341 putIState $ i { idris_options = opt' }
343setTarget :: Target -> Idris ()
344setTarget t = do i <- getIState
345 let opts = idris_options i
346 let opt' = opts { opt_target = t }
347 putIState $ i { idris_options = opt' }
349target :: Idris Target
350target = do i <- getIState
351 return (opt_target (idris_options i))
353setOutputTy :: OutputType -> Idris ()
354setOutputTy t = do i <- getIState
355 let opts = idris_options i
356 let opt' = opts { opt_outputTy = t }
357 putIState $ i { idris_options = opt' }
359outputTy :: Idris OutputType
360outputTy = do i <- getIState
361 return $ opt_outputTy $ idris_options i
363setIdeSlave :: Bool -> Idris ()
364setIdeSlave True = do i <- getIState
365 putIState $ i { idris_outputmode = (IdeSlave 0) }
366setIdeSlave False = return ()
368verbose :: Idris Bool
369verbose = do i <- getIState
370 return (opt_verbose (idris_options i))
372setVerbose :: Bool -> Idris ()
373setVerbose t = do i <- getIState
374 let opts = idris_options i
375 let opt' = opts { opt_verbose = t }
376 putIState $ i { idris_options = opt' }
378typeInType :: Idris Bool
379typeInType = do i <- getIState
380 return (opt_typeintype (idris_options i))
382setTypeInType :: Bool -> Idris ()
383setTypeInType t = do i <- getIState
384 let opts = idris_options i
385 let opt' = opts { opt_typeintype = t }
386 putIState $ i { idris_options = opt' }
388coverage :: Idris Bool
389coverage = do i <- getIState
390 return (opt_coverage (idris_options i))
392setCoverage :: Bool -> Idris ()
393setCoverage t = do i <- getIState
394 let opts = idris_options i
395 let opt' = opts { opt_coverage = t }
396 putIState $ i { idris_options = opt' }
398setIBCSubDir :: FilePath -> Idris ()
399setIBCSubDir fp = do i <- getIState
400 let opts = idris_options i
401 let opt' = opts { opt_ibcsubdir = fp }
402 putIState $ i { idris_options = opt' }
404valIBCSubDir :: IState -> Idris FilePath
405valIBCSubDir i = return (opt_ibcsubdir (idris_options i))
407addImportDir :: FilePath -> Idris ()
408addImportDir fp = do i <- getIState
409 let opts = idris_options i
410 let opt' = opts { opt_importdirs = fp : opt_importdirs opts }
411 putIState $ i { idris_options = opt' }
413setImportDirs :: [FilePath] -> Idris ()
414setImportDirs fps = do i <- getIState
415 let opts = idris_options i
416 let opt' = opts { opt_importdirs = fps }
417 putIState $ i { idris_options = opt' }
419allImportDirs :: IState -> Idris [FilePath]
420allImportDirs i = do let optdirs = opt_importdirs (idris_options i)
421 return ("." : reverse optdirs)
423impShow :: Idris Bool
424impShow = do i <- getIState
425 return (opt_showimp (idris_options i))
427setImpShow :: Bool -> Idris ()
428setImpShow t = do i <- getIState
429 let opts = idris_options i
430 let opt' = opts { opt_showimp = t }
431 putIState $ i { idris_options = opt' }
433logLvl :: Int -> String -> Idris ()
434logLvl l str = do i <- getIState
435 let lvl = opt_logLevel (idris_options i)
436 when (lvl >= l)
437 $ do liftIO (putStrLn str)
438 putIState $ i { idris_log = idris_log i ++ str ++ "\n" }
440cmdOptType :: Opt -> Idris Bool
441cmdOptType x = do i <- getIState
442 return $ x `elem` opt_cmdline (idris_options i)
444iLOG :: String -> Idris ()
445iLOG = logLvl 1
447noErrors :: Idris Bool
448noErrors = do i <- getIState
449 case errLine i of
450 Nothing -> return True
451 _ -> return False
453setTypeCase :: Bool -> Idris ()
454setTypeCase t = do i <- getIState
455 let opts = idris_options i
456 let opt' = opts { opt_typecase = t }
457 putIState $ i { idris_options = opt' }
460-- For inferring types of things
462bi = FC "builtin" 0
464inferTy = MN 0 "__Infer"
465inferCon = MN 0 "__infer"
466inferDecl = PDatadecl inferTy
467 PType
468 [("", inferCon, PPi impl (MN 0 "A") PType (
469 PPi expl (MN 0 "a") (PRef bi (MN 0 "A"))
470 (PRef bi inferTy)), bi)]
472infTerm t = PApp bi (PRef bi inferCon) [pimp (MN 0 "A") Placeholder, pexp t]
473infP = P (TCon 6 0) inferTy (TType (UVal 0))
475getInferTerm, getInferType :: Term -> Term
476getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
477getInferTerm (App (App _ _) tm) = tm
478getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
480getInferType (Bind n b sc) = Bind n b $ getInferType sc
481getInferType (App (App _ ty) _) = ty
483-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
485primNames = [unitTy, unitCon,
486 falseTy, pairTy, pairCon,
487 eqTy, eqCon, inferTy, inferCon]
489unitTy = MN 0 "__Unit"
490unitCon = MN 0 "__II"
491unitDecl = PDatadecl unitTy PType
492 [("", unitCon, PRef bi unitTy, bi)]
494falseTy = MN 0 "__False"
495falseDecl = PDatadecl falseTy PType []
497pairTy = MN 0 "__Pair"
498pairCon = MN 0 "__MkPair"
499pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
500 [("", pairCon, PPi impl (n "A") PType (
501 PPi impl (n "B") PType (
502 PPi expl (n "a") (PRef bi (n "A")) (
503 PPi expl (n "b") (PRef bi (n "B"))
504 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
505 pexp (PRef bi (n "B"))])))), bi)]
506 where n a = MN 0 a
508eqTy = UN "="
509eqCon = UN "refl"
510eqDecl = PDatadecl eqTy (piBind [(n "a", PType), (n "b", PType),
511 (n "x", PRef bi (n "a")), (n "y", PRef bi (n "b"))]
512 PType)
513 [("", eqCon, PPi impl (n "a") PType (
514 PPi impl (n "x") (PRef bi (n "a"))
515 (PApp bi (PRef bi eqTy) [pimp (n "a") Placeholder,
516 pimp (n "b") Placeholder,
517 pexp (PRef bi (n "x")),
518 pexp (PRef bi (n "x"))])), bi)]
519 where n a = MN 0 a
521-- Defined in builtins.idr
522sigmaTy = UN "Exists"
523existsCon = UN "Ex_intro"
525piBind :: [(Name, PTerm)] -> PTerm -> PTerm
526piBind = piBindp expl
528piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
529piBindp p [] t = t
530piBindp p ((n, ty):ns) t = PPi p n ty (piBind ns t)
532-- Dealing with parameters
534expandParams :: (Name -> Name) -> [(Name, PTerm)] ->
535 [Name] -> -- all names
536 [Name] -> -- names with no declaration
537 PTerm -> PTerm
538expandParams dec ps ns infs tm = en tm
539 where
540 -- if we shadow a name (say in a lambda binding) that is used in a call to
541 -- a lifted function, we need access to both names - once in the scope of the
542 -- binding and once to call the lifted functions. So we'll explicitly shadow
543 -- it. (Yes, it's a hack. The alternative would be to resolve names earlier
544 -- but we didn't...)
546 mkShadow (UN n) = MN 0 n
547 mkShadow (MN i n) = MN (i+1) n
548 mkShadow (NS x s) = NS (mkShadow x) s
550 en (PLam n t s)
551 | n `elem` map fst ps
552 = let n' = mkShadow n in
553 PLam n' (en t) (en (shadow n n' s))
554 | otherwise = PLam n (en t) (en s)
555 en (PPi p n t s)
556 | n `elem` map fst ps
557 = let n' = mkShadow n in
558 PPi p n' (en t) (en (shadow n n' s))
559 | otherwise = PPi p n (en t) (en s)
560 en (PLet n ty v s)
561 | n `elem` map fst ps
562 = let n' = mkShadow n in
563 PLet n' (en ty) (en v) (en (shadow n n' s))
564 | otherwise = PLet n (en ty) (en v) (en s)
565 en (PEq f l r) = PEq f (en l) (en r)
566 en (PRewrite f l r) = PRewrite f (en l) (en r)
567 en (PTyped l r) = PTyped (en l) (en r)
568 en (PPair f l r) = PPair f (en l) (en r)
569 en (PDPair f l t r) = PDPair f (en l) (en t) (en r)
570 en (PAlternative a as) = PAlternative a (map en as)
571 en (PHidden t) = PHidden (en t)
572 en (PUnifyLog t) = PUnifyLog (en t)
573 en (PDoBlock ds) = PDoBlock (map (fmap en) ds)
574 en (PProof ts) = PProof (map (fmap en) ts)
575 en (PTactics ts) = PTactics (map (fmap en) ts)
577 en (PQuote (Var n))
578 | n `nselem` ns = PQuote (Var (dec n))
579 en (PApp fc (PInferRef fc' n) as)
580 | n `nselem` ns = PApp fc (PInferRef fc' (dec n))
581 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
582 en (PApp fc (PRef fc' n) as)
583 | n `elem` infs = PApp fc (PInferRef fc' (dec n))
584 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
585 | n `nselem` ns = PApp fc (PRef fc' (dec n))
586 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
587 en (PRef fc n)
588 | n `elem` infs = PApp fc (PInferRef fc (dec n))
589 (map (pexp . (PRef fc)) (map fst ps))
590 | n `nselem` ns = PApp fc (PRef fc (dec n))
591 (map (pexp . (PRef fc)) (map fst ps))
592 en (PInferRef fc n)
593 | n `nselem` ns = PApp fc (PInferRef fc (dec n))
594 (map (pexp . (PRef fc)) (map fst ps))
595 en (PApp fc f as) = PApp fc (en f) (map (fmap en) as)
596 en (PCase fc c os) = PCase fc (en c) (map (pmap en) os)
597 en t = t
599 nselem x [] = False
600 nselem x (y : xs) | nseq x y = True
601 | otherwise = nselem x xs
603 nseq x y = nsroot x == nsroot y
605expandParamsD :: Bool -> -- True = RHS only
606 IState ->
607 (Name -> Name) -> [(Name, PTerm)] -> [Name] -> PDecl -> PDecl
608expandParamsD rhsonly ist dec ps ns (PTy doc syn fc o n ty)
609 = if n `elem` ns && (not rhsonly)
610 then -- trace (show (n, expandParams dec ps ns ty)) $
611 PTy doc syn fc o (dec n) (piBind ps (expandParams dec ps ns [] ty))
612 else --trace (show (n, expandParams dec ps ns ty)) $
613 PTy doc syn fc o n (expandParams dec ps ns [] ty)
614expandParamsD rhsonly ist dec ps ns (PPostulate doc syn fc o n ty)
615 = if n `elem` ns && (not rhsonly)
616 then -- trace (show (n, expandParams dec ps ns ty)) $
617 PPostulate doc syn fc o (dec n) (piBind ps
618 (expandParams dec ps ns [] ty))
619 else --trace (show (n, expandParams dec ps ns ty)) $
620 PPostulate doc syn fc o n (expandParams dec ps ns [] ty)
621expandParamsD rhsonly ist dec ps ns (PClauses fc opts n cs)
622 = let n' = if n `elem` ns then dec n else n in
623 PClauses fc opts n' (map expandParamsC cs)
624 where
625 expandParamsC (PClause fc n lhs ws rhs ds)
626 = let -- ps' = updateps True (namesIn ist rhs) (zip ps [0..])
627 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
628 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
629 n' = if n `elem` ns then dec n else n in
630 PClause fc n' lhs'
631 (map (expandParams dec ps'' ns []) ws)
632 (expandParams dec ps'' ns [] rhs)
633 (map (expandParamsD True ist dec ps'' ns) ds)
634 expandParamsC (PWith fc n lhs ws wval ds)
635 = let -- ps' = updateps True (namesIn ist wval) (zip ps [0..])
636 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
637 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
638 n' = if n `elem` ns then dec n else n in
639 PWith fc n' lhs'
640 (map (expandParams dec ps'' ns []) ws)
641 (expandParams dec ps'' ns [] wval)
642 (map (expandParamsD rhsonly ist dec ps'' ns) ds)
643 updateps yn nm [] = []
644 updateps yn nm (((a, t), i):as)
645 | (a `elem` nm) == yn = (a, t) : updateps yn nm as
646 | otherwise = (MN i (show n ++ "_u"), t) : updateps yn nm as
647expandParamsD rhs ist dec ps ns (PData doc syn fc co pd)
648 = PData doc syn fc co (expandPData pd)
649 where
650 -- just do the type decl, leave constructors alone (parameters will be
651 -- added implicitly)
652 expandPData (PDatadecl n ty cons)
653 = if n `elem` ns
654 then PDatadecl (dec n) (piBind ps (expandParams dec ps ns [] ty))
655 (map econ cons)
656 else PDatadecl n (expandParams dec ps ns [] ty) (map econ cons)
657 econ (doc, n, t, fc)
658 = (doc, dec n, piBindp expl ps (expandParams dec ps ns [] t), fc)
659expandParamsD rhs ist dec ps ns (PParams f params pds)
660 = PParams f (ps ++ map (mapsnd (expandParams dec ps ns [])) params)
661 (map (expandParamsD True ist dec ps ns) pds)
662-- (map (expandParamsD ist dec ps ns) pds)
663expandParamsD rhs ist dec ps ns (PMutual f pds)
664 = PMutual f (map (expandParamsD rhs ist dec ps ns) pds)
665expandParamsD rhs ist dec ps ns (PClass doc info f cs n params decls)
666 = PClass doc info f
667 (map (expandParams dec ps ns []) cs)
668 n
669 (map (mapsnd (expandParams dec ps ns [])) params)
670 (map (expandParamsD rhs ist dec ps ns) decls)
671expandParamsD rhs ist dec ps ns (PInstance info f cs n params ty cn decls)
672 = PInstance info f
673 (map (expandParams dec ps ns []) cs)
674 n
675 (map (expandParams dec ps ns []) params)
676 (expandParams dec ps ns [] ty)
677 cn
678 (map (expandParamsD rhs ist dec ps ns) decls)
679expandParamsD rhs ist dec ps ns d = d
681mapsnd f (x, t) = (x, f t)
683-- Calculate a priority for a type, for deciding elaboration order
684-- * if it's just a type variable or concrete type, do it early (0)
685-- * if there's only type variables and injective constructors, do it next (1)
686-- * if there's a function type, next (2)
687-- * finally, everything else (3)
689getPriority :: IState -> PTerm -> Int
690getPriority i tm = 1 -- pri tm
691 where
692 pri (PRef _ n) =
693 case lookupP n (tt_ctxt i) of
694 ((P (DCon _ _) _ _):_) -> 1
695 ((P (TCon _ _) _ _):_) -> 1
696 ((P Ref _ _):_) -> 1
697 [] -> 0 -- must be locally bound, if it's not an error...
698 pri (PPi _ _ x y) = max 5 (max (pri x) (pri y))
699 pri (PTrue _) = 0
700 pri (PFalse _) = 0
701 pri (PRefl _ _) = 1
702 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
703 pri (PRewrite _ l r) = max 1 (max (pri l) (pri r))
704 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
705 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
706 pri (PTyped l r) = pri l
707 pri (PPair _ l r) = max 1 (max (pri l) (pri r))
708 pri (PDPair _ l t r) = max 1 (max (pri l) (max (pri t) (pri r)))
709 pri (PAlternative a as) = maximum (map pri as)
710 pri (PConstant _) = 0
711 pri Placeholder = 1
712 pri _ = 3
714addStatics :: Name -> Term -> PTerm -> Idris ()
715addStatics n tm ptm =
716 do let (statics, dynamics) = initStatics tm ptm
717 let stnames = nub $ concatMap freeNames (map snd statics)
718 let dnames = nub $ concatMap freeNames (map snd dynamics)
719 when (not (null statics)) $
720 logLvl 7 $ show n ++ " " ++ show statics ++ "\n" ++ show dynamics
721 ++ "\n" ++ show stnames ++ "\n" ++ show dnames
722 let statics' = nub $ map fst statics ++
723 filter (\x -> not (elem x dnames)) stnames
724 let stpos = staticList statics' tm
725 i <- getIState
726 putIState $ i { idris_statics = addDef n stpos (idris_statics i) }
727 addIBC (IBCStatic n)
728 where
729 initStatics (Bind n (Pi ty) sc) (PPi p _ _ s)
730 = let (static, dynamic) = initStatics (instantiate (P Bound n ty) sc) s in
731 if pstatic p == Static then ((n, ty) : static, dynamic)
732 else (static, (n, ty) : dynamic)
733 initStatics t pt = ([], [])
735 staticList sts (Bind n (Pi _) sc) = (n `elem` sts) : staticList sts sc
736 staticList _ _ = []
738-- Dealing with implicit arguments
740-- Add constraint bindings from using block
742addUsingConstraints :: SyntaxInfo -> FC -> PTerm -> Idris PTerm
743addUsingConstraints syn fc t
744 = do ist <- get
745 let ns = namesIn [] ist t
746 let cs = getConstraints t -- check declared constraints
747 let addconsts = uconsts \\ cs
748 -- if all names in the arguments of addconsts appear in ns,
749 -- add the constraint implicitly
750 return (doAdd addconsts ns t)
751 where uconsts = filter uconst (using syn)
752 uconst (UConstraint _ _) = True
753 uconst _ = False
755 doAdd [] _ t = t
756 -- if all of args in ns, then add it
757 doAdd (UConstraint c args : cs) ns t
758 | all (\n -> elem n ns) args
759 = PPi (Constraint False Dynamic "") (MN 0 "cu")
760 (mkConst c args) (doAdd cs ns t)
761 | otherwise = doAdd cs ns t
763 mkConst c args = PApp fc (PRef fc c)
764 (map (\n -> PExp 0 False (PRef fc n) "") args)
766 getConstraints (PPi (Constraint _ _ _) _ c sc)
767 = getcapp c ++ getConstraints sc
768 getConstraints (PPi _ _ c sc) = getConstraints sc
769 getConstraints _ = []
771 getcapp (PApp _ (PRef _ c) args)
772 = do ns <- mapM getName args
773 return (UConstraint c ns)
774 getcapp _ = []
776 getName (PExp _ _ (PRef _ n) _) = return n
777 getName _ = []
779-- Add implicit Pi bindings for any names in the term which appear in an
780-- argument position.
782-- This has become a right mess already. Better redo it some time...
784implicit :: SyntaxInfo -> Name -> PTerm -> Idris PTerm
785implicit syn n ptm = implicit' syn [] n ptm
787implicit' :: SyntaxInfo -> [Name] -> Name -> PTerm -> Idris PTerm
788implicit' syn ignore n ptm
789 = do i <- getIState
790 let (tm', impdata) = implicitise syn ignore i ptm
791-- let (tm'', spos) = findStatics i tm'
792 putIState $ i { idris_implicits = addDef n impdata (idris_implicits i) }
793 addIBC (IBCImp n)
794 logLvl 5 ("Implicit " ++ show n ++ " " ++ show impdata)
795-- i <- get
796-- putIState $ i { idris_statics = addDef n spos (idris_statics i) }
797 return tm'
799implicitise :: SyntaxInfo -> [Name] -> IState -> PTerm -> (PTerm, [PArg])
800implicitise syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
801 let (declimps, ns') = execState (imps True [] tm) ([], [])
802 ns = filter (\n -> implicitable n || elem n (map fst uvars)) $
803 ns' \\ (map fst pvars ++ no_imp syn ++ ignore)
804 nsOrder = filter (not . inUsing) ns ++ filter inUsing ns in
805 if null ns
806 then (tm, reverse declimps)
807 else implicitise syn ignore ist (pibind uvars nsOrder tm)
808 where
809 uvars = map ipair (filter uimplicit (using syn))
810 pvars = syn_params syn
812 inUsing n = n `elem` map fst uvars
814 ipair (UImplicit x y) = (x, y)
815 uimplicit (UImplicit _ _) = True
816 uimplicit _ = False
818 dropAll (x:xs) ys | x `elem` ys = dropAll xs ys
819 | otherwise = x : dropAll xs ys
820 dropAll [] ys = []
822 imps top env (PApp _ f as)
823 = do (decls, ns) <- get
824 let isn = concatMap (namesIn uvars ist) (map getTm as)
825 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
826 imps top env (PPi (Imp l _ doc) n ty sc)
827 = do let isn = nub (namesIn uvars ist ty) `dropAll` [n]
828 (decls , ns) <- get
829 put (PImp (getPriority ist ty) l n ty doc : decls,
830 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
831 imps True (n:env) sc
832 imps top env (PPi (Exp l _ doc) n ty sc)
833 = do let isn = nub (namesIn uvars ist ty ++ case sc of
834 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
835 _ -> [])
836 (decls, ns) <- get -- ignore decls in HO types
837 put (PExp (getPriority ist ty) l ty doc : decls,
838 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
839 imps True (n:env) sc
840 imps top env (PPi (Constraint l _ doc) n ty sc)
841 = do let isn = nub (namesIn uvars ist ty ++ case sc of
842 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
843 _ -> [])
844 (decls, ns) <- get -- ignore decls in HO types
845 put (PConstraint 10 l ty doc : decls,
846 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
847 imps True (n:env) sc
848 imps top env (PPi (TacImp l _ scr doc) n ty sc)
849 = do let isn = nub (namesIn uvars ist ty ++ case sc of
850 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
851 _ -> [])
852 (decls, ns) <- get -- ignore decls in HO types
853 put (PTacImplicit 10 l n scr ty doc : decls,
854 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
855 imps True (n:env) sc
856 imps top env (PEq _ l r)
857 = do (decls, ns) <- get
858 let isn = namesIn uvars ist l ++ namesIn uvars ist r
859 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
860 imps top env (PRewrite _ l r)
861 = do (decls, ns) <- get
862 let isn = namesIn uvars ist l ++ namesIn uvars ist r
863 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
864 imps top env (PTyped l r)
865 = imps top env l
866 imps top env (PPair _ l r)
867 = do (decls, ns) <- get
868 let isn = namesIn uvars ist l ++ namesIn uvars ist r
869 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
870 imps top env (PDPair _ (PRef _ n) t r)
871 = do (decls, ns) <- get
872 let isn = nub (namesIn uvars ist t ++ namesIn uvars ist r) \\ [n]
873 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
874 imps top env (PDPair _ l t r)
875 = do (decls, ns) <- get
876 let isn = namesIn uvars ist l ++ namesIn uvars ist t ++
877 namesIn uvars ist r
878 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
879 imps top env (PAlternative a as)
880 = do (decls, ns) <- get
881 let isn = concatMap (namesIn uvars ist) as
882 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
883 imps top env (PLam n ty sc)
884 = do imps False env ty
885 imps False (n:env) sc
886 imps top env (PHidden tm) = imps False env tm
887 imps top env (PUnifyLog tm) = imps False env tm
888 imps top env _ = return ()
890 pibind using [] sc = sc
891 pibind using (n:ns) sc
892 = case lookup n using of
893 Just ty -> PPi (Imp False Dynamic "") n ty (pibind using ns sc)
894 Nothing -> PPi (Imp False Dynamic "") n Placeholder
895 (pibind using ns sc)
897-- Add implicit arguments in function calls
898addImplPat :: IState -> PTerm -> PTerm
899addImplPat = addImpl' True [] []
901addImplBound :: IState -> [Name] -> PTerm -> PTerm
902addImplBound ist ns = addImpl' False ns [] ist
904addImplBoundInf :: IState -> [Name] -> [Name] -> PTerm -> PTerm
905addImplBoundInf ist ns inf = addImpl' False ns inf ist
907addImpl :: IState -> PTerm -> PTerm
908addImpl = addImpl' False [] []
910-- TODO: in patterns, don't add implicits to function names guarded by constructors
911-- and *not* inside a PHidden
913addImpl' :: Bool -> [Name] -> [Name] -> IState -> PTerm -> PTerm
914addImpl' inpat env infns ist ptm = ai (zip env (repeat Nothing)) ptm
915 where
916 ai env (PRef fc f)
917 | f `elem` infns = PInferRef fc f
918 | not (f `elem` map fst env) = handleErr $ aiFn inpat inpat ist fc f []
919 ai env (PHidden (PRef fc f))
920 | not (f `elem` map fst env) = handleErr $ aiFn inpat False ist fc f []
921 ai env (PEq fc l r) = let l' = ai env l
922 r' = ai env r in
923 PEq fc l' r'
924 ai env (PRewrite fc l r) = let l' = ai env l
925 r' = ai env r in
926 PRewrite fc l' r'
927 ai env (PTyped l r) = let l' = ai env l
928 r' = ai env r in
929 PTyped l' r'
930 ai env (PPair fc l r) = let l' = ai env l
931 r' = ai env r in
932 PPair fc l' r'
933 ai env (PDPair fc l t r) = let l' = ai env l
934 t' = ai env t
935 r' = ai env r in
936 PDPair fc l' t' r'
937 ai env (PAlternative a as) = let as' = map (ai env) as in
938 PAlternative a as'
939 ai env (PApp fc (PInferRef _ f) as)
940 = let as' = map (fmap (ai env)) as in
941 PApp fc (PInferRef fc f) as'
942 ai env (PApp fc ftm@(PRef _ f) as)
943 | f `elem` infns = ai env (PApp fc (PInferRef fc f) as)
944 | not (f `elem` map fst env)
945 = let as' = map (fmap (ai env)) as in
946 handleErr $ aiFn inpat False ist fc f as'
947 | Just (Just ty) <- lookup f env
948 = let as' = map (fmap (ai env)) as
949 arity = getPArity ty in
950 mkPApp fc arity ftm as'
951 ai env (PApp fc f as) = let f' = ai env f
952 as' = map (fmap (ai env)) as in
953 mkPApp fc 1 f' as'
954 ai env (PCase fc c os) = let c' = ai env c
955 os' = map (pmap (ai env)) os in
956 PCase fc c' os'
957 ai env (PLam n ty sc) = let ty' = ai env ty
958 sc' = ai ((n, Just ty):env) sc in
959 PLam n ty' sc'
960 ai env (PLet n ty val sc)
961 = let ty' = ai env ty
962 val' = ai env val
963 sc' = ai ((n, Just ty):env) sc in
964 PLet n ty' val' sc'
965 ai env (PPi p n ty sc) = let ty' = ai env ty
966 sc' = ai ((n, Just ty):env) sc in
967 PPi p n ty' sc'
968 ai env (PHidden tm) = PHidden (ai env tm)
969 ai env (PProof ts) = PProof (map (fmap (ai env)) ts)
970 ai env (PTactics ts) = PTactics (map (fmap (ai env)) ts)
971 ai env (PUnifyLog tm) = PUnifyLog (ai env tm)
972 ai env tm = tm
974 handleErr (Left err) = PElabError err
975 handleErr (Right x) = x
977-- if in a pattern, and there are no arguments, and there's no possible
978-- names with zero explicit arguments, don't add implicits.
980aiFn :: Bool -> Bool -> IState -> FC -> Name -> [PArg] -> Either Err PTerm
981aiFn inpat True ist fc f []
982 = case lookupDef f (tt_ctxt ist) of
983 [] -> Right $ PPatvar fc f
984 alts -> let ialts = lookupCtxt f (idris_implicits ist) in
985 -- trace (show f ++ " " ++ show (fc, any (all imp) ialts, ialts, any constructor alts)) $
986 if (not (vname f) || tcname f
987 || any constructor alts || any allImp ialts)
988 then aiFn inpat False ist fc f [] -- use it as a constructor
989 else Right $ PPatvar fc f
990 where imp (PExp _ _ _ _) = False
991 imp _ = True
992 allImp [] = False
993 allImp xs = all imp xs
994 constructor (TyDecl (DCon _ _) _) = True
995 constructor _ = False
997 vname (UN n) = True -- non qualified
998 vname _ = False
1000aiFn inpat expat ist fc f as
1001 | f `elem` primNames = Right $ PApp fc (PRef fc f) as
1002aiFn inpat expat ist fc f as
1003 -- This is where namespaces get resolved by adding PAlternative
1004 = case lookupCtxtName f (idris_implicits ist) of
1005 [(f',ns)] -> Right $ mkPApp fc (length ns) (PRef fc f') (insertImpl ns as)
1006 [] -> if f `elem` idris_metavars ist
1007 then Right $ PApp fc (PRef fc f) as
1008 else Right $ mkPApp fc (length as) (PRef fc f) as
1009 alts -> Right $
1010 PAlternative True $
1011 map (\(f', ns) -> mkPApp fc (length ns) (PRef fc f')
1012 (insertImpl ns as)) alts
1013 where
1014 insertImpl :: [PArg] -> [PArg] -> [PArg]
1015 insertImpl (PExp p l ty _ : ps) (PExp _ _ tm d : given) =
1016 PExp p l tm d : insertImpl ps given
1017 insertImpl (PConstraint p l ty _ : ps) (PConstraint _ _ tm d : given) =
1018 PConstraint p l tm d : insertImpl ps given
1019 insertImpl (PConstraint p l ty d : ps) given =
1020 PConstraint p l (PResolveTC fc) d : insertImpl ps given
1021 insertImpl (PImp p l n ty d : ps) given =
1022 case find n given [] of
1023 Just (tm, given') -> PImp p l n tm "" : insertImpl ps given'
1024 Nothing -> PImp p l n Placeholder "" : insertImpl ps given
1025 insertImpl (PTacImplicit p l n sc ty d : ps) given =
1026 case find n given [] of
1027 Just (tm, given') -> PTacImplicit p l n sc tm "" : insertImpl ps given'
1028 Nothing -> if inpat
1029 then PTacImplicit p l n sc Placeholder "" : insertImpl ps given
1030 else PTacImplicit p l n sc sc "" : insertImpl ps given
1031 insertImpl expected [] = []
1032 insertImpl _ given = given
1034 find n [] acc = Nothing
1035 find n (PImp _ _ n' t _ : gs) acc
1036 | n == n' = Just (t, reverse acc ++ gs)
1037 find n (PTacImplicit _ _ n' _ t _ : gs) acc
1038 | n == n' = Just (t, reverse acc ++ gs)
1039 find n (g : gs) acc = find n gs (g : acc)
1041-- replace non-linear occurrences with _
1042-- ASSUMPTION: This is called before adding 'alternatives' because otherwise
1043-- it is hard to get right!
1045stripLinear :: IState -> PTerm -> PTerm
1046stripLinear i tm = evalState (sl tm) [] where
1047 sl :: PTerm -> State [Name] PTerm
1048 sl (PRef fc f)
1049 | (_:_) <- lookupTy f (tt_ctxt i)
1050 = return $ PRef fc f
1051 | otherwise = do ns <- get
1052 if (f `elem` ns)
1053 then return Placeholder
1054 else do put (f : ns)
1055 return (PRef fc f)
1056 sl (PPatvar fc f)
1057 = do ns <- get
1058 if (f `elem` ns)
1059 then return Placeholder
1060 else do put (f : ns)
1061 return (PPatvar fc f)
1062 sl (PApp fc fn args) = do fn' <- sl fn
1063 args' <- mapM slA args
1064 return $ PApp fc fn' args'
1065 where slA (PImp p l n t d) = do t' <- sl t
1066 return $ PImp p l n t' d
1067 slA (PExp p l t d) = do t' <- sl t
1068 return $ PExp p l t' d
1069 slA (PConstraint p l t d)
1070 = do t' <- sl t
1071 return $ PConstraint p l t' d
1072 slA (PTacImplicit p l n sc t d)
1073 = do t' <- sl t
1074 return $ PTacImplicit p l n sc t' d
1075 sl x = return x
1077mkPApp fc a f [] = f
1078mkPApp fc a f as = let rest = drop a as in
1079 appRest fc (PApp fc f (take a as)) rest
1080 where
1081 appRest fc f [] = f
1082 appRest fc f (a : as) = appRest fc (PApp fc f [a]) as
1084-- Find 'static' argument positions
1085-- (the declared ones, plus any names in argument position in the declared
1086-- statics)
1087-- FIXME: It's possible that this really has to happen after elaboration
1089findStatics :: IState -> PTerm -> (PTerm, [Bool])
1090findStatics ist tm = trace (showImp True tm) $
1091 let (ns, ss) = fs tm in
1092 runState (pos ns ss tm) []
1093 where fs (PPi p n t sc)
1094 | Static <- pstatic p
1095 = let (ns, ss) = fs sc in
1096 (namesIn [] ist t : ns, n : ss)
1097 | otherwise = let (ns, ss) = fs sc in
1098 (ns, ss)
1099 fs _ = ([], [])
1101 inOne n ns = length (filter id (map (elem n) ns)) == 1
1103 pos ns ss (PPi p n t sc)
1104 | elem n ss = do sc' <- pos ns ss sc
1105 spos <- get
1106 put (True : spos)
1107 return (PPi (p { pstatic = Static }) n t sc')
1108 | otherwise = do sc' <- pos ns ss sc
1109 spos <- get
1110 put (False : spos)
1111 return (PPi p n t sc')
1112 pos ns ss t = return t
1114-- Debugging/logging stuff
1116dumpDecls :: [PDecl] -> String
1117dumpDecls [] = ""
1118dumpDecls (d:ds) = dumpDecl d ++ "\n" ++ dumpDecls ds
1120dumpDecl (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
1121dumpDecl (PTy _ _ _ _ n t) = "tydecl " ++ show n ++ " : " ++ showImp True t
1122dumpDecl (PClauses _ _ n cs) = "pat " ++ show n ++ "\t" ++ showSep "\n\t" (map (showCImp True) cs)
1123dumpDecl (PData _ _ _ _ d) = showDImp True d
1124dumpDecl (PParams _ ns ps) = "params {" ++ show ns ++ "\n" ++ dumpDecls ps ++ "}\n"
1125dumpDecl (PNamespace n ps) = "namespace {" ++ n ++ "\n" ++ dumpDecls ps ++ "}\n"
1126dumpDecl (PSyntax _ syn) = "syntax " ++ show syn
1127dumpDecl (PClass _ _ _ cs n ps ds)
1128 = "class " ++ show cs ++ " " ++ show n ++ " " ++ show ps ++ "\n" ++ dumpDecls ds
1129dumpDecl (PInstance _ _ cs n _ t _ ds)
1130 = "instance " ++ show cs ++ " " ++ show n ++ " " ++ show t ++ "\n" ++ dumpDecls ds
1131dumpDecl _ = "..."
1132-- dumpDecl (PImport i) = "import " ++ i
1134-- for 6.12/7 compatibility
1135data EitherErr a b = LeftErr a | RightOK b
1137instance Monad (EitherErr a) where
1138 return = RightOK
1140 (LeftErr e) >>= k = LeftErr e
1141 RightOK v >>= k = k v
1143toEither (LeftErr e) = Left e
1144toEither (RightOK ho) = Right ho
1146-- syntactic match of a against b, returning pair of variables in a
1147-- and what they match. Returns the pair that failed if not a match.
1149matchClause :: IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1150matchClause = matchClause' False
1152matchClause' :: Bool -> IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1153matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
1154 matchArg x y = match (fullApp (getTm x)) (fullApp (getTm y))
1156 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1157 fullApp x = x
1159 match' x y = match (fullApp x) (fullApp y)
1160 match (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x]) x'
1161 | PConstant (I _) <- getTm x = match (getTm x) x'
1162 match x' (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x])
1163 | PConstant (I _) <- getTm x = match (getTm x) x'
1164 match (PApp _ (PRef _ (UN "lazy")) [_,x]) x' = match (getTm x) x'
1165 match x (PApp _ (PRef _ (UN "lazy")) [_,x']) = match x (getTm x')
1166 match (PApp _ f args) (PApp _ f' args')
1167 | length args == length args'
1168 = do mf <- match' f f'
1169 ms <- zipWithM matchArg args args'
1170 return (mf ++ concat ms)
1171-- match (PRef _ n) (PRef _ n') | n == n' = return []
1172-- | otherwise = Nothing
1173 match (PRef f n) (PApp _ x []) = match (PRef f n) x
1174 match (PPatvar f n) xr = match (PRef f n) xr
1175 match xr (PPatvar f n) = match xr (PRef f n)
1176 match (PApp _ x []) (PRef f n) = match x (PRef f n)
1177 match (PRef _ n) tm@(PRef _ n')
1178 | n == n' && not names &&
1179 (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1180 = return [(n, tm)]
1181 | n == n' = return []
1182 match (PRef _ n) tm
1183 | not names && (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1184 = return [(n, tm)]
1185 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
1186 mr <- match' r r'
1187 return (ml ++ mr)
1188 match (PRewrite _ l r) (PRewrite _ l' r')
1189 = do ml <- match' l l'
1190 mr <- match' r r'
1191 return (ml ++ mr)
1192 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
1193 mr <- match r r'
1194 return (ml ++ mr)
1195 match (PTyped l r) x = match l x
1196 match x (PTyped l r) = match x l
1197 match (PPair _ l r) (PPair _ l' r') = do ml <- match' l l'
1198 mr <- match' r r'
1199 return (ml ++ mr)
1200 match (PDPair _ l t r) (PDPair _ l' t' r') = do ml <- match' l l'
1201 mt <- match' t t'
1202 mr <- match' r r'
1203 return (ml ++ mt ++ mr)
1204 match (PAlternative a as) (PAlternative a' as')
1205 = do ms <- zipWithM match' as as'
1206 return (concat ms)
1207 match a@(PAlternative _ as) b
1208 = do let ms = zipWith match' as (repeat b)
1209 case (rights (map toEither ms)) of
1210 (x: _) -> return x
1211 _ -> LeftErr (a, b)
1212 match (PCase _ _ _) _ = return [] -- lifted out
1213 match (PMetavar _) _ = return [] -- modified
1214 match (PInferRef _ _) _ = return [] -- modified
1215 match (PQuote _) _ = return []
1216 match (PProof _) _ = return []
1217 match (PTactics _) _ = return []
1218 match (PRefl _ _) (PRefl _ _) = return []
1219 match (PResolveTC _) (PResolveTC _) = return []
1220 match (PTrue _) (PTrue _) = return []
1221 match (PFalse _) (PFalse _) = return []
1222 match (PReturn _) (PReturn _) = return []
1223 match (PPi _ _ t s) (PPi _ _ t' s') = do mt <- match' t t'
1224 ms <- match' s s'
1225 return (mt ++ ms)
1226 match (PLam _ t s) (PLam _ t' s') = do mt <- match' t t'
1227 ms <- match' s s'
1228 return (mt ++ ms)
1229 match (PLet _ t ty s) (PLet _ t' ty' s') = do mt <- match' t t'
1230 mty <- match' ty ty'
1231 ms <- match' s s'
1232 return (mt ++ mty ++ ms)
1233 match (PHidden x) (PHidden y) = match' x y
1234 match (PUnifyLog x) y = match' x y
1235 match x (PUnifyLog y) = match' x y
1236 match Placeholder _ = return []
1237 match _ Placeholder = return []
1238 match (PResolveTC _) _ = return []
1239 match a b | a == b = return []
1240 | otherwise = LeftErr (a, b)
1242 checkRpts (RightOK ms) = check ms where
1243 check ((n,t):xs)
1244 | Just t' <- lookup n xs = if t/=t' && t/=Placeholder && t'/=Placeholder
1245 then Left (t, t')
1246 else check xs
1247 check (_:xs) = check xs
1248 check [] = Right ms
1249 checkRpts (LeftErr x) = Left x
1251substMatches :: [(Name, PTerm)] -> PTerm -> PTerm
1252substMatches ms = substMatchesShadow ms []
1254substMatchesShadow :: [(Name, PTerm)] -> [Name] -> PTerm -> PTerm
1255substMatchesShadow [] shs t = t
1256substMatchesShadow ((n,tm):ns) shs t
1257 = substMatchShadow n shs tm (substMatchesShadow ns shs t)
1259substMatch :: Name -> PTerm -> PTerm -> PTerm
1260substMatch n = substMatchShadow n []
1262substMatchShadow :: Name -> [Name] -> PTerm -> PTerm -> PTerm
1263substMatchShadow n shs tm t = sm shs t where
1264 sm xs (PRef _ n') | n == n' = tm
1265 sm xs (PLam x t sc) = PLam x (sm xs t) (sm xs sc)
1266 sm xs (PPi p x t sc)
1267 | x `elem` xs
1268 = let x' = nextName x in
1269 PPi p x' (sm (x':xs) (substMatch x (PRef (FC "" 0) x') t))
1270 (sm (x':xs) (substMatch x (PRef (FC "" 0) x') sc))
1271 | otherwise = PPi p x (sm xs t) (sm (x : xs) sc)
1272 sm xs (PApp f x as) = PApp f (sm xs x) (map (fmap (sm xs)) as)
1273 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
1274 sm xs (PEq f x y) = PEq f (sm xs x) (sm xs y)
1275 sm xs (PRewrite f x y) = PRewrite f (sm xs x) (sm xs y)
1276 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
1277 sm xs (PPair f x y) = PPair f (sm xs x) (sm xs y)
1278 sm xs (PDPair f x t y) = PDPair f (sm xs x) (sm xs t) (sm xs y)
1279 sm xs (PAlternative a as) = PAlternative a (map (sm xs) as)
1280 sm xs (PHidden x) = PHidden (sm xs x)
1281 sm xs (PUnifyLog x) = PUnifyLog (sm xs x)
1282 sm xs x = x
1284shadow :: Name -> Name -> PTerm -> PTerm
1285shadow n n' t = sm t where
1286 sm (PRef fc x) | n == x = PRef fc n'
1287 sm (PLam x t sc) = PLam x (sm t) (sm sc)
1288 sm (PPi p x t sc) = PPi p x (sm t) (sm sc)
1289 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
1290 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
1291 sm (PEq f x y) = PEq f (sm x) (sm y)
1292 sm (PRewrite f x y) = PRewrite f (sm x) (sm y)
1293 sm (PTyped x y) = PTyped (sm x) (sm y)
1294 sm (PPair f x y) = PPair f (sm x) (sm y)
1295 sm (PDPair f x t y) = PDPair f (sm x) (sm t) (sm y)
1296 sm (PAlternative a as) = PAlternative a (map sm as)
1297 sm (PHidden x) = PHidden (sm x)
1298 sm (PUnifyLog x) = PUnifyLog (sm x)
1299 sm x = x