on e8ae2f4 help sign in
Idris-dev/src/Idris/AbsSyntax.hs
1306 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' }
343getQuiet :: Idris Bool
344getQuiet = do i <- getIState
345 let opts = idris_options i
346 return (opt_quiet opts)
348setTarget :: Target -> Idris ()
349setTarget t = do i <- getIState
350 let opts = idris_options i
351 let opt' = opts { opt_target = t }
352 putIState $ i { idris_options = opt' }
354target :: Idris Target
355target = do i <- getIState
356 return (opt_target (idris_options i))
358setOutputTy :: OutputType -> Idris ()
359setOutputTy t = do i <- getIState
360 let opts = idris_options i
361 let opt' = opts { opt_outputTy = t }
362 putIState $ i { idris_options = opt' }
364outputTy :: Idris OutputType
365outputTy = do i <- getIState
366 return $ opt_outputTy $ idris_options i
368setIdeSlave :: Bool -> Idris ()
369setIdeSlave True = do i <- getIState
370 putIState $ i { idris_outputmode = (IdeSlave 0) }
371setIdeSlave False = return ()
373verbose :: Idris Bool
374verbose = do i <- getIState
375 return (opt_verbose (idris_options i))
377setVerbose :: Bool -> Idris ()
378setVerbose t = do i <- getIState
379 let opts = idris_options i
380 let opt' = opts { opt_verbose = t }
381 putIState $ i { idris_options = opt' }
383typeInType :: Idris Bool
384typeInType = do i <- getIState
385 return (opt_typeintype (idris_options i))
387setTypeInType :: Bool -> Idris ()
388setTypeInType t = do i <- getIState
389 let opts = idris_options i
390 let opt' = opts { opt_typeintype = t }
391 putIState $ i { idris_options = opt' }
393coverage :: Idris Bool
394coverage = do i <- getIState
395 return (opt_coverage (idris_options i))
397setCoverage :: Bool -> Idris ()
398setCoverage t = do i <- getIState
399 let opts = idris_options i
400 let opt' = opts { opt_coverage = t }
401 putIState $ i { idris_options = opt' }
403setIBCSubDir :: FilePath -> Idris ()
404setIBCSubDir fp = do i <- getIState
405 let opts = idris_options i
406 let opt' = opts { opt_ibcsubdir = fp }
407 putIState $ i { idris_options = opt' }
409valIBCSubDir :: IState -> Idris FilePath
410valIBCSubDir i = return (opt_ibcsubdir (idris_options i))
412addImportDir :: FilePath -> Idris ()
413addImportDir fp = do i <- getIState
414 let opts = idris_options i
415 let opt' = opts { opt_importdirs = fp : opt_importdirs opts }
416 putIState $ i { idris_options = opt' }
418setImportDirs :: [FilePath] -> Idris ()
419setImportDirs fps = do i <- getIState
420 let opts = idris_options i
421 let opt' = opts { opt_importdirs = fps }
422 putIState $ i { idris_options = opt' }
424allImportDirs :: IState -> Idris [FilePath]
425allImportDirs i = do let optdirs = opt_importdirs (idris_options i)
426 return ("." : reverse optdirs)
428impShow :: Idris Bool
429impShow = do i <- getIState
430 return (opt_showimp (idris_options i))
432setImpShow :: Bool -> Idris ()
433setImpShow t = do i <- getIState
434 let opts = idris_options i
435 let opt' = opts { opt_showimp = t }
436 putIState $ i { idris_options = opt' }
438logLvl :: Int -> String -> Idris ()
439logLvl l str = do i <- getIState
440 let lvl = opt_logLevel (idris_options i)
441 when (lvl >= l)
442 $ do liftIO (putStrLn str)
443 putIState $ i { idris_log = idris_log i ++ str ++ "\n" }
445cmdOptType :: Opt -> Idris Bool
446cmdOptType x = do i <- getIState
447 return $ x `elem` opt_cmdline (idris_options i)
449iLOG :: String -> Idris ()
450iLOG = logLvl 1
452noErrors :: Idris Bool
453noErrors = do i <- getIState
454 case errLine i of
455 Nothing -> return True
456 _ -> return False
458setTypeCase :: Bool -> Idris ()
459setTypeCase t = do i <- getIState
460 let opts = idris_options i
461 let opt' = opts { opt_typecase = t }
462 putIState $ i { idris_options = opt' }
465-- For inferring types of things
467bi = FC "builtin" 0
469inferTy = MN 0 "__Infer"
470inferCon = MN 0 "__infer"
471inferDecl = PDatadecl inferTy
472 PType
473 [("", inferCon, PPi impl (MN 0 "A") PType (
474 PPi expl (MN 0 "a") (PRef bi (MN 0 "A"))
475 (PRef bi inferTy)), bi)]
477infTerm t = PApp bi (PRef bi inferCon) [pimp (MN 0 "A") Placeholder, pexp t]
478infP = P (TCon 6 0) inferTy (TType (UVal 0))
480getInferTerm, getInferType :: Term -> Term
481getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
482getInferTerm (App (App _ _) tm) = tm
483getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
485getInferType (Bind n b sc) = Bind n b $ getInferType sc
486getInferType (App (App _ ty) _) = ty
488-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
490primNames = [unitTy, unitCon,
491 falseTy, pairTy, pairCon,
492 eqTy, eqCon, inferTy, inferCon]
494unitTy = MN 0 "__Unit"
495unitCon = MN 0 "__II"
496unitDecl = PDatadecl unitTy PType
497 [("", unitCon, PRef bi unitTy, bi)]
499falseTy = MN 0 "__False"
500falseDecl = PDatadecl falseTy PType []
502pairTy = MN 0 "__Pair"
503pairCon = MN 0 "__MkPair"
504pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
505 [("", pairCon, PPi impl (n "A") PType (
506 PPi impl (n "B") PType (
507 PPi expl (n "a") (PRef bi (n "A")) (
508 PPi expl (n "b") (PRef bi (n "B"))
509 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
510 pexp (PRef bi (n "B"))])))), bi)]
511 where n a = MN 0 a
513eqTy = UN "="
514eqCon = UN "refl"
515eqDecl = PDatadecl eqTy (piBind [(n "a", PType), (n "b", PType),
516 (n "x", PRef bi (n "a")), (n "y", PRef bi (n "b"))]
517 PType)
518 [("", eqCon, PPi impl (n "a") PType (
519 PPi impl (n "x") (PRef bi (n "a"))
520 (PApp bi (PRef bi eqTy) [pimp (n "a") Placeholder,
521 pimp (n "b") Placeholder,
522 pexp (PRef bi (n "x")),
523 pexp (PRef bi (n "x"))])), bi)]
524 where n a = MN 0 a
526-- Defined in builtins.idr
527sigmaTy = UN "Exists"
528existsCon = UN "Ex_intro"
530piBind :: [(Name, PTerm)] -> PTerm -> PTerm
531piBind = piBindp expl
533piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
534piBindp p [] t = t
535piBindp p ((n, ty):ns) t = PPi p n ty (piBind ns t)
537-- Dealing with parameters
539expandParams :: (Name -> Name) -> [(Name, PTerm)] ->
540 [Name] -> -- all names
541 [Name] -> -- names with no declaration
542 PTerm -> PTerm
543expandParams dec ps ns infs tm = en tm
544 where
545 -- if we shadow a name (say in a lambda binding) that is used in a call to
546 -- a lifted function, we need access to both names - once in the scope of the
547 -- binding and once to call the lifted functions. So we'll explicitly shadow
548 -- it. (Yes, it's a hack. The alternative would be to resolve names earlier
549 -- but we didn't...)
551 mkShadow (UN n) = MN 0 n
552 mkShadow (MN i n) = MN (i+1) n
553 mkShadow (NS x s) = NS (mkShadow x) s
555 en (PLam n t s)
556 | n `elem` map fst ps
557 = let n' = mkShadow n in
558 PLam n' (en t) (en (shadow n n' s))
559 | otherwise = PLam n (en t) (en s)
560 en (PPi p n t s)
561 | n `elem` map fst ps
562 = let n' = mkShadow n in
563 PPi p n' (en t) (en (shadow n n' s))
564 | otherwise = PPi p n (en t) (en s)
565 en (PLet n ty v s)
566 | n `elem` map fst ps
567 = let n' = mkShadow n in
568 PLet n' (en ty) (en v) (en (shadow n n' s))
569 | otherwise = PLet n (en ty) (en v) (en s)
570 en (PEq f l r) = PEq f (en l) (en r)
571 en (PRewrite f l r) = PRewrite f (en l) (en r)
572 en (PTyped l r) = PTyped (en l) (en r)
573 en (PPair f l r) = PPair f (en l) (en r)
574 en (PDPair f l t r) = PDPair f (en l) (en t) (en r)
575 en (PAlternative a as) = PAlternative a (map en as)
576 en (PHidden t) = PHidden (en t)
577 en (PUnifyLog t) = PUnifyLog (en t)
578 en (PDoBlock ds) = PDoBlock (map (fmap en) ds)
579 en (PProof ts) = PProof (map (fmap en) ts)
580 en (PTactics ts) = PTactics (map (fmap en) ts)
582 en (PQuote (Var n))
583 | n `nselem` ns = PQuote (Var (dec n))
584 en (PApp fc (PInferRef fc' n) as)
585 | n `nselem` ns = PApp fc (PInferRef fc' (dec n))
586 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
587 en (PApp fc (PRef fc' n) as)
588 | n `elem` infs = PApp fc (PInferRef fc' (dec n))
589 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
590 | n `nselem` ns = PApp fc (PRef fc' (dec n))
591 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
592 en (PRef fc n)
593 | n `elem` infs = PApp fc (PInferRef fc (dec n))
594 (map (pexp . (PRef fc)) (map fst ps))
595 | n `nselem` ns = PApp fc (PRef fc (dec n))
596 (map (pexp . (PRef fc)) (map fst ps))
597 en (PInferRef fc n)
598 | n `nselem` ns = PApp fc (PInferRef fc (dec n))
599 (map (pexp . (PRef fc)) (map fst ps))
600 en (PApp fc f as) = PApp fc (en f) (map (fmap en) as)
601 en (PCase fc c os) = PCase fc (en c) (map (pmap en) os)
602 en t = t
604 nselem x [] = False
605 nselem x (y : xs) | nseq x y = True
606 | otherwise = nselem x xs
608 nseq x y = nsroot x == nsroot y
610expandParamsD :: Bool -> -- True = RHS only
611 IState ->
612 (Name -> Name) -> [(Name, PTerm)] -> [Name] -> PDecl -> PDecl
613expandParamsD rhsonly ist dec ps ns (PTy doc syn fc o n ty)
614 = if n `elem` ns && (not rhsonly)
615 then -- trace (show (n, expandParams dec ps ns ty)) $
616 PTy doc syn fc o (dec n) (piBind ps (expandParams dec ps ns [] ty))
617 else --trace (show (n, expandParams dec ps ns ty)) $
618 PTy doc syn fc o n (expandParams dec ps ns [] ty)
619expandParamsD rhsonly ist dec ps ns (PPostulate doc syn fc o n ty)
620 = if n `elem` ns && (not rhsonly)
621 then -- trace (show (n, expandParams dec ps ns ty)) $
622 PPostulate doc syn fc o (dec n) (piBind ps
623 (expandParams dec ps ns [] ty))
624 else --trace (show (n, expandParams dec ps ns ty)) $
625 PPostulate doc syn fc o n (expandParams dec ps ns [] ty)
626expandParamsD rhsonly ist dec ps ns (PClauses fc opts n cs)
627 = let n' = if n `elem` ns then dec n else n in
628 PClauses fc opts n' (map expandParamsC cs)
629 where
630 expandParamsC (PClause fc n lhs ws rhs ds)
631 = let -- ps' = updateps True (namesIn ist rhs) (zip ps [0..])
632 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
633 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
634 n' = if n `elem` ns then dec n else n in
635 PClause fc n' lhs'
636 (map (expandParams dec ps'' ns []) ws)
637 (expandParams dec ps'' ns [] rhs)
638 (map (expandParamsD True ist dec ps'' ns) ds)
639 expandParamsC (PWith fc n lhs ws wval ds)
640 = let -- ps' = updateps True (namesIn ist wval) (zip ps [0..])
641 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
642 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
643 n' = if n `elem` ns then dec n else n in
644 PWith fc n' lhs'
645 (map (expandParams dec ps'' ns []) ws)
646 (expandParams dec ps'' ns [] wval)
647 (map (expandParamsD rhsonly ist dec ps'' ns) ds)
648 updateps yn nm [] = []
649 updateps yn nm (((a, t), i):as)
650 | (a `elem` nm) == yn = (a, t) : updateps yn nm as
651 | otherwise = (MN i (show n ++ "_u"), t) : updateps yn nm as
652expandParamsD rhs ist dec ps ns (PData doc syn fc co pd)
653 = PData doc syn fc co (expandPData pd)
654 where
655 -- just do the type decl, leave constructors alone (parameters will be
656 -- added implicitly)
657 expandPData (PDatadecl n ty cons)
658 = if n `elem` ns
659 then PDatadecl (dec n) (piBind ps (expandParams dec ps ns [] ty))
660 (map econ cons)
661 else PDatadecl n (expandParams dec ps ns [] ty) (map econ cons)
662 econ (doc, n, t, fc)
663 = (doc, dec n, piBindp expl ps (expandParams dec ps ns [] t), fc)
664expandParamsD rhs ist dec ps ns (PParams f params pds)
665 = PParams f (ps ++ map (mapsnd (expandParams dec ps ns [])) params)
666 (map (expandParamsD True ist dec ps ns) pds)
667-- (map (expandParamsD ist dec ps ns) pds)
668expandParamsD rhs ist dec ps ns (PMutual f pds)
669 = PMutual f (map (expandParamsD rhs ist dec ps ns) pds)
670expandParamsD rhs ist dec ps ns (PClass doc info f cs n params decls)
671 = PClass doc info f
672 (map (expandParams dec ps ns []) cs)
673 n
674 (map (mapsnd (expandParams dec ps ns [])) params)
675 (map (expandParamsD rhs ist dec ps ns) decls)
676expandParamsD rhs ist dec ps ns (PInstance info f cs n params ty cn decls)
677 = PInstance info f
678 (map (expandParams dec ps ns []) cs)
679 n
680 (map (expandParams dec ps ns []) params)
681 (expandParams dec ps ns [] ty)
682 cn
683 (map (expandParamsD rhs ist dec ps ns) decls)
684expandParamsD rhs ist dec ps ns d = d
686mapsnd f (x, t) = (x, f t)
688-- Calculate a priority for a type, for deciding elaboration order
689-- * if it's just a type variable or concrete type, do it early (0)
690-- * if there's only type variables and injective constructors, do it next (1)
691-- * if there's a function type, next (2)
692-- * finally, everything else (3)
694getPriority :: IState -> PTerm -> Int
695getPriority i tm = 1 -- pri tm
696 where
697 pri (PRef _ n) =
698 case lookupP n (tt_ctxt i) of
699 ((P (DCon _ _) _ _):_) -> 1
700 ((P (TCon _ _) _ _):_) -> 1
701 ((P Ref _ _):_) -> 1
702 [] -> 0 -- must be locally bound, if it's not an error...
703 pri (PPi _ _ x y) = max 5 (max (pri x) (pri y))
704 pri (PTrue _) = 0
705 pri (PFalse _) = 0
706 pri (PRefl _ _) = 1
707 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
708 pri (PRewrite _ l r) = max 1 (max (pri l) (pri r))
709 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
710 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
711 pri (PTyped l r) = pri l
712 pri (PPair _ l r) = max 1 (max (pri l) (pri r))
713 pri (PDPair _ l t r) = max 1 (max (pri l) (max (pri t) (pri r)))
714 pri (PAlternative a as) = maximum (map pri as)
715 pri (PConstant _) = 0
716 pri Placeholder = 1
717 pri _ = 3
719addStatics :: Name -> Term -> PTerm -> Idris ()
720addStatics n tm ptm =
721 do let (statics, dynamics) = initStatics tm ptm
722 let stnames = nub $ concatMap freeNames (map snd statics)
723 let dnames = nub $ concatMap freeNames (map snd dynamics)
724 when (not (null statics)) $
725 logLvl 7 $ show n ++ " " ++ show statics ++ "\n" ++ show dynamics
726 ++ "\n" ++ show stnames ++ "\n" ++ show dnames
727 let statics' = nub $ map fst statics ++
728 filter (\x -> not (elem x dnames)) stnames
729 let stpos = staticList statics' tm
730 i <- getIState
731 putIState $ i { idris_statics = addDef n stpos (idris_statics i) }
732 addIBC (IBCStatic n)
733 where
734 initStatics (Bind n (Pi ty) sc) (PPi p _ _ s)
735 = let (static, dynamic) = initStatics (instantiate (P Bound n ty) sc) s in
736 if pstatic p == Static then ((n, ty) : static, dynamic)
737 else (static, (n, ty) : dynamic)
738 initStatics t pt = ([], [])
740 staticList sts (Bind n (Pi _) sc) = (n `elem` sts) : staticList sts sc
741 staticList _ _ = []
743-- Dealing with implicit arguments
745-- Add constraint bindings from using block
747addUsingConstraints :: SyntaxInfo -> FC -> PTerm -> Idris PTerm
748addUsingConstraints syn fc t
749 = do ist <- get
750 let ns = namesIn [] ist t
751 let cs = getConstraints t -- check declared constraints
752 let addconsts = uconsts \\ cs
753 -- if all names in the arguments of addconsts appear in ns,
754 -- add the constraint implicitly
755 return (doAdd addconsts ns t)
756 where uconsts = filter uconst (using syn)
757 uconst (UConstraint _ _) = True
758 uconst _ = False
760 doAdd [] _ t = t
761 -- if all of args in ns, then add it
762 doAdd (UConstraint c args : cs) ns t
763 | all (\n -> elem n ns) args
764 = PPi (Constraint False Dynamic "") (MN 0 "cu")
765 (mkConst c args) (doAdd cs ns t)
766 | otherwise = doAdd cs ns t
768 mkConst c args = PApp fc (PRef fc c)
769 (map (\n -> PExp 0 False (PRef fc n) "") args)
771 getConstraints (PPi (Constraint _ _ _) _ c sc)
772 = getcapp c ++ getConstraints sc
773 getConstraints (PPi _ _ c sc) = getConstraints sc
774 getConstraints _ = []
776 getcapp (PApp _ (PRef _ c) args)
777 = do ns <- mapM getName args
778 return (UConstraint c ns)
779 getcapp _ = []
781 getName (PExp _ _ (PRef _ n) _) = return n
782 getName _ = []
784-- Add implicit Pi bindings for any names in the term which appear in an
785-- argument position.
787-- This has become a right mess already. Better redo it some time...
789implicit :: SyntaxInfo -> Name -> PTerm -> Idris PTerm
790implicit syn n ptm = implicit' syn [] n ptm
792implicit' :: SyntaxInfo -> [Name] -> Name -> PTerm -> Idris PTerm
793implicit' syn ignore n ptm
794 = do i <- getIState
795 let (tm', impdata) = implicitise syn ignore i ptm
796-- let (tm'', spos) = findStatics i tm'
797 putIState $ i { idris_implicits = addDef n impdata (idris_implicits i) }
798 addIBC (IBCImp n)
799 logLvl 5 ("Implicit " ++ show n ++ " " ++ show impdata)
800-- i <- get
801-- putIState $ i { idris_statics = addDef n spos (idris_statics i) }
802 return tm'
804implicitise :: SyntaxInfo -> [Name] -> IState -> PTerm -> (PTerm, [PArg])
805implicitise syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
806 let (declimps, ns') = execState (imps True [] tm) ([], [])
807 ns = filter (\n -> implicitable n || elem n (map fst uvars)) $
808 ns' \\ (map fst pvars ++ no_imp syn ++ ignore)
809 nsOrder = filter (not . inUsing) ns ++ filter inUsing ns in
810 if null ns
811 then (tm, reverse declimps)
812 else implicitise syn ignore ist (pibind uvars nsOrder tm)
813 where
814 uvars = map ipair (filter uimplicit (using syn))
815 pvars = syn_params syn
817 inUsing n = n `elem` map fst uvars
819 ipair (UImplicit x y) = (x, y)
820 uimplicit (UImplicit _ _) = True
821 uimplicit _ = False
823 dropAll (x:xs) ys | x `elem` ys = dropAll xs ys
824 | otherwise = x : dropAll xs ys
825 dropAll [] ys = []
827 imps top env (PApp _ f as)
828 = do (decls, ns) <- get
829 let isn = concatMap (namesIn uvars ist) (map getTm as)
830 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
831 imps top env (PPi (Imp l _ doc) n ty sc)
832 = do let isn = nub (namesIn uvars ist ty) `dropAll` [n]
833 (decls , ns) <- get
834 put (PImp (getPriority ist ty) l n ty doc : decls,
835 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
836 imps True (n:env) sc
837 imps top env (PPi (Exp l _ doc) n ty sc)
838 = do let isn = nub (namesIn uvars ist ty ++ case sc of
839 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
840 _ -> [])
841 (decls, ns) <- get -- ignore decls in HO types
842 put (PExp (getPriority ist ty) l ty doc : decls,
843 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
844 imps True (n:env) sc
845 imps top env (PPi (Constraint l _ doc) n ty sc)
846 = do let isn = nub (namesIn uvars ist ty ++ case sc of
847 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
848 _ -> [])
849 (decls, ns) <- get -- ignore decls in HO types
850 put (PConstraint 10 l ty doc : decls,
851 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
852 imps True (n:env) sc
853 imps top env (PPi (TacImp l _ scr doc) n ty sc)
854 = do let isn = nub (namesIn uvars ist ty ++ case sc of
855 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
856 _ -> [])
857 (decls, ns) <- get -- ignore decls in HO types
858 put (PTacImplicit 10 l n scr ty doc : decls,
859 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
860 imps True (n:env) sc
861 imps top env (PEq _ l r)
862 = do (decls, ns) <- get
863 let isn = namesIn uvars ist l ++ namesIn uvars ist r
864 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
865 imps top env (PRewrite _ l r)
866 = do (decls, ns) <- get
867 let isn = namesIn uvars ist l ++ namesIn uvars ist r
868 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
869 imps top env (PTyped l r)
870 = imps top env l
871 imps top env (PPair _ l r)
872 = do (decls, ns) <- get
873 let isn = namesIn uvars ist l ++ namesIn uvars ist r
874 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
875 imps top env (PDPair _ (PRef _ n) t r)
876 = do (decls, ns) <- get
877 let isn = nub (namesIn uvars ist t ++ namesIn uvars ist r) \\ [n]
878 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
879 imps top env (PDPair _ l t r)
880 = do (decls, ns) <- get
881 let isn = namesIn uvars ist l ++ namesIn uvars ist t ++
882 namesIn uvars ist r
883 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
884 imps top env (PAlternative a as)
885 = do (decls, ns) <- get
886 let isn = concatMap (namesIn uvars ist) as
887 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
888 imps top env (PLam n ty sc)
889 = do imps False env ty
890 imps False (n:env) sc
891 imps top env (PHidden tm) = imps False env tm
892 imps top env (PUnifyLog tm) = imps False env tm
893 imps top env _ = return ()
895 pibind using [] sc = sc
896 pibind using (n:ns) sc
897 = case lookup n using of
898 Just ty -> PPi (Imp False Dynamic "") n ty (pibind using ns sc)
899 Nothing -> PPi (Imp False Dynamic "") n Placeholder
900 (pibind using ns sc)
902-- Add implicit arguments in function calls
903addImplPat :: IState -> PTerm -> PTerm
904addImplPat = addImpl' True [] []
906addImplBound :: IState -> [Name] -> PTerm -> PTerm
907addImplBound ist ns = addImpl' False ns [] ist
909addImplBoundInf :: IState -> [Name] -> [Name] -> PTerm -> PTerm
910addImplBoundInf ist ns inf = addImpl' False ns inf ist
912addImpl :: IState -> PTerm -> PTerm
913addImpl = addImpl' False [] []
915-- TODO: in patterns, don't add implicits to function names guarded by constructors
916-- and *not* inside a PHidden
918addImpl' :: Bool -> [Name] -> [Name] -> IState -> PTerm -> PTerm
919addImpl' inpat env infns ist ptm = ai (zip env (repeat Nothing)) ptm
920 where
921 ai env (PRef fc f)
922 | f `elem` infns = PInferRef fc f
923 | not (f `elem` map fst env) = handleErr $ aiFn inpat inpat ist fc f []
924 ai env (PHidden (PRef fc f))
925 | not (f `elem` map fst env) = handleErr $ aiFn inpat False ist fc f []
926 ai env (PEq fc l r) = let l' = ai env l
927 r' = ai env r in
928 PEq fc l' r'
929 ai env (PRewrite fc l r) = let l' = ai env l
930 r' = ai env r in
931 PRewrite fc l' r'
932 ai env (PTyped l r) = let l' = ai env l
933 r' = ai env r in
934 PTyped l' r'
935 ai env (PPair fc l r) = let l' = ai env l
936 r' = ai env r in
937 PPair fc l' r'
938 ai env (PDPair fc l t r) = let l' = ai env l
939 t' = ai env t
940 r' = ai env r in
941 PDPair fc l' t' r'
942 ai env (PAlternative a as) = let as' = map (ai env) as in
943 PAlternative a as'
944 ai env (PApp fc (PInferRef _ f) as)
945 = let as' = map (fmap (ai env)) as in
946 PApp fc (PInferRef fc f) as'
947 ai env (PApp fc ftm@(PRef _ f) as)
948 | f `elem` infns = ai env (PApp fc (PInferRef fc f) as)
949 | not (f `elem` map fst env)
950 = let as' = map (fmap (ai env)) as in
951 handleErr $ aiFn inpat False ist fc f as'
952 | Just (Just ty) <- lookup f env
953 = let as' = map (fmap (ai env)) as
954 arity = getPArity ty in
955 mkPApp fc arity ftm as'
956 ai env (PApp fc f as) = let f' = ai env f
957 as' = map (fmap (ai env)) as in
958 mkPApp fc 1 f' as'
959 ai env (PCase fc c os) = let c' = ai env c
960 os' = map (pmap (ai env)) os in
961 PCase fc c' os'
962 ai env (PLam n ty sc) = let ty' = ai env ty
963 sc' = ai ((n, Just ty):env) sc in
964 PLam n ty' sc'
965 ai env (PLet n ty val sc)
966 = let ty' = ai env ty
967 val' = ai env val
968 sc' = ai ((n, Just ty):env) sc in
969 PLet n ty' val' sc'
970 ai env (PPi p n ty sc) = let ty' = ai env ty
971 sc' = ai ((n, Just ty):env) sc in
972 PPi p n ty' sc'
973 ai env (PHidden tm) = PHidden (ai env tm)
974 ai env (PProof ts) = PProof (map (fmap (ai env)) ts)
975 ai env (PTactics ts) = PTactics (map (fmap (ai env)) ts)
976 ai env (PUnifyLog tm) = PUnifyLog (ai env tm)
977 ai env tm = tm
979 handleErr (Left err) = PElabError err
980 handleErr (Right x) = x
982-- if in a pattern, and there are no arguments, and there's no possible
983-- names with zero explicit arguments, don't add implicits.
985aiFn :: Bool -> Bool -> IState -> FC -> Name -> [PArg] -> Either Err PTerm
986aiFn inpat True ist fc f []
987 = case lookupDef f (tt_ctxt ist) of
988 [] -> Right $ PPatvar fc f
989 alts -> let ialts = lookupCtxt f (idris_implicits ist) in
990 -- trace (show f ++ " " ++ show (fc, any (all imp) ialts, ialts, any constructor alts)) $
991 if (not (vname f) || tcname f
992 || any constructor alts || any allImp ialts)
993 then aiFn inpat False ist fc f [] -- use it as a constructor
994 else Right $ PPatvar fc f
995 where imp (PExp _ _ _ _) = False
996 imp _ = True
997 allImp [] = False
998 allImp xs = all imp xs
999 constructor (TyDecl (DCon _ _) _) = True
1000 constructor _ = False
1002 vname (UN n) = True -- non qualified
1003 vname _ = False
1005aiFn inpat expat ist fc f as
1006 | f `elem` primNames = Right $ PApp fc (PRef fc f) as
1007aiFn inpat expat ist fc f as
1008 -- This is where namespaces get resolved by adding PAlternative
1009 = case lookupCtxtName f (idris_implicits ist) of
1010 [(f',ns)] -> Right $ mkPApp fc (length ns) (PRef fc f') (insertImpl ns as)
1011 [] -> if f `elem` idris_metavars ist
1012 then Right $ PApp fc (PRef fc f) as
1013 else Right $ mkPApp fc (length as) (PRef fc f) as
1014 alts -> Right $
1015 PAlternative True $
1016 map (\(f', ns) -> mkPApp fc (length ns) (PRef fc f')
1017 (insertImpl ns as)) alts
1018 where
1019 insertImpl :: [PArg] -> [PArg] -> [PArg]
1020 insertImpl (PExp p l ty _ : ps) (PExp _ _ tm d : given) =
1021 PExp p l tm d : insertImpl ps given
1022 insertImpl (PConstraint p l ty _ : ps) (PConstraint _ _ tm d : given) =
1023 PConstraint p l tm d : insertImpl ps given
1024 insertImpl (PConstraint p l ty d : ps) given =
1025 PConstraint p l (PResolveTC fc) d : insertImpl ps given
1026 insertImpl (PImp p l n ty d : ps) given =
1027 case find n given [] of
1028 Just (tm, given') -> PImp p l n tm "" : insertImpl ps given'
1029 Nothing -> PImp p l n Placeholder "" : insertImpl ps given
1030 insertImpl (PTacImplicit p l n sc ty d : ps) given =
1031 case find n given [] of
1032 Just (tm, given') -> PTacImplicit p l n sc tm "" : insertImpl ps given'
1033 Nothing -> if inpat
1034 then PTacImplicit p l n sc Placeholder "" : insertImpl ps given
1035 else PTacImplicit p l n sc sc "" : insertImpl ps given
1036 insertImpl expected [] = []
1037 insertImpl _ given = given
1039 find n [] acc = Nothing
1040 find n (PImp _ _ n' t _ : gs) acc
1041 | n == n' = Just (t, reverse acc ++ gs)
1042 find n (PTacImplicit _ _ n' _ t _ : gs) acc
1043 | n == n' = Just (t, reverse acc ++ gs)
1044 find n (g : gs) acc = find n gs (g : acc)
1046-- replace non-linear occurrences with _
1047-- ASSUMPTION: This is called before adding 'alternatives' because otherwise
1048-- it is hard to get right!
1050stripLinear :: IState -> PTerm -> PTerm
1051stripLinear i tm = evalState (sl tm) [] where
1052 sl :: PTerm -> State [Name] PTerm
1053 sl (PRef fc f)
1054 | (_:_) <- lookupTy f (tt_ctxt i)
1055 = return $ PRef fc f
1056 | otherwise = do ns <- get
1057 if (f `elem` ns)
1058 then return Placeholder
1059 else do put (f : ns)
1060 return (PRef fc f)
1061 sl (PPatvar fc f)
1062 = do ns <- get
1063 if (f `elem` ns)
1064 then return Placeholder
1065 else do put (f : ns)
1066 return (PPatvar fc f)
1067 sl (PApp fc fn args) = do fn' <- sl fn
1068 args' <- mapM slA args
1069 return $ PApp fc fn' args'
1070 where slA (PImp p l n t d) = do t' <- sl t
1071 return $ PImp p l n t' d
1072 slA (PExp p l t d) = do t' <- sl t
1073 return $ PExp p l t' d
1074 slA (PConstraint p l t d)
1075 = do t' <- sl t
1076 return $ PConstraint p l t' d
1077 slA (PTacImplicit p l n sc t d)
1078 = do t' <- sl t
1079 return $ PTacImplicit p l n sc t' d
1080 sl x = return x
1082mkPApp fc a f [] = f
1083mkPApp fc a f as = let rest = drop a as in
1084 appRest fc (PApp fc f (take a as)) rest
1085 where
1086 appRest fc f [] = f
1087 appRest fc f (a : as) = appRest fc (PApp fc f [a]) as
1089-- Find 'static' argument positions
1090-- (the declared ones, plus any names in argument position in the declared
1091-- statics)
1092-- FIXME: It's possible that this really has to happen after elaboration
1094findStatics :: IState -> PTerm -> (PTerm, [Bool])
1095findStatics ist tm = trace (showImp True tm) $
1096 let (ns, ss) = fs tm in
1097 runState (pos ns ss tm) []
1098 where fs (PPi p n t sc)
1099 | Static <- pstatic p
1100 = let (ns, ss) = fs sc in
1101 (namesIn [] ist t : ns, n : ss)
1102 | otherwise = let (ns, ss) = fs sc in
1103 (ns, ss)
1104 fs _ = ([], [])
1106 inOne n ns = length (filter id (map (elem n) ns)) == 1
1108 pos ns ss (PPi p n t sc)
1109 | elem n ss = do sc' <- pos ns ss sc
1110 spos <- get
1111 put (True : spos)
1112 return (PPi (p { pstatic = Static }) n t sc')
1113 | otherwise = do sc' <- pos ns ss sc
1114 spos <- get
1115 put (False : spos)
1116 return (PPi p n t sc')
1117 pos ns ss t = return t
1119-- Debugging/logging stuff
1121dumpDecls :: [PDecl] -> String
1122dumpDecls [] = ""
1123dumpDecls (d:ds) = dumpDecl d ++ "\n" ++ dumpDecls ds
1125dumpDecl (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
1126dumpDecl (PTy _ _ _ _ n t) = "tydecl " ++ show n ++ " : " ++ showImp True t
1127dumpDecl (PClauses _ _ n cs) = "pat " ++ show n ++ "\t" ++ showSep "\n\t" (map (showCImp True) cs)
1128dumpDecl (PData _ _ _ _ d) = showDImp True d
1129dumpDecl (PParams _ ns ps) = "params {" ++ show ns ++ "\n" ++ dumpDecls ps ++ "}\n"
1130dumpDecl (PNamespace n ps) = "namespace {" ++ n ++ "\n" ++ dumpDecls ps ++ "}\n"
1131dumpDecl (PSyntax _ syn) = "syntax " ++ show syn
1132dumpDecl (PClass _ _ _ cs n ps ds)
1133 = "class " ++ show cs ++ " " ++ show n ++ " " ++ show ps ++ "\n" ++ dumpDecls ds
1134dumpDecl (PInstance _ _ cs n _ t _ ds)
1135 = "instance " ++ show cs ++ " " ++ show n ++ " " ++ show t ++ "\n" ++ dumpDecls ds
1136dumpDecl _ = "..."
1137-- dumpDecl (PImport i) = "import " ++ i
1139-- for 6.12/7 compatibility
1140data EitherErr a b = LeftErr a | RightOK b
1142instance Monad (EitherErr a) where
1143 return = RightOK
1145 (LeftErr e) >>= k = LeftErr e
1146 RightOK v >>= k = k v
1148toEither (LeftErr e) = Left e
1149toEither (RightOK ho) = Right ho
1151-- syntactic match of a against b, returning pair of variables in a
1152-- and what they match. Returns the pair that failed if not a match.
1154matchClause :: IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1155matchClause = matchClause' False
1157matchClause' :: Bool -> IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1158matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
1159 matchArg x y = match (fullApp (getTm x)) (fullApp (getTm y))
1161 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1162 fullApp x = x
1164 match' x y = match (fullApp x) (fullApp y)
1165 match (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x]) x'
1166 | PConstant (I _) <- getTm x = match (getTm x) x'
1167 match x' (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x])
1168 | PConstant (I _) <- getTm x = match (getTm x) x'
1169 match (PApp _ (PRef _ (UN "lazy")) [_,x]) x' = match (getTm x) x'
1170 match x (PApp _ (PRef _ (UN "lazy")) [_,x']) = match x (getTm x')
1171 match (PApp _ f args) (PApp _ f' args')
1172 | length args == length args'
1173 = do mf <- match' f f'
1174 ms <- zipWithM matchArg args args'
1175 return (mf ++ concat ms)
1176-- match (PRef _ n) (PRef _ n') | n == n' = return []
1177-- | otherwise = Nothing
1178 match (PRef f n) (PApp _ x []) = match (PRef f n) x
1179 match (PPatvar f n) xr = match (PRef f n) xr
1180 match xr (PPatvar f n) = match xr (PRef f n)
1181 match (PApp _ x []) (PRef f n) = match x (PRef f n)
1182 match (PRef _ n) tm@(PRef _ n')
1183 | n == n' && not names &&
1184 (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1185 = return [(n, tm)]
1186 | n == n' = return []
1187 match (PRef _ n) tm
1188 | not names && (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1189 = return [(n, tm)]
1190 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
1191 mr <- match' r r'
1192 return (ml ++ mr)
1193 match (PRewrite _ l r) (PRewrite _ l' r')
1194 = do ml <- match' l l'
1195 mr <- match' r r'
1196 return (ml ++ mr)
1197 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
1198 mr <- match r r'
1199 return (ml ++ mr)
1200 match (PTyped l r) x = match l x
1201 match x (PTyped l r) = match x l
1202 match (PPair _ l r) (PPair _ l' r') = do ml <- match' l l'
1203 mr <- match' r r'
1204 return (ml ++ mr)
1205 match (PDPair _ l t r) (PDPair _ l' t' r') = do ml <- match' l l'
1206 mt <- match' t t'
1207 mr <- match' r r'
1208 return (ml ++ mt ++ mr)
1209 match (PAlternative a as) (PAlternative a' as')
1210 = do ms <- zipWithM match' as as'
1211 return (concat ms)
1212 match a@(PAlternative _ as) b
1213 = do let ms = zipWith match' as (repeat b)
1214 case (rights (map toEither ms)) of
1215 (x: _) -> return x
1216 _ -> LeftErr (a, b)
1217 match (PCase _ _ _) _ = return [] -- lifted out
1218 match (PMetavar _) _ = return [] -- modified
1219 match (PInferRef _ _) _ = return [] -- modified
1220 match (PQuote _) _ = return []
1221 match (PProof _) _ = return []
1222 match (PTactics _) _ = return []
1223 match (PRefl _ _) (PRefl _ _) = return []
1224 match (PResolveTC _) (PResolveTC _) = return []
1225 match (PTrue _) (PTrue _) = return []
1226 match (PFalse _) (PFalse _) = return []
1227 match (PReturn _) (PReturn _) = return []
1228 match (PPi _ _ t s) (PPi _ _ t' s') = do mt <- match' t t'
1229 ms <- match' s s'
1230 return (mt ++ ms)
1231 match (PLam _ t s) (PLam _ t' s') = do mt <- match' t t'
1232 ms <- match' s s'
1233 return (mt ++ ms)
1234 match (PLet _ t ty s) (PLet _ t' ty' s') = do mt <- match' t t'
1235 mty <- match' ty ty'
1236 ms <- match' s s'
1237 return (mt ++ mty ++ ms)
1238 match (PHidden x) (PHidden y) = match' x y
1239 match (PUnifyLog x) y = match' x y
1240 match x (PUnifyLog y) = match' x y
1241 match Placeholder _ = return []
1242 match _ Placeholder = return []
1243 match (PResolveTC _) _ = return []
1244 match a b | a == b = return []
1245 | otherwise = LeftErr (a, b)
1247 checkRpts (RightOK ms) = check ms where
1248 check ((n,t):xs)
1249 | Just t' <- lookup n xs = if t/=t' && t/=Placeholder && t'/=Placeholder
1250 then Left (t, t')
1251 else check xs
1252 check (_:xs) = check xs
1253 check [] = Right ms
1254 checkRpts (LeftErr x) = Left x
1256substMatches :: [(Name, PTerm)] -> PTerm -> PTerm
1257substMatches ms = substMatchesShadow ms []
1259substMatchesShadow :: [(Name, PTerm)] -> [Name] -> PTerm -> PTerm
1260substMatchesShadow [] shs t = t
1261substMatchesShadow ((n,tm):ns) shs t
1262 = substMatchShadow n shs tm (substMatchesShadow ns shs t)
1264substMatch :: Name -> PTerm -> PTerm -> PTerm
1265substMatch n = substMatchShadow n []
1267substMatchShadow :: Name -> [Name] -> PTerm -> PTerm -> PTerm
1268substMatchShadow n shs tm t = sm shs t where
1269 sm xs (PRef _ n') | n == n' = tm
1270 sm xs (PLam x t sc) = PLam x (sm xs t) (sm xs sc)
1271 sm xs (PPi p x t sc)
1272 | x `elem` xs
1273 = let x' = nextName x in
1274 PPi p x' (sm (x':xs) (substMatch x (PRef (FC "" 0) x') t))
1275 (sm (x':xs) (substMatch x (PRef (FC "" 0) x') sc))
1276 | otherwise = PPi p x (sm xs t) (sm (x : xs) sc)
1277 sm xs (PApp f x as) = PApp f (sm xs x) (map (fmap (sm xs)) as)
1278 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
1279 sm xs (PEq f x y) = PEq f (sm xs x) (sm xs y)
1280 sm xs (PRewrite f x y) = PRewrite f (sm xs x) (sm xs y)
1281 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
1282 sm xs (PPair f x y) = PPair f (sm xs x) (sm xs y)
1283 sm xs (PDPair f x t y) = PDPair f (sm xs x) (sm xs t) (sm xs y)
1284 sm xs (PAlternative a as) = PAlternative a (map (sm xs) as)
1285 sm xs (PHidden x) = PHidden (sm xs x)
1286 sm xs (PUnifyLog x) = PUnifyLog (sm xs x)
1287 sm xs x = x
1289shadow :: Name -> Name -> PTerm -> PTerm
1290shadow n n' t = sm t where
1291 sm (PRef fc x) | n == x = PRef fc n'
1292 sm (PLam x t sc) = PLam x (sm t) (sm sc)
1293 sm (PPi p x t sc) = PPi p x (sm t) (sm sc)
1294 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
1295 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
1296 sm (PEq f x y) = PEq f (sm x) (sm y)
1297 sm (PRewrite f x y) = PRewrite f (sm x) (sm y)
1298 sm (PTyped x y) = PTyped (sm x) (sm y)
1299 sm (PPair f x y) = PPair f (sm x) (sm y)
1300 sm (PDPair f x t y) = PDPair f (sm x) (sm t) (sm y)
1301 sm (PAlternative a as) = PAlternative a (map sm as)
1302 sm (PHidden x) = PHidden (sm x)
1303 sm (PUnifyLog x) = PUnifyLog (sm x)
1304 sm x = x