on 5242001 help sign in
Idris-dev/src/Idris/AbsSyntax.hs
1350 lines 56 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)
33forCodegen :: Codegen -> [(Codegen, a)] -> [a]
34forCodegen tgt xs = [x | (tgt', x) <- xs, tgt == tgt']
36getObjectFiles :: Codegen -> Idris [FilePath]
37getObjectFiles tgt = do i <- getIState; return (forCodegen tgt $ idris_objs i)
39addObjectFile :: Codegen -> FilePath -> Idris ()
40addObjectFile tgt f = do i <- getIState; putIState $ i { idris_objs = (tgt, f) : idris_objs i }
42getLibs :: Codegen -> Idris [String]
43getLibs tgt = do i <- getIState; return (forCodegen tgt $ idris_libs i)
45addLib :: Codegen -> 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 :: Codegen -> 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 :: Codegen -> Idris [String]
167getHdrs tgt = do i <- getIState; return (forCodegen 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
282-- this needs some typing magic and more structured output towards emacs
283iputGoal :: String -> Idris ()
284iputGoal s = do i <- getIState
285 case idris_outputmode i of
286 RawOutput -> liftIO $ putStrLn s
287 IdeSlave n -> liftIO $ putStrLn $ convSExp "write-goal" s n
289isetPrompt :: String -> Idris ()
290isetPrompt p = do i <- getIState
291 case idris_outputmode i of
292 IdeSlave n -> liftIO $ putStrLn $ convSExp "set-prompt" p n
294iWarn :: FC -> String -> Idris ()
295iWarn fc err = do i <- getIState
296 case idris_outputmode i of
297 RawOutput -> liftIO $ putStrLn (show fc ++ ":" ++ err)
298 IdeSlave n -> liftIO $ putStrLn $ convSExp "warning" (fc_fname fc, fc_line fc, err) n
300setLogLevel :: Int -> Idris ()
301setLogLevel l = do i <- getIState
302 let opts = idris_options i
303 let opt' = opts { opt_logLevel = l }
304 putIState $ i { idris_options = opt' }
306setCmdLine :: [Opt] -> Idris ()
307setCmdLine opts = do i <- getIState
308 let iopts = idris_options i
309 putIState $ i { idris_options = iopts { opt_cmdline = opts } }
311getDumpDefun :: Idris (Maybe FilePath)
312getDumpDefun = do i <- getIState
313 return $ findC (opt_cmdline (idris_options i))
314 where findC [] = Nothing
315 findC (DumpDefun x : _) = Just x
316 findC (_ : xs) = findC xs
318getDumpCases :: Idris (Maybe FilePath)
319getDumpCases = do i <- getIState
320 return $ findC (opt_cmdline (idris_options i))
321 where findC [] = Nothing
322 findC (DumpCases x : _) = Just x
323 findC (_ : xs) = findC xs
325logLevel :: Idris Int
326logLevel = do i <- getIState
327 return (opt_logLevel (idris_options i))
329setErrContext :: Bool -> Idris ()
330setErrContext t = do i <- getIState
331 let opts = idris_options i
332 let opt' = opts { opt_errContext = t }
333 putIState $ i { idris_options = opt' }
335errContext :: Idris Bool
336errContext = do i <- getIState
337 return (opt_errContext (idris_options i))
339useREPL :: Idris Bool
340useREPL = do i <- getIState
341 return (opt_repl (idris_options i))
343setREPL :: Bool -> Idris ()
344setREPL t = do i <- getIState
345 let opts = idris_options i
346 let opt' = opts { opt_repl = t }
347 putIState $ i { idris_options = opt' }
349setQuiet :: Bool -> Idris ()
350setQuiet q = do i <- getIState
351 let opts = idris_options i
352 let opt' = opts { opt_quiet = q }
353 putIState $ i { idris_options = opt' }
355getQuiet :: Idris Bool
356getQuiet = do i <- getIState
357 let opts = idris_options i
358 return (opt_quiet opts)
360setCodegen :: Codegen -> Idris ()
361setCodegen t = do i <- getIState
362 let opts = idris_options i
363 let opt' = opts { opt_codegen = t }
364 putIState $ i { idris_options = opt' }
366codegen :: Idris Codegen
367codegen = do i <- getIState
368 return (opt_codegen (idris_options i))
370setOutputTy :: OutputType -> Idris ()
371setOutputTy t = do i <- getIState
372 let opts = idris_options i
373 let opt' = opts { opt_outputTy = t }
374 putIState $ i { idris_options = opt' }
376outputTy :: Idris OutputType
377outputTy = do i <- getIState
378 return $ opt_outputTy $ idris_options i
380setIdeSlave :: Bool -> Idris ()
381setIdeSlave True = do i <- getIState
382 putIState $ i { idris_outputmode = (IdeSlave 0) }
383setIdeSlave False = return ()
385setTargetTriple :: String -> Idris ()
386setTargetTriple t = do i <- getIState
387 let opts = idris_options i
388 opt' = opts { opt_triple = t }
389 putIState $ i { idris_options = opt' }
391targetTriple :: Idris String
392targetTriple = do i <- getIState
393 return (opt_triple (idris_options i))
395setTargetCPU :: String -> Idris ()
396setTargetCPU t = do i <- getIState
397 let opts = idris_options i
398 opt' = opts { opt_cpu = t }
399 putIState $ i { idris_options = opt' }
401targetCPU :: Idris String
402targetCPU = do i <- getIState
403 return (opt_cpu (idris_options i))
405setOptLevel :: Int -> Idris ()
406setOptLevel t = do i <- getIState
407 let opts = idris_options i
408 opt' = opts { opt_optLevel = t }
409 putIState $ i { idris_options = opt' }
411optLevel :: Idris Int
412optLevel = do i <- getIState
413 return (opt_optLevel (idris_options i))
415verbose :: Idris Bool
416verbose = do i <- getIState
417 return (opt_verbose (idris_options i))
419setVerbose :: Bool -> Idris ()
420setVerbose t = do i <- getIState
421 let opts = idris_options i
422 let opt' = opts { opt_verbose = t }
423 putIState $ i { idris_options = opt' }
425typeInType :: Idris Bool
426typeInType = do i <- getIState
427 return (opt_typeintype (idris_options i))
429setTypeInType :: Bool -> Idris ()
430setTypeInType t = do i <- getIState
431 let opts = idris_options i
432 let opt' = opts { opt_typeintype = t }
433 putIState $ i { idris_options = opt' }
435coverage :: Idris Bool
436coverage = do i <- getIState
437 return (opt_coverage (idris_options i))
439setCoverage :: Bool -> Idris ()
440setCoverage t = do i <- getIState
441 let opts = idris_options i
442 let opt' = opts { opt_coverage = t }
443 putIState $ i { idris_options = opt' }
445setIBCSubDir :: FilePath -> Idris ()
446setIBCSubDir fp = do i <- getIState
447 let opts = idris_options i
448 let opt' = opts { opt_ibcsubdir = fp }
449 putIState $ i { idris_options = opt' }
451valIBCSubDir :: IState -> Idris FilePath
452valIBCSubDir i = return (opt_ibcsubdir (idris_options i))
454addImportDir :: FilePath -> Idris ()
455addImportDir fp = do i <- getIState
456 let opts = idris_options i
457 let opt' = opts { opt_importdirs = fp : opt_importdirs opts }
458 putIState $ i { idris_options = opt' }
460setImportDirs :: [FilePath] -> Idris ()
461setImportDirs fps = do i <- getIState
462 let opts = idris_options i
463 let opt' = opts { opt_importdirs = fps }
464 putIState $ i { idris_options = opt' }
466allImportDirs :: IState -> Idris [FilePath]
467allImportDirs i = do let optdirs = opt_importdirs (idris_options i)
468 return ("." : reverse optdirs)
470impShow :: Idris Bool
471impShow = do i <- getIState
472 return (opt_showimp (idris_options i))
474setImpShow :: Bool -> Idris ()
475setImpShow t = do i <- getIState
476 let opts = idris_options i
477 let opt' = opts { opt_showimp = t }
478 putIState $ i { idris_options = opt' }
480logLvl :: Int -> String -> Idris ()
481logLvl l str = do i <- getIState
482 let lvl = opt_logLevel (idris_options i)
483 when (lvl >= l)
484 $ do liftIO (putStrLn str)
485 putIState $ i { idris_log = idris_log i ++ str ++ "\n" }
487cmdOptType :: Opt -> Idris Bool
488cmdOptType x = do i <- getIState
489 return $ x `elem` opt_cmdline (idris_options i)
491iLOG :: String -> Idris ()
492iLOG = logLvl 1
494noErrors :: Idris Bool
495noErrors = do i <- getIState
496 case errLine i of
497 Nothing -> return True
498 _ -> return False
500setTypeCase :: Bool -> Idris ()
501setTypeCase t = do i <- getIState
502 let opts = idris_options i
503 let opt' = opts { opt_typecase = t }
504 putIState $ i { idris_options = opt' }
507-- For inferring types of things
509bi = FC "builtin" 0
511inferTy = MN 0 "__Infer"
512inferCon = MN 0 "__infer"
513inferDecl = PDatadecl inferTy
514 PType
515 [("", inferCon, PPi impl (MN 0 "A") PType (
516 PPi expl (MN 0 "a") (PRef bi (MN 0 "A"))
517 (PRef bi inferTy)), bi)]
519infTerm t = PApp bi (PRef bi inferCon) [pimp (MN 0 "A") Placeholder, pexp t]
520infP = P (TCon 6 0) inferTy (TType (UVal 0))
522getInferTerm, getInferType :: Term -> Term
523getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
524getInferTerm (App (App _ _) tm) = tm
525getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
527getInferType (Bind n b sc) = Bind n b $ getInferType sc
528getInferType (App (App _ ty) _) = ty
530-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
532primNames = [unitTy, unitCon,
533 falseTy, pairTy, pairCon,
534 eqTy, eqCon, inferTy, inferCon]
536unitTy = MN 0 "__Unit"
537unitCon = MN 0 "__II"
538unitDecl = PDatadecl unitTy PType
539 [("", unitCon, PRef bi unitTy, bi)]
541falseTy = MN 0 "__False"
542falseDecl = PDatadecl falseTy PType []
544pairTy = MN 0 "__Pair"
545pairCon = MN 0 "__MkPair"
546pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
547 [("", pairCon, PPi impl (n "A") PType (
548 PPi impl (n "B") PType (
549 PPi expl (n "a") (PRef bi (n "A")) (
550 PPi expl (n "b") (PRef bi (n "B"))
551 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
552 pexp (PRef bi (n "B"))])))), bi)]
553 where n a = MN 0 a
555eqTy = UN "="
556eqCon = UN "refl"
557eqDecl = PDatadecl eqTy (piBind [(n "a", PType), (n "b", PType),
558 (n "x", PRef bi (n "a")), (n "y", PRef bi (n "b"))]
559 PType)
560 [("", eqCon, PPi impl (n "a") PType (
561 PPi impl (n "x") (PRef bi (n "a"))
562 (PApp bi (PRef bi eqTy) [pimp (n "a") Placeholder,
563 pimp (n "b") Placeholder,
564 pexp (PRef bi (n "x")),
565 pexp (PRef bi (n "x"))])), bi)]
566 where n a = MN 0 a
568-- Defined in builtins.idr
569sigmaTy = UN "Exists"
570existsCon = UN "Ex_intro"
572piBind :: [(Name, PTerm)] -> PTerm -> PTerm
573piBind = piBindp expl
575piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
576piBindp p [] t = t
577piBindp p ((n, ty):ns) t = PPi p n ty (piBind ns t)
579-- Dealing with parameters
581expandParams :: (Name -> Name) -> [(Name, PTerm)] ->
582 [Name] -> -- all names
583 [Name] -> -- names with no declaration
584 PTerm -> PTerm
585expandParams dec ps ns infs tm = en tm
586 where
587 -- if we shadow a name (say in a lambda binding) that is used in a call to
588 -- a lifted function, we need access to both names - once in the scope of the
589 -- binding and once to call the lifted functions. So we'll explicitly shadow
590 -- it. (Yes, it's a hack. The alternative would be to resolve names earlier
591 -- but we didn't...)
593 mkShadow (UN n) = MN 0 n
594 mkShadow (MN i n) = MN (i+1) n
595 mkShadow (NS x s) = NS (mkShadow x) s
597 en (PLam n t s)
598 | n `elem` map fst ps
599 = let n' = mkShadow n in
600 PLam n' (en t) (en (shadow n n' s))
601 | otherwise = PLam n (en t) (en s)
602 en (PPi p n t s)
603 | n `elem` map fst ps
604 = let n' = mkShadow n in
605 PPi p n' (en t) (en (shadow n n' s))
606 | otherwise = PPi p n (en t) (en s)
607 en (PLet n ty v s)
608 | n `elem` map fst ps
609 = let n' = mkShadow n in
610 PLet n' (en ty) (en v) (en (shadow n n' s))
611 | otherwise = PLet n (en ty) (en v) (en s)
612 en (PEq f l r) = PEq f (en l) (en r)
613 en (PRewrite f l r g) = PRewrite f (en l) (en r) (fmap en g)
614 en (PTyped l r) = PTyped (en l) (en r)
615 en (PPair f l r) = PPair f (en l) (en r)
616 en (PDPair f l t r) = PDPair f (en l) (en t) (en r)
617 en (PAlternative a as) = PAlternative a (map en as)
618 en (PHidden t) = PHidden (en t)
619 en (PUnifyLog t) = PUnifyLog (en t)
620 en (PDoBlock ds) = PDoBlock (map (fmap en) ds)
621 en (PProof ts) = PProof (map (fmap en) ts)
622 en (PTactics ts) = PTactics (map (fmap en) ts)
624 en (PQuote (Var n))
625 | n `nselem` ns = PQuote (Var (dec n))
626 en (PApp fc (PInferRef fc' n) as)
627 | n `nselem` ns = PApp fc (PInferRef fc' (dec n))
628 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
629 en (PApp fc (PRef fc' n) as)
630 | n `elem` infs = PApp fc (PInferRef fc' (dec n))
631 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
632 | n `nselem` ns = PApp fc (PRef fc' (dec n))
633 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
634 en (PRef fc n)
635 | n `elem` infs = PApp fc (PInferRef fc (dec n))
636 (map (pexp . (PRef fc)) (map fst ps))
637 | n `nselem` ns = PApp fc (PRef fc (dec n))
638 (map (pexp . (PRef fc)) (map fst ps))
639 en (PInferRef fc n)
640 | n `nselem` ns = PApp fc (PInferRef fc (dec n))
641 (map (pexp . (PRef fc)) (map fst ps))
642 en (PApp fc f as) = PApp fc (en f) (map (fmap en) as)
643 en (PCase fc c os) = PCase fc (en c) (map (pmap en) os)
644 en t = t
646 nselem x [] = False
647 nselem x (y : xs) | nseq x y = True
648 | otherwise = nselem x xs
650 nseq x y = nsroot x == nsroot y
652expandParamsD :: Bool -> -- True = RHS only
653 IState ->
654 (Name -> Name) -> [(Name, PTerm)] -> [Name] -> PDecl -> PDecl
655expandParamsD rhsonly ist dec ps ns (PTy doc syn fc o n ty)
656 = if n `elem` ns && (not rhsonly)
657 then -- trace (show (n, expandParams dec ps ns ty)) $
658 PTy doc syn fc o (dec n) (piBind ps (expandParams dec ps ns [] ty))
659 else --trace (show (n, expandParams dec ps ns ty)) $
660 PTy doc syn fc o n (expandParams dec ps ns [] ty)
661expandParamsD rhsonly ist dec ps ns (PPostulate doc syn fc o n ty)
662 = if n `elem` ns && (not rhsonly)
663 then -- trace (show (n, expandParams dec ps ns ty)) $
664 PPostulate doc syn fc o (dec n) (piBind ps
665 (expandParams dec ps ns [] ty))
666 else --trace (show (n, expandParams dec ps ns ty)) $
667 PPostulate doc syn fc o n (expandParams dec ps ns [] ty)
668expandParamsD rhsonly ist dec ps ns (PClauses fc opts n cs)
669 = let n' = if n `elem` ns then dec n else n in
670 PClauses fc opts n' (map expandParamsC cs)
671 where
672 expandParamsC (PClause fc n lhs ws rhs ds)
673 = let -- ps' = updateps True (namesIn ist rhs) (zip ps [0..])
674 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
675 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
676 n' = if n `elem` ns then dec n else n in
677 PClause fc n' lhs'
678 (map (expandParams dec ps'' ns []) ws)
679 (expandParams dec ps'' ns [] rhs)
680 (map (expandParamsD True ist dec ps'' ns) ds)
681 expandParamsC (PWith fc n lhs ws wval ds)
682 = let -- ps' = updateps True (namesIn ist wval) (zip ps [0..])
683 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
684 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
685 n' = if n `elem` ns then dec n else n in
686 PWith fc n' lhs'
687 (map (expandParams dec ps'' ns []) ws)
688 (expandParams dec ps'' ns [] wval)
689 (map (expandParamsD rhsonly ist dec ps'' ns) ds)
690 updateps yn nm [] = []
691 updateps yn nm (((a, t), i):as)
692 | (a `elem` nm) == yn = (a, t) : updateps yn nm as
693 | otherwise = (MN i (show n ++ "_u"), t) : updateps yn nm as
694expandParamsD rhs ist dec ps ns (PData doc syn fc co pd)
695 = PData doc syn fc co (expandPData pd)
696 where
697 -- just do the type decl, leave constructors alone (parameters will be
698 -- added implicitly)
699 expandPData (PDatadecl n ty cons)
700 = if n `elem` ns
701 then PDatadecl (dec n) (piBind ps (expandParams dec ps ns [] ty))
702 (map econ cons)
703 else PDatadecl n (expandParams dec ps ns [] ty) (map econ cons)
704 econ (doc, n, t, fc)
705 = (doc, dec n, piBindp expl ps (expandParams dec ps ns [] t), fc)
706expandParamsD rhs ist dec ps ns (PParams f params pds)
707 = PParams f (ps ++ map (mapsnd (expandParams dec ps ns [])) params)
708 (map (expandParamsD True ist dec ps ns) pds)
709-- (map (expandParamsD ist dec ps ns) pds)
710expandParamsD rhs ist dec ps ns (PMutual f pds)
711 = PMutual f (map (expandParamsD rhs ist dec ps ns) pds)
712expandParamsD rhs ist dec ps ns (PClass doc info f cs n params decls)
713 = PClass doc info f
714 (map (expandParams dec ps ns []) cs)
715 n
716 (map (mapsnd (expandParams dec ps ns [])) params)
717 (map (expandParamsD rhs ist dec ps ns) decls)
718expandParamsD rhs ist dec ps ns (PInstance info f cs n params ty cn decls)
719 = PInstance info f
720 (map (expandParams dec ps ns []) cs)
721 n
722 (map (expandParams dec ps ns []) params)
723 (expandParams dec ps ns [] ty)
724 cn
725 (map (expandParamsD rhs ist dec ps ns) decls)
726expandParamsD rhs ist dec ps ns d = d
728mapsnd f (x, t) = (x, f t)
730-- Calculate a priority for a type, for deciding elaboration order
731-- * if it's just a type variable or concrete type, do it early (0)
732-- * if there's only type variables and injective constructors, do it next (1)
733-- * if there's a function type, next (2)
734-- * finally, everything else (3)
736getPriority :: IState -> PTerm -> Int
737getPriority i tm = 1 -- pri tm
738 where
739 pri (PRef _ n) =
740 case lookupP n (tt_ctxt i) of
741 ((P (DCon _ _) _ _):_) -> 1
742 ((P (TCon _ _) _ _):_) -> 1
743 ((P Ref _ _):_) -> 1
744 [] -> 0 -- must be locally bound, if it's not an error...
745 pri (PPi _ _ x y) = max 5 (max (pri x) (pri y))
746 pri (PTrue _) = 0
747 pri (PFalse _) = 0
748 pri (PRefl _ _) = 1
749 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
750 pri (PRewrite _ l r _) = max 1 (max (pri l) (pri r))
751 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
752 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
753 pri (PTyped l r) = pri l
754 pri (PPair _ l r) = max 1 (max (pri l) (pri r))
755 pri (PDPair _ l t r) = max 1 (max (pri l) (max (pri t) (pri r)))
756 pri (PAlternative a as) = maximum (map pri as)
757 pri (PConstant _) = 0
758 pri Placeholder = 1
759 pri _ = 3
761addStatics :: Name -> Term -> PTerm -> Idris ()
762addStatics n tm ptm =
763 do let (statics, dynamics) = initStatics tm ptm
764 let stnames = nub $ concatMap freeNames (map snd statics)
765 let dnames = nub $ concatMap freeNames (map snd dynamics)
766 when (not (null statics)) $
767 logLvl 7 $ show n ++ " " ++ show statics ++ "\n" ++ show dynamics
768 ++ "\n" ++ show stnames ++ "\n" ++ show dnames
769 let statics' = nub $ map fst statics ++
770 filter (\x -> not (elem x dnames)) stnames
771 let stpos = staticList statics' tm
772 i <- getIState
773 putIState $ i { idris_statics = addDef n stpos (idris_statics i) }
774 addIBC (IBCStatic n)
775 where
776 initStatics (Bind n (Pi ty) sc) (PPi p _ _ s)
777 = let (static, dynamic) = initStatics (instantiate (P Bound n ty) sc) s in
778 if pstatic p == Static then ((n, ty) : static, dynamic)
779 else (static, (n, ty) : dynamic)
780 initStatics t pt = ([], [])
782 staticList sts (Bind n (Pi _) sc) = (n `elem` sts) : staticList sts sc
783 staticList _ _ = []
785-- Dealing with implicit arguments
787-- Add constraint bindings from using block
789addUsingConstraints :: SyntaxInfo -> FC -> PTerm -> Idris PTerm
790addUsingConstraints syn fc t
791 = do ist <- get
792 let ns = namesIn [] ist t
793 let cs = getConstraints t -- check declared constraints
794 let addconsts = uconsts \\ cs
795 -- if all names in the arguments of addconsts appear in ns,
796 -- add the constraint implicitly
797 return (doAdd addconsts ns t)
798 where uconsts = filter uconst (using syn)
799 uconst (UConstraint _ _) = True
800 uconst _ = False
802 doAdd [] _ t = t
803 -- if all of args in ns, then add it
804 doAdd (UConstraint c args : cs) ns t
805 | all (\n -> elem n ns) args
806 = PPi (Constraint False Dynamic "") (MN 0 "cu")
807 (mkConst c args) (doAdd cs ns t)
808 | otherwise = doAdd cs ns t
810 mkConst c args = PApp fc (PRef fc c)
811 (map (\n -> PExp 0 False (PRef fc n) "") args)
813 getConstraints (PPi (Constraint _ _ _) _ c sc)
814 = getcapp c ++ getConstraints sc
815 getConstraints (PPi _ _ c sc) = getConstraints sc
816 getConstraints _ = []
818 getcapp (PApp _ (PRef _ c) args)
819 = do ns <- mapM getName args
820 return (UConstraint c ns)
821 getcapp _ = []
823 getName (PExp _ _ (PRef _ n) _) = return n
824 getName _ = []
826-- Add implicit Pi bindings for any names in the term which appear in an
827-- argument position.
829-- This has become a right mess already. Better redo it some time...
831implicit :: SyntaxInfo -> Name -> PTerm -> Idris PTerm
832implicit syn n ptm = implicit' syn [] n ptm
834implicit' :: SyntaxInfo -> [Name] -> Name -> PTerm -> Idris PTerm
835implicit' syn ignore n ptm
836 = do i <- getIState
837 let (tm', impdata) = implicitise syn ignore i ptm
838-- let (tm'', spos) = findStatics i tm'
839 putIState $ i { idris_implicits = addDef n impdata (idris_implicits i) }
840 addIBC (IBCImp n)
841 logLvl 5 ("Implicit " ++ show n ++ " " ++ show impdata)
842-- i <- get
843-- putIState $ i { idris_statics = addDef n spos (idris_statics i) }
844 return tm'
846implicitise :: SyntaxInfo -> [Name] -> IState -> PTerm -> (PTerm, [PArg])
847implicitise syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
848 let (declimps, ns') = execState (imps True [] tm) ([], [])
849 ns = filter (\n -> implicitable n || elem n (map fst uvars)) $
850 ns' \\ (map fst pvars ++ no_imp syn ++ ignore)
851 nsOrder = filter (not . inUsing) ns ++ filter inUsing ns in
852 if null ns
853 then (tm, reverse declimps)
854 else implicitise syn ignore ist (pibind uvars nsOrder tm)
855 where
856 uvars = map ipair (filter uimplicit (using syn))
857 pvars = syn_params syn
859 inUsing n = n `elem` map fst uvars
861 ipair (UImplicit x y) = (x, y)
862 uimplicit (UImplicit _ _) = True
863 uimplicit _ = False
865 dropAll (x:xs) ys | x `elem` ys = dropAll xs ys
866 | otherwise = x : dropAll xs ys
867 dropAll [] ys = []
869 imps top env (PApp _ f as)
870 = do (decls, ns) <- get
871 let isn = concatMap (namesIn uvars ist) (map getTm as)
872 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
873 imps top env (PPi (Imp l _ doc) n ty sc)
874 = do let isn = nub (namesIn uvars ist ty) `dropAll` [n]
875 (decls , ns) <- get
876 put (PImp (getPriority ist ty) l n ty doc : decls,
877 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
878 imps True (n:env) sc
879 imps top env (PPi (Exp l _ doc) n ty sc)
880 = do let isn = nub (namesIn uvars ist ty ++ case sc of
881 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
882 _ -> [])
883 (decls, ns) <- get -- ignore decls in HO types
884 put (PExp (getPriority ist ty) l ty doc : decls,
885 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
886 imps True (n:env) sc
887 imps top env (PPi (Constraint l _ doc) n ty sc)
888 = do let isn = nub (namesIn uvars ist ty ++ case sc of
889 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
890 _ -> [])
891 (decls, ns) <- get -- ignore decls in HO types
892 put (PConstraint 10 l ty doc : decls,
893 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
894 imps True (n:env) sc
895 imps top env (PPi (TacImp l _ scr doc) n ty sc)
896 = do let isn = nub (namesIn uvars ist ty ++ case sc of
897 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
898 _ -> [])
899 (decls, ns) <- get -- ignore decls in HO types
900 put (PTacImplicit 10 l n scr ty doc : decls,
901 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
902 imps True (n:env) sc
903 imps top env (PEq _ l r)
904 = do (decls, ns) <- get
905 let isn = namesIn uvars ist l ++ namesIn uvars ist r
906 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
907 imps top env (PRewrite _ l r _)
908 = do (decls, ns) <- get
909 let isn = namesIn uvars ist l ++ namesIn uvars ist r
910 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
911 imps top env (PTyped l r)
912 = imps top env l
913 imps top env (PPair _ l r)
914 = do (decls, ns) <- get
915 let isn = namesIn uvars ist l ++ namesIn uvars ist r
916 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
917 imps top env (PDPair _ (PRef _ n) t r)
918 = do (decls, ns) <- get
919 let isn = nub (namesIn uvars ist t ++ namesIn uvars ist r) \\ [n]
920 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
921 imps top env (PDPair _ l t r)
922 = do (decls, ns) <- get
923 let isn = namesIn uvars ist l ++ namesIn uvars ist t ++
924 namesIn uvars ist r
925 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
926 imps top env (PAlternative a as)
927 = do (decls, ns) <- get
928 let isn = concatMap (namesIn uvars ist) as
929 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
930 imps top env (PLam n ty sc)
931 = do imps False env ty
932 imps False (n:env) sc
933 imps top env (PHidden tm) = imps False env tm
934 imps top env (PUnifyLog tm) = imps False env tm
935 imps top env _ = return ()
937 pibind using [] sc = sc
938 pibind using (n:ns) sc
939 = case lookup n using of
940 Just ty -> PPi (Imp False Dynamic "") n ty (pibind using ns sc)
941 Nothing -> PPi (Imp False Dynamic "") n Placeholder
942 (pibind using ns sc)
944-- Add implicit arguments in function calls
945addImplPat :: IState -> PTerm -> PTerm
946addImplPat = addImpl' True [] []
948addImplBound :: IState -> [Name] -> PTerm -> PTerm
949addImplBound ist ns = addImpl' False ns [] ist
951addImplBoundInf :: IState -> [Name] -> [Name] -> PTerm -> PTerm
952addImplBoundInf ist ns inf = addImpl' False ns inf ist
954addImpl :: IState -> PTerm -> PTerm
955addImpl = addImpl' False [] []
957-- TODO: in patterns, don't add implicits to function names guarded by constructors
958-- and *not* inside a PHidden
960addImpl' :: Bool -> [Name] -> [Name] -> IState -> PTerm -> PTerm
961addImpl' inpat env infns ist ptm = ai (zip env (repeat Nothing)) ptm
962 where
963 ai env (PRef fc f)
964 | f `elem` infns = PInferRef fc f
965 | not (f `elem` map fst env) = handleErr $ aiFn inpat inpat ist fc f []
966 ai env (PHidden (PRef fc f))
967 | not (f `elem` map fst env) = handleErr $ aiFn inpat False ist fc f []
968 ai env (PEq fc l r) = let l' = ai env l
969 r' = ai env r in
970 PEq fc l' r'
971 ai env (PRewrite fc l r g) = let l' = ai env l
972 r' = ai env r
973 g' = fmap (ai env) g in
974 PRewrite fc l' r' g'
975 ai env (PTyped l r) = let l' = ai env l
976 r' = ai env r in
977 PTyped l' r'
978 ai env (PPair fc l r) = let l' = ai env l
979 r' = ai env r in
980 PPair fc l' r'
981 ai env (PDPair fc l t r) = let l' = ai env l
982 t' = ai env t
983 r' = ai env r in
984 PDPair fc l' t' r'
985 ai env (PAlternative a as) = let as' = map (ai env) as in
986 PAlternative a as'
987 ai env (PApp fc (PInferRef _ f) as)
988 = let as' = map (fmap (ai env)) as in
989 PApp fc (PInferRef fc f) as'
990 ai env (PApp fc ftm@(PRef _ f) as)
991 | f `elem` infns = ai env (PApp fc (PInferRef fc f) as)
992 | not (f `elem` map fst env)
993 = let as' = map (fmap (ai env)) as in
994 handleErr $ aiFn inpat False ist fc f as'
995 | Just (Just ty) <- lookup f env
996 = let as' = map (fmap (ai env)) as
997 arity = getPArity ty in
998 mkPApp fc arity ftm as'
999 ai env (PApp fc f as) = let f' = ai env f
1000 as' = map (fmap (ai env)) as in
1001 mkPApp fc 1 f' as'
1002 ai env (PCase fc c os) = let c' = ai env c
1003 os' = map (pmap (ai env)) os in
1004 PCase fc c' os'
1005 ai env (PLam n ty sc) = let ty' = ai env ty
1006 sc' = ai ((n, Just ty):env) sc in
1007 PLam n ty' sc'
1008 ai env (PLet n ty val sc)
1009 = let ty' = ai env ty
1010 val' = ai env val
1011 sc' = ai ((n, Just ty):env) sc in
1012 PLet n ty' val' sc'
1013 ai env (PPi p n ty sc) = let ty' = ai env ty
1014 sc' = ai ((n, Just ty):env) sc in
1015 PPi p n ty' sc'
1016 ai env (PHidden tm) = PHidden (ai env tm)
1017 ai env (PProof ts) = PProof (map (fmap (ai env)) ts)
1018 ai env (PTactics ts) = PTactics (map (fmap (ai env)) ts)
1019 ai env (PUnifyLog tm) = PUnifyLog (ai env tm)
1020 ai env tm = tm
1022 handleErr (Left err) = PElabError err
1023 handleErr (Right x) = x
1025-- if in a pattern, and there are no arguments, and there's no possible
1026-- names with zero explicit arguments, don't add implicits.
1028aiFn :: Bool -> Bool -> IState -> FC -> Name -> [PArg] -> Either Err PTerm
1029aiFn inpat True ist fc f []
1030 = case lookupDef f (tt_ctxt ist) of
1031 [] -> Right $ PPatvar fc f
1032 alts -> let ialts = lookupCtxt f (idris_implicits ist) in
1033 -- trace (show f ++ " " ++ show (fc, any (all imp) ialts, ialts, any constructor alts)) $
1034 if (not (vname f) || tcname f
1035 || any constructor alts || any allImp ialts)
1036 then aiFn inpat False ist fc f [] -- use it as a constructor
1037 else Right $ PPatvar fc f
1038 where imp (PExp _ _ _ _) = False
1039 imp _ = True
1040 allImp [] = False
1041 allImp xs = all imp xs
1042 constructor (TyDecl (DCon _ _) _) = True
1043 constructor _ = False
1045 vname (UN n) = True -- non qualified
1046 vname _ = False
1048aiFn inpat expat ist fc f as
1049 | f `elem` primNames = Right $ PApp fc (PRef fc f) as
1050aiFn inpat expat ist fc f as
1051 -- This is where namespaces get resolved by adding PAlternative
1052 = case lookupCtxtName f (idris_implicits ist) of
1053 [(f',ns)] -> Right $ mkPApp fc (length ns) (PRef fc f') (insertImpl ns as)
1054 [] -> if f `elem` idris_metavars ist
1055 then Right $ PApp fc (PRef fc f) as
1056 else Right $ mkPApp fc (length as) (PRef fc f) as
1057 alts -> Right $
1058 PAlternative True $
1059 map (\(f', ns) -> mkPApp fc (length ns) (PRef fc f')
1060 (insertImpl ns as)) alts
1061 where
1062 insertImpl :: [PArg] -> [PArg] -> [PArg]
1063 insertImpl (PExp p l ty _ : ps) (PExp _ _ tm d : given) =
1064 PExp p l tm d : insertImpl ps given
1065 insertImpl (PConstraint p l ty _ : ps) (PConstraint _ _ tm d : given) =
1066 PConstraint p l tm d : insertImpl ps given
1067 insertImpl (PConstraint p l ty d : ps) given =
1068 PConstraint p l (PResolveTC fc) d : insertImpl ps given
1069 insertImpl (PImp p l n ty d : ps) given =
1070 case find n given [] of
1071 Just (tm, given') -> PImp p l n tm "" : insertImpl ps given'
1072 Nothing -> PImp p l n Placeholder "" : insertImpl ps given
1073 insertImpl (PTacImplicit p l n sc ty d : ps) given =
1074 case find n given [] of
1075 Just (tm, given') -> PTacImplicit p l n sc tm "" : insertImpl ps given'
1076 Nothing -> if inpat
1077 then PTacImplicit p l n sc Placeholder "" : insertImpl ps given
1078 else PTacImplicit p l n sc sc "" : insertImpl ps given
1079 insertImpl expected [] = []
1080 insertImpl _ given = given
1082 find n [] acc = Nothing
1083 find n (PImp _ _ n' t _ : gs) acc
1084 | n == n' = Just (t, reverse acc ++ gs)
1085 find n (PTacImplicit _ _ n' _ t _ : gs) acc
1086 | n == n' = Just (t, reverse acc ++ gs)
1087 find n (g : gs) acc = find n gs (g : acc)
1089-- replace non-linear occurrences with _
1090-- ASSUMPTION: This is called before adding 'alternatives' because otherwise
1091-- it is hard to get right!
1093stripLinear :: IState -> PTerm -> PTerm
1094stripLinear i tm = evalState (sl tm) [] where
1095 sl :: PTerm -> State [Name] PTerm
1096 sl (PRef fc f)
1097 | (_:_) <- lookupTy f (tt_ctxt i)
1098 = return $ PRef fc f
1099 | otherwise = do ns <- get
1100 if (f `elem` ns)
1101 then return Placeholder
1102 else do put (f : ns)
1103 return (PRef fc f)
1104 sl (PPatvar fc f)
1105 = do ns <- get
1106 if (f `elem` ns)
1107 then return Placeholder
1108 else do put (f : ns)
1109 return (PPatvar fc f)
1110 sl (PApp fc fn args) = do fn' <- sl fn
1111 args' <- mapM slA args
1112 return $ PApp fc fn' args'
1113 where slA (PImp p l n t d) = do t' <- sl t
1114 return $ PImp p l n t' d
1115 slA (PExp p l t d) = do t' <- sl t
1116 return $ PExp p l t' d
1117 slA (PConstraint p l t d)
1118 = do t' <- sl t
1119 return $ PConstraint p l t' d
1120 slA (PTacImplicit p l n sc t d)
1121 = do t' <- sl t
1122 return $ PTacImplicit p l n sc t' d
1123 sl x = return x
1125mkPApp fc a f [] = f
1126mkPApp fc a f as = let rest = drop a as in
1127 appRest fc (PApp fc f (take a as)) rest
1128 where
1129 appRest fc f [] = f
1130 appRest fc f (a : as) = appRest fc (PApp fc f [a]) as
1132-- Find 'static' argument positions
1133-- (the declared ones, plus any names in argument position in the declared
1134-- statics)
1135-- FIXME: It's possible that this really has to happen after elaboration
1137findStatics :: IState -> PTerm -> (PTerm, [Bool])
1138findStatics ist tm = trace (showImp True tm) $
1139 let (ns, ss) = fs tm in
1140 runState (pos ns ss tm) []
1141 where fs (PPi p n t sc)
1142 | Static <- pstatic p
1143 = let (ns, ss) = fs sc in
1144 (namesIn [] ist t : ns, n : ss)
1145 | otherwise = let (ns, ss) = fs sc in
1146 (ns, ss)
1147 fs _ = ([], [])
1149 inOne n ns = length (filter id (map (elem n) ns)) == 1
1151 pos ns ss (PPi p n t sc)
1152 | elem n ss = do sc' <- pos ns ss sc
1153 spos <- get
1154 put (True : spos)
1155 return (PPi (p { pstatic = Static }) n t sc')
1156 | otherwise = do sc' <- pos ns ss sc
1157 spos <- get
1158 put (False : spos)
1159 return (PPi p n t sc')
1160 pos ns ss t = return t
1162-- Debugging/logging stuff
1164dumpDecls :: [PDecl] -> String
1165dumpDecls [] = ""
1166dumpDecls (d:ds) = dumpDecl d ++ "\n" ++ dumpDecls ds
1168dumpDecl (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
1169dumpDecl (PTy _ _ _ _ n t) = "tydecl " ++ show n ++ " : " ++ showImp True t
1170dumpDecl (PClauses _ _ n cs) = "pat " ++ show n ++ "\t" ++ showSep "\n\t" (map (showCImp True) cs)
1171dumpDecl (PData _ _ _ _ d) = showDImp True d
1172dumpDecl (PParams _ ns ps) = "params {" ++ show ns ++ "\n" ++ dumpDecls ps ++ "}\n"
1173dumpDecl (PNamespace n ps) = "namespace {" ++ n ++ "\n" ++ dumpDecls ps ++ "}\n"
1174dumpDecl (PSyntax _ syn) = "syntax " ++ show syn
1175dumpDecl (PClass _ _ _ cs n ps ds)
1176 = "class " ++ show cs ++ " " ++ show n ++ " " ++ show ps ++ "\n" ++ dumpDecls ds
1177dumpDecl (PInstance _ _ cs n _ t _ ds)
1178 = "instance " ++ show cs ++ " " ++ show n ++ " " ++ show t ++ "\n" ++ dumpDecls ds
1179dumpDecl _ = "..."
1180-- dumpDecl (PImport i) = "import " ++ i
1182-- for 6.12/7 compatibility
1183data EitherErr a b = LeftErr a | RightOK b
1185instance Monad (EitherErr a) where
1186 return = RightOK
1188 (LeftErr e) >>= k = LeftErr e
1189 RightOK v >>= k = k v
1191toEither (LeftErr e) = Left e
1192toEither (RightOK ho) = Right ho
1194-- syntactic match of a against b, returning pair of variables in a
1195-- and what they match. Returns the pair that failed if not a match.
1197matchClause :: IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1198matchClause = matchClause' False
1200matchClause' :: Bool -> IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1201matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
1202 matchArg x y = match (fullApp (getTm x)) (fullApp (getTm y))
1204 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1205 fullApp x = x
1207 match' x y = match (fullApp x) (fullApp y)
1208 match (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x]) x'
1209 | PConstant (I _) <- getTm x = match (getTm x) x'
1210 match x' (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x])
1211 | PConstant (I _) <- getTm x = match (getTm x) x'
1212 match (PApp _ (PRef _ (UN "lazy")) [_,x]) x' = match (getTm x) x'
1213 match x (PApp _ (PRef _ (UN "lazy")) [_,x']) = match x (getTm x')
1214 match (PApp _ f args) (PApp _ f' args')
1215 | length args == length args'
1216 = do mf <- match' f f'
1217 ms <- zipWithM matchArg args args'
1218 return (mf ++ concat ms)
1219-- match (PRef _ n) (PRef _ n') | n == n' = return []
1220-- | otherwise = Nothing
1221 match (PRef f n) (PApp _ x []) = match (PRef f n) x
1222 match (PPatvar f n) xr = match (PRef f n) xr
1223 match xr (PPatvar f n) = match xr (PRef f n)
1224 match (PApp _ x []) (PRef f n) = match x (PRef f n)
1225 match (PRef _ n) tm@(PRef _ n')
1226 | n == n' && not names &&
1227 (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1228 = return [(n, tm)]
1229 | n == n' = return []
1230 match (PRef _ n) tm
1231 | not names && (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1232 = return [(n, tm)]
1233 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
1234 mr <- match' r r'
1235 return (ml ++ mr)
1236 match (PRewrite _ l r _) (PRewrite _ l' r' _)
1237 = do ml <- match' l l'
1238 mr <- match' r r'
1239 return (ml ++ mr)
1240 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
1241 mr <- match r r'
1242 return (ml ++ mr)
1243 match (PTyped l r) x = match l x
1244 match x (PTyped l r) = match x l
1245 match (PPair _ l r) (PPair _ l' r') = do ml <- match' l l'
1246 mr <- match' r r'
1247 return (ml ++ mr)
1248 match (PDPair _ l t r) (PDPair _ l' t' r') = do ml <- match' l l'
1249 mt <- match' t t'
1250 mr <- match' r r'
1251 return (ml ++ mt ++ mr)
1252 match (PAlternative a as) (PAlternative a' as')
1253 = do ms <- zipWithM match' as as'
1254 return (concat ms)
1255 match a@(PAlternative _ as) b
1256 = do let ms = zipWith match' as (repeat b)
1257 case (rights (map toEither ms)) of
1258 (x: _) -> return x
1259 _ -> LeftErr (a, b)
1260 match (PCase _ _ _) _ = return [] -- lifted out
1261 match (PMetavar _) _ = return [] -- modified
1262 match (PInferRef _ _) _ = return [] -- modified
1263 match (PQuote _) _ = return []
1264 match (PProof _) _ = return []
1265 match (PTactics _) _ = return []
1266 match (PRefl _ _) (PRefl _ _) = return []
1267 match (PResolveTC _) (PResolveTC _) = return []
1268 match (PTrue _) (PTrue _) = return []
1269 match (PFalse _) (PFalse _) = return []
1270 match (PReturn _) (PReturn _) = return []
1271 match (PPi _ _ t s) (PPi _ _ t' s') = do mt <- match' t t'
1272 ms <- match' s s'
1273 return (mt ++ ms)
1274 match (PLam _ t s) (PLam _ t' s') = do mt <- match' t t'
1275 ms <- match' s s'
1276 return (mt ++ ms)
1277 match (PLet _ t ty s) (PLet _ t' ty' s') = do mt <- match' t t'
1278 mty <- match' ty ty'
1279 ms <- match' s s'
1280 return (mt ++ mty ++ ms)
1281 match (PHidden x) (PHidden y) = match' x y
1282 match (PUnifyLog x) y = match' x y
1283 match x (PUnifyLog y) = match' x y
1284 match Placeholder _ = return []
1285 match _ Placeholder = return []
1286 match (PResolveTC _) _ = return []
1287 match a b | a == b = return []
1288 | otherwise = LeftErr (a, b)
1290 checkRpts (RightOK ms) = check ms where
1291 check ((n,t):xs)
1292 | Just t' <- lookup n xs = if t/=t' && t/=Placeholder && t'/=Placeholder
1293 then Left (t, t')
1294 else check xs
1295 check (_:xs) = check xs
1296 check [] = Right ms
1297 checkRpts (LeftErr x) = Left x
1299substMatches :: [(Name, PTerm)] -> PTerm -> PTerm
1300substMatches ms = substMatchesShadow ms []
1302substMatchesShadow :: [(Name, PTerm)] -> [Name] -> PTerm -> PTerm
1303substMatchesShadow [] shs t = t
1304substMatchesShadow ((n,tm):ns) shs t
1305 = substMatchShadow n shs tm (substMatchesShadow ns shs t)
1307substMatch :: Name -> PTerm -> PTerm -> PTerm
1308substMatch n = substMatchShadow n []
1310substMatchShadow :: Name -> [Name] -> PTerm -> PTerm -> PTerm
1311substMatchShadow n shs tm t = sm shs t where
1312 sm xs (PRef _ n') | n == n' = tm
1313 sm xs (PLam x t sc) = PLam x (sm xs t) (sm xs sc)
1314 sm xs (PPi p x t sc)
1315 | x `elem` xs
1316 = let x' = nextName x in
1317 PPi p x' (sm (x':xs) (substMatch x (PRef (FC "" 0) x') t))
1318 (sm (x':xs) (substMatch x (PRef (FC "" 0) x') sc))
1319 | otherwise = PPi p x (sm xs t) (sm (x : xs) sc)
1320 sm xs (PApp f x as) = PApp f (sm xs x) (map (fmap (sm xs)) as)
1321 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
1322 sm xs (PEq f x y) = PEq f (sm xs x) (sm xs y)
1323 sm xs (PRewrite f x y tm) = PRewrite f (sm xs x) (sm xs y)
1324 (fmap (sm xs) tm)
1325 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
1326 sm xs (PPair f x y) = PPair f (sm xs x) (sm xs y)
1327 sm xs (PDPair f x t y) = PDPair f (sm xs x) (sm xs t) (sm xs y)
1328 sm xs (PAlternative a as) = PAlternative a (map (sm xs) as)
1329 sm xs (PHidden x) = PHidden (sm xs x)
1330 sm xs (PUnifyLog x) = PUnifyLog (sm xs x)
1331 sm xs x = x
1333shadow :: Name -> Name -> PTerm -> PTerm
1334shadow n n' t = sm t where
1335 sm (PRef fc x) | n == x = PRef fc n'
1336 sm (PLam x t sc) = PLam x (sm t) (sm sc)
1337 sm (PPi p x t sc) = PPi p x (sm t) (sm sc)
1338 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
1339 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
1340 sm (PEq f x y) = PEq f (sm x) (sm y)
1341 sm (PRewrite f x y tm) = PRewrite f (sm x) (sm y) (fmap sm tm)
1342 sm (PTyped x y) = PTyped (sm x) (sm y)
1343 sm (PPair f x y) = PPair f (sm x) (sm y)
1344 sm (PDPair f x t y) = PDPair f (sm x) (sm t) (sm y)
1345 sm (PAlternative a as) = PAlternative a (map sm as)
1346 sm (PHidden x) = PHidden (sm x)
1347 sm (PUnifyLog x) = PUnifyLog (sm x)
1348 sm x = x