on 4dddfaf help sign in
Idris-dev/src/Idris/AbsSyntax.hs
1363 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] }
64addTrans :: (Term, Term) -> Idris ()
65addTrans t = do i <- getIState
66 putIState $ i { idris_transforms = t : idris_transforms i }
68totcheck :: (FC, Name) -> Idris ()
69totcheck n = do i <- getIState; putIState $ i { idris_totcheck = idris_totcheck i ++ [n] }
71setFlags :: Name -> [FnOpt] -> Idris ()
72setFlags n fs = do i <- getIState; putIState $ i { idris_flags = addDef n fs (idris_flags i) }
74setAccessibility :: Name -> Accessibility -> Idris ()
75setAccessibility n a
76 = do i <- getIState
77 let ctxt = setAccess n a (tt_ctxt i)
78 putIState $ i { tt_ctxt = ctxt }
80setTotality :: Name -> Totality -> Idris ()
81setTotality n a
82 = do i <- getIState
83 let ctxt = setTotal n a (tt_ctxt i)
84 putIState $ i { tt_ctxt = ctxt }
86getTotality :: Name -> Idris Totality
87getTotality n
88 = do i <- getIState
89 case lookupTotal n (tt_ctxt i) of
90 [t] -> return t
91 _ -> return (Total [])
93-- Get coercions which might return the required type
94getCoercionsTo :: IState -> Type -> [Name]
95getCoercionsTo i ty =
96 let cs = idris_coercions i
97 (fn,_) = unApply (getRetTy ty) in
98 findCoercions fn cs
99 where findCoercions t [] = []
100 findCoercions t (n : ns) =
101 let ps = case lookupTy n (tt_ctxt i) of
102 [ty] -> case unApply (getRetTy ty) of
103 (t', _) ->
104 if t == t' then [n] else []
105 _ -> [] in
106 ps ++ findCoercions t ns
108addToCG :: Name -> CGInfo -> Idris ()
109addToCG n cg
110 = do i <- getIState
111 putIState $ i { idris_callgraph = addDef n cg (idris_callgraph i) }
113addCoercion :: Name -> Idris ()
114addCoercion n = do i <- getIState
115 putIState $ i { idris_coercions = n : idris_coercions i }
117addDocStr :: Name -> String -> Idris ()
118addDocStr n doc
119 = do i <- getIState
120 putIState $ i { idris_docstrings = addDef n doc (idris_docstrings i) }
122addToCalledG :: Name -> [Name] -> Idris ()
123addToCalledG n ns = return () -- TODO
125-- Add a class instance function. Dodgy hack: Put integer instances first in the
126-- list so they are resolved by default.
127-- Dodgy hack 2: put constraint chasers (@@) last
129addInstance :: Bool -> Name -> Name -> Idris ()
130addInstance int n i
131 = do ist <- getIState
132 case lookupCtxt n (idris_classes ist) of
133 [CI a b c d ins] ->
134 do let cs = addDef n (CI a b c d (addI i ins)) (idris_classes ist)
135 putIState $ ist { idris_classes = cs }
136 _ -> do let cs = addDef n (CI (MN 0 "none") [] [] [] [i]) (idris_classes ist)
137 putIState $ ist { idris_classes = cs }
138 where addI i ins | int = i : ins
139 | chaser n = ins ++ [i]
140 | otherwise = insI i ins
141 insI i [] = [i]
142 insI i (n : ns) | chaser n = i : n : ns
143 | otherwise = n : insI i ns
145 chaser (UN ('@':'@':_)) = True
146 chaser (NS n _) = chaser n
147 chaser _ = False
149addClass :: Name -> ClassInfo -> Idris ()
150addClass n i
151 = do ist <- getIState
152 let i' = case lookupCtxt n (idris_classes ist) of
153 [c] -> c { class_instances = class_instances i }
154 _ -> i
155 putIState $ ist { idris_classes = addDef n i' (idris_classes ist) }
157addIBC :: IBCWrite -> Idris ()
158addIBC ibc@(IBCDef n)
159 = do i <- getIState
160 when (notDef (ibc_write i)) $
161 putIState $ i { ibc_write = ibc : ibc_write i }
162 where notDef [] = True
163 notDef (IBCDef n': is) | n == n' = False
164 notDef (_ : is) = notDef is
165addIBC ibc = do i <- getIState; putIState $ i { ibc_write = ibc : ibc_write i }
167clearIBC :: Idris ()
168clearIBC = do i <- getIState; putIState $ i { ibc_write = [] }
170getHdrs :: Codegen -> Idris [String]
171getHdrs tgt = do i <- getIState; return (forCodegen tgt $ idris_hdrs i)
173setErrLine :: Int -> Idris ()
174setErrLine x = do i <- getIState;
175 case (errLine i) of
176 Nothing -> putIState $ i { errLine = Just x }
177 Just _ -> return ()
179clearErr :: Idris ()
180clearErr = do i <- getIState
181 putIState $ i { errLine = Nothing }
183getSO :: Idris (Maybe String)
184getSO = do i <- getIState
185 return (compiled_so i)
187setSO :: Maybe String -> Idris ()
188setSO s = do i <- getIState
189 putIState $ (i { compiled_so = s })
191getIState :: Idris IState
192getIState = get
194putIState :: IState -> Idris ()
195putIState = put
197getName :: Idris Int
198getName = do i <- getIState;
199 let idx = idris_name i;
200 putIState $ (i { idris_name = idx + 1 })
201 return idx
203checkUndefined :: FC -> Name -> Idris ()
204checkUndefined fc n
205 = do i <- getContext
206 case lookupTy n i of
207 (_:_) -> fail $ show fc ++ ":" ++
208 show n ++ " already defined"
209 _ -> return ()
211isUndefined :: FC -> Name -> Idris Bool
212isUndefined fc n
213 = do i <- getContext
214 case lookupTy n i of
215 (_:_) -> return False
216 _ -> return True
218setContext :: Context -> Idris ()
219setContext ctxt = do i <- getIState; putIState $ (i { tt_ctxt = ctxt } )
221updateContext :: (Context -> Context) -> Idris ()
222updateContext f = do i <- getIState; putIState $ (i { tt_ctxt = f (tt_ctxt i) } )
224addConstraints :: FC -> (Int, [UConstraint]) -> Idris ()
225addConstraints fc (v, cs)
226 = do i <- getIState
227 let ctxt = tt_ctxt i
228 let ctxt' = ctxt { uconstraints = cs ++ uconstraints ctxt,
229 next_tvar = v }
230 let ics = zip cs (repeat fc) ++ idris_constraints i
231 putIState $ i { tt_ctxt = ctxt', idris_constraints = ics }
233addDeferred = addDeferred' Ref
234addDeferredTyCon = addDeferred' (TCon 0 0)
236addDeferred' :: NameType -> [(Name, Type)] -> Idris ()
237addDeferred' nt ns
238 = do mapM_ (\(n, t) -> updateContext (addTyDecl n nt (tidyNames [] t))) ns
239 i <- getIState
240 putIState $ i { idris_metavars = map fst ns ++ idris_metavars i }
241 where tidyNames used (Bind (MN i x) b sc)
242 = let n' = uniqueName (UN x) used in
243 Bind n' b $ tidyNames (n':used) sc
244 tidyNames used (Bind n b sc)
245 = let n' = uniqueName n used in
246 Bind n' b $ tidyNames (n':used) sc
247 tidyNames used b = b
249solveDeferred :: Name -> Idris ()
250solveDeferred n = do i <- getIState
251 putIState $ i { idris_metavars = idris_metavars i \\ [n] }
253iResult :: String -> Idris ()
254iResult s = do i <- getIState
255 case idris_outputmode i of
256 RawOutput -> case s of
257 "" -> return ()
258 s -> liftIO $ putStrLn s
259 IdeSlave n ->
260 let good = SexpList [SymbolAtom "ok", toSExp s] in
261 liftIO $ putStrLn $ convSExp "return" good n
263iFail :: String -> Idris ()
264iFail s = do i <- getIState
265 case idris_outputmode i of
266 RawOutput -> case s of
267 "" -> return ()
268 s -> liftIO $ putStrLn s
269 IdeSlave n ->
270 let good = SexpList [SymbolAtom "error", toSExp s] in
271 liftIO . putStrLn $ convSExp "return" good n
273iputStrLn :: String -> Idris ()
274iputStrLn s = do i <- getIState
275 case idris_outputmode i of
276 RawOutput -> liftIO $ putStrLn s
277 IdeSlave n ->
278 case span (/=':') s of
279 (fn, ':':rest) -> case span isDigit rest of
280 ([], ':':msg) -> write
281 ([], msg) -> write
282 (num, ':':msg) -> iWarn (FC fn (read num)) msg
283 _ -> write
284 where write = liftIO . putStrLn $ convSExp "write-string" s n
286ideslavePutSExp :: SExpable a => String -> a -> Idris ()
287ideslavePutSExp cmd info = do i <- getIState
288 case idris_outputmode i of
289 IdeSlave n -> liftIO . putStrLn $ convSExp cmd info n
290 _ -> return ()
292-- this needs some typing magic and more structured output towards emacs
293iputGoal :: String -> Idris ()
294iputGoal s = do i <- getIState
295 case idris_outputmode i of
296 RawOutput -> liftIO $ putStrLn s
297 IdeSlave n -> liftIO . putStrLn $ convSExp "write-goal" s n
299isetPrompt :: String -> Idris ()
300isetPrompt p = do i <- getIState
301 case idris_outputmode i of
302 IdeSlave n -> liftIO . putStrLn $ convSExp "set-prompt" p n
304iWarn :: FC -> String -> Idris ()
305iWarn fc err = do i <- getIState
306 case idris_outputmode i of
307 RawOutput -> liftIO $ putStrLn (show fc ++ ":" ++ err)
308 IdeSlave n -> liftIO . putStrLn $ convSExp "warning" (fc_fname fc, fc_line fc, err) n
310setLogLevel :: Int -> Idris ()
311setLogLevel l = do i <- getIState
312 let opts = idris_options i
313 let opt' = opts { opt_logLevel = l }
314 putIState $ i { idris_options = opt' }
316setCmdLine :: [Opt] -> Idris ()
317setCmdLine opts = do i <- getIState
318 let iopts = idris_options i
319 putIState $ i { idris_options = iopts { opt_cmdline = opts } }
321getDumpDefun :: Idris (Maybe FilePath)
322getDumpDefun = do i <- getIState
323 return $ findC (opt_cmdline (idris_options i))
324 where findC [] = Nothing
325 findC (DumpDefun x : _) = Just x
326 findC (_ : xs) = findC xs
328getDumpCases :: Idris (Maybe FilePath)
329getDumpCases = do i <- getIState
330 return $ findC (opt_cmdline (idris_options i))
331 where findC [] = Nothing
332 findC (DumpCases x : _) = Just x
333 findC (_ : xs) = findC xs
335logLevel :: Idris Int
336logLevel = do i <- getIState
337 return (opt_logLevel (idris_options i))
339setErrContext :: Bool -> Idris ()
340setErrContext t = do i <- getIState
341 let opts = idris_options i
342 let opt' = opts { opt_errContext = t }
343 putIState $ i { idris_options = opt' }
345errContext :: Idris Bool
346errContext = do i <- getIState
347 return (opt_errContext (idris_options i))
349useREPL :: Idris Bool
350useREPL = do i <- getIState
351 return (opt_repl (idris_options i))
353setREPL :: Bool -> Idris ()
354setREPL t = do i <- getIState
355 let opts = idris_options i
356 let opt' = opts { opt_repl = t }
357 putIState $ i { idris_options = opt' }
359setQuiet :: Bool -> Idris ()
360setQuiet q = do i <- getIState
361 let opts = idris_options i
362 let opt' = opts { opt_quiet = q }
363 putIState $ i { idris_options = opt' }
365getQuiet :: Idris Bool
366getQuiet = do i <- getIState
367 let opts = idris_options i
368 return (opt_quiet opts)
370setCodegen :: Codegen -> Idris ()
371setCodegen t = do i <- getIState
372 let opts = idris_options i
373 let opt' = opts { opt_codegen = t }
374 putIState $ i { idris_options = opt' }
376codegen :: Idris Codegen
377codegen = do i <- getIState
378 return (opt_codegen (idris_options i))
380setOutputTy :: OutputType -> Idris ()
381setOutputTy t = do i <- getIState
382 let opts = idris_options i
383 let opt' = opts { opt_outputTy = t }
384 putIState $ i { idris_options = opt' }
386outputTy :: Idris OutputType
387outputTy = do i <- getIState
388 return $ opt_outputTy $ idris_options i
390setIdeSlave :: Bool -> Idris ()
391setIdeSlave True = do i <- getIState
392 putIState $ i { idris_outputmode = (IdeSlave 0) }
393setIdeSlave False = return ()
395setTargetTriple :: String -> Idris ()
396setTargetTriple t = do i <- getIState
397 let opts = idris_options i
398 opt' = opts { opt_triple = t }
399 putIState $ i { idris_options = opt' }
401targetTriple :: Idris String
402targetTriple = do i <- getIState
403 return (opt_triple (idris_options i))
405setTargetCPU :: String -> Idris ()
406setTargetCPU t = do i <- getIState
407 let opts = idris_options i
408 opt' = opts { opt_cpu = t }
409 putIState $ i { idris_options = opt' }
411targetCPU :: Idris String
412targetCPU = do i <- getIState
413 return (opt_cpu (idris_options i))
415setOptLevel :: Int -> Idris ()
416setOptLevel t = do i <- getIState
417 let opts = idris_options i
418 opt' = opts { opt_optLevel = t }
419 putIState $ i { idris_options = opt' }
421optLevel :: Idris Int
422optLevel = do i <- getIState
423 return (opt_optLevel (idris_options i))
425verbose :: Idris Bool
426verbose = do i <- getIState
427 return (opt_verbose (idris_options i))
429setVerbose :: Bool -> Idris ()
430setVerbose t = do i <- getIState
431 let opts = idris_options i
432 let opt' = opts { opt_verbose = t }
433 putIState $ i { idris_options = opt' }
435typeInType :: Idris Bool
436typeInType = do i <- getIState
437 return (opt_typeintype (idris_options i))
439setTypeInType :: Bool -> Idris ()
440setTypeInType t = do i <- getIState
441 let opts = idris_options i
442 let opt' = opts { opt_typeintype = t }
443 putIState $ i { idris_options = opt' }
445coverage :: Idris Bool
446coverage = do i <- getIState
447 return (opt_coverage (idris_options i))
449setCoverage :: Bool -> Idris ()
450setCoverage t = do i <- getIState
451 let opts = idris_options i
452 let opt' = opts { opt_coverage = t }
453 putIState $ i { idris_options = opt' }
455setIBCSubDir :: FilePath -> Idris ()
456setIBCSubDir fp = do i <- getIState
457 let opts = idris_options i
458 let opt' = opts { opt_ibcsubdir = fp }
459 putIState $ i { idris_options = opt' }
461valIBCSubDir :: IState -> Idris FilePath
462valIBCSubDir i = return (opt_ibcsubdir (idris_options i))
464addImportDir :: FilePath -> Idris ()
465addImportDir fp = do i <- getIState
466 let opts = idris_options i
467 let opt' = opts { opt_importdirs = fp : opt_importdirs opts }
468 putIState $ i { idris_options = opt' }
470setImportDirs :: [FilePath] -> Idris ()
471setImportDirs fps = do i <- getIState
472 let opts = idris_options i
473 let opt' = opts { opt_importdirs = fps }
474 putIState $ i { idris_options = opt' }
476allImportDirs :: IState -> Idris [FilePath]
477allImportDirs i = do let optdirs = opt_importdirs (idris_options i)
478 return ("." : reverse optdirs)
480impShow :: Idris Bool
481impShow = do i <- getIState
482 return (opt_showimp (idris_options i))
484setImpShow :: Bool -> Idris ()
485setImpShow t = do i <- getIState
486 let opts = idris_options i
487 let opt' = opts { opt_showimp = t }
488 putIState $ i { idris_options = opt' }
490logLvl :: Int -> String -> Idris ()
491logLvl l str = do i <- getIState
492 let lvl = opt_logLevel (idris_options i)
493 when (lvl >= l)
494 $ do liftIO (putStrLn str)
495 putIState $ i { idris_log = idris_log i ++ str ++ "\n" }
497cmdOptType :: Opt -> Idris Bool
498cmdOptType x = do i <- getIState
499 return $ x `elem` opt_cmdline (idris_options i)
501iLOG :: String -> Idris ()
502iLOG = logLvl 1
504noErrors :: Idris Bool
505noErrors = do i <- getIState
506 case errLine i of
507 Nothing -> return True
508 _ -> return False
510setTypeCase :: Bool -> Idris ()
511setTypeCase t = do i <- getIState
512 let opts = idris_options i
513 let opt' = opts { opt_typecase = t }
514 putIState $ i { idris_options = opt' }
517-- For inferring types of things
519bi = FC "builtin" 0
521inferTy = MN 0 "__Infer"
522inferCon = MN 0 "__infer"
523inferDecl = PDatadecl inferTy
524 PType
525 [("", inferCon, PPi impl (MN 0 "A") PType (
526 PPi expl (MN 0 "a") (PRef bi (MN 0 "A"))
527 (PRef bi inferTy)), bi)]
529infTerm t = PApp bi (PRef bi inferCon) [pimp (MN 0 "A") Placeholder, pexp t]
530infP = P (TCon 6 0) inferTy (TType (UVal 0))
532getInferTerm, getInferType :: Term -> Term
533getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
534getInferTerm (App (App _ _) tm) = tm
535getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
537getInferType (Bind n b sc) = Bind n b $ getInferType sc
538getInferType (App (App _ ty) _) = ty
540-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
542primNames = [unitTy, unitCon,
543 falseTy, pairTy, pairCon,
544 eqTy, eqCon, inferTy, inferCon]
546unitTy = MN 0 "__Unit"
547unitCon = MN 0 "__II"
548unitDecl = PDatadecl unitTy PType
549 [("", unitCon, PRef bi unitTy, bi)]
551falseTy = MN 0 "__False"
552falseDecl = PDatadecl falseTy PType []
554pairTy = MN 0 "__Pair"
555pairCon = MN 0 "__MkPair"
556pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
557 [("", pairCon, PPi impl (n "A") PType (
558 PPi impl (n "B") PType (
559 PPi expl (n "a") (PRef bi (n "A")) (
560 PPi expl (n "b") (PRef bi (n "B"))
561 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
562 pexp (PRef bi (n "B"))])))), bi)]
563 where n a = MN 0 a
565eqTy = UN "="
566eqCon = UN "refl"
567eqDecl = PDatadecl eqTy (piBind [(n "a", PType), (n "b", PType),
568 (n "x", PRef bi (n "a")), (n "y", PRef bi (n "b"))]
569 PType)
570 [("", eqCon, PPi impl (n "a") PType (
571 PPi impl (n "x") (PRef bi (n "a"))
572 (PApp bi (PRef bi eqTy) [pimp (n "a") Placeholder,
573 pimp (n "b") Placeholder,
574 pexp (PRef bi (n "x")),
575 pexp (PRef bi (n "x"))])), bi)]
576 where n a = MN 0 a
578-- Defined in builtins.idr
579sigmaTy = UN "Exists"
580existsCon = UN "Ex_intro"
582piBind :: [(Name, PTerm)] -> PTerm -> PTerm
583piBind = piBindp expl
585piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
586piBindp p [] t = t
587piBindp p ((n, ty):ns) t = PPi p n ty (piBind ns t)
589-- Dealing with parameters
591expandParams :: (Name -> Name) -> [(Name, PTerm)] ->
592 [Name] -> -- all names
593 [Name] -> -- names with no declaration
594 PTerm -> PTerm
595expandParams dec ps ns infs tm = en tm
596 where
597 -- if we shadow a name (say in a lambda binding) that is used in a call to
598 -- a lifted function, we need access to both names - once in the scope of the
599 -- binding and once to call the lifted functions. So we'll explicitly shadow
600 -- it. (Yes, it's a hack. The alternative would be to resolve names earlier
601 -- but we didn't...)
603 mkShadow (UN n) = MN 0 n
604 mkShadow (MN i n) = MN (i+1) n
605 mkShadow (NS x s) = NS (mkShadow x) s
607 en (PLam n t s)
608 | n `elem` map fst ps
609 = let n' = mkShadow n in
610 PLam n' (en t) (en (shadow n n' s))
611 | otherwise = PLam n (en t) (en s)
612 en (PPi p n t s)
613 | n `elem` map fst ps
614 = let n' = mkShadow n in
615 PPi p n' (en t) (en (shadow n n' s))
616 | otherwise = PPi p n (en t) (en s)
617 en (PLet n ty v s)
618 | n `elem` map fst ps
619 = let n' = mkShadow n in
620 PLet n' (en ty) (en v) (en (shadow n n' s))
621 | otherwise = PLet n (en ty) (en v) (en s)
622 en (PEq f l r) = PEq f (en l) (en r)
623 en (PRewrite f l r g) = PRewrite f (en l) (en r) (fmap en g)
624 en (PTyped l r) = PTyped (en l) (en r)
625 en (PPair f l r) = PPair f (en l) (en r)
626 en (PDPair f l t r) = PDPair f (en l) (en t) (en r)
627 en (PAlternative a as) = PAlternative a (map en as)
628 en (PHidden t) = PHidden (en t)
629 en (PUnifyLog t) = PUnifyLog (en t)
630 en (PDoBlock ds) = PDoBlock (map (fmap en) ds)
631 en (PProof ts) = PProof (map (fmap en) ts)
632 en (PTactics ts) = PTactics (map (fmap en) ts)
634 en (PQuote (Var n))
635 | n `nselem` ns = PQuote (Var (dec n))
636 en (PApp fc (PInferRef fc' n) as)
637 | n `nselem` ns = PApp fc (PInferRef fc' (dec n))
638 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
639 en (PApp fc (PRef fc' n) as)
640 | n `elem` infs = PApp fc (PInferRef fc' (dec n))
641 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
642 | n `nselem` ns = PApp fc (PRef fc' (dec n))
643 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
644 en (PRef fc n)
645 | n `elem` infs = PApp fc (PInferRef fc (dec n))
646 (map (pexp . (PRef fc)) (map fst ps))
647 | n `nselem` ns = PApp fc (PRef fc (dec n))
648 (map (pexp . (PRef fc)) (map fst ps))
649 en (PInferRef fc n)
650 | n `nselem` ns = PApp fc (PInferRef fc (dec n))
651 (map (pexp . (PRef fc)) (map fst ps))
652 en (PApp fc f as) = PApp fc (en f) (map (fmap en) as)
653 en (PCase fc c os) = PCase fc (en c) (map (pmap en) os)
654 en t = t
656 nselem x [] = False
657 nselem x (y : xs) | nseq x y = True
658 | otherwise = nselem x xs
660 nseq x y = nsroot x == nsroot y
662expandParamsD :: Bool -> -- True = RHS only
663 IState ->
664 (Name -> Name) -> [(Name, PTerm)] -> [Name] -> PDecl -> PDecl
665expandParamsD rhsonly ist dec ps ns (PTy doc syn fc o n ty)
666 = if n `elem` ns && (not rhsonly)
667 then -- trace (show (n, expandParams dec ps ns ty)) $
668 PTy doc syn fc o (dec n) (piBind ps (expandParams dec ps ns [] ty))
669 else --trace (show (n, expandParams dec ps ns ty)) $
670 PTy doc syn fc o n (expandParams dec ps ns [] ty)
671expandParamsD rhsonly ist dec ps ns (PPostulate doc syn fc o n ty)
672 = if n `elem` ns && (not rhsonly)
673 then -- trace (show (n, expandParams dec ps ns ty)) $
674 PPostulate doc syn fc o (dec n) (piBind ps
675 (expandParams dec ps ns [] ty))
676 else --trace (show (n, expandParams dec ps ns ty)) $
677 PPostulate doc syn fc o n (expandParams dec ps ns [] ty)
678expandParamsD rhsonly ist dec ps ns (PClauses fc opts n cs)
679 = let n' = if n `elem` ns then dec n else n in
680 PClauses fc opts n' (map expandParamsC cs)
681 where
682 expandParamsC (PClause fc n lhs ws rhs ds)
683 = let -- ps' = updateps True (namesIn ist rhs) (zip ps [0..])
684 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
685 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
686 n' = if n `elem` ns then dec n else n in
687 PClause fc n' lhs'
688 (map (expandParams dec ps'' ns []) ws)
689 (expandParams dec ps'' ns [] rhs)
690 (map (expandParamsD True ist dec ps'' ns) ds)
691 expandParamsC (PWith fc n lhs ws wval ds)
692 = let -- ps' = updateps True (namesIn ist wval) (zip ps [0..])
693 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
694 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
695 n' = if n `elem` ns then dec n else n in
696 PWith fc n' lhs'
697 (map (expandParams dec ps'' ns []) ws)
698 (expandParams dec ps'' ns [] wval)
699 (map (expandParamsD rhsonly ist dec ps'' ns) ds)
700 updateps yn nm [] = []
701 updateps yn nm (((a, t), i):as)
702 | (a `elem` nm) == yn = (a, t) : updateps yn nm as
703 | otherwise = (MN i (show n ++ "_u"), t) : updateps yn nm as
704expandParamsD rhs ist dec ps ns (PData doc syn fc co pd)
705 = PData doc syn fc co (expandPData pd)
706 where
707 -- just do the type decl, leave constructors alone (parameters will be
708 -- added implicitly)
709 expandPData (PDatadecl n ty cons)
710 = if n `elem` ns
711 then PDatadecl (dec n) (piBind ps (expandParams dec ps ns [] ty))
712 (map econ cons)
713 else PDatadecl n (expandParams dec ps ns [] ty) (map econ cons)
714 econ (doc, n, t, fc)
715 = (doc, dec n, piBindp expl ps (expandParams dec ps ns [] t), fc)
716expandParamsD rhs ist dec ps ns (PParams f params pds)
717 = PParams f (ps ++ map (mapsnd (expandParams dec ps ns [])) params)
718 (map (expandParamsD True ist dec ps ns) pds)
719-- (map (expandParamsD ist dec ps ns) pds)
720expandParamsD rhs ist dec ps ns (PMutual f pds)
721 = PMutual f (map (expandParamsD rhs ist dec ps ns) pds)
722expandParamsD rhs ist dec ps ns (PClass doc info f cs n params decls)
723 = PClass doc info f
724 (map (expandParams dec ps ns []) cs)
725 n
726 (map (mapsnd (expandParams dec ps ns [])) params)
727 (map (expandParamsD rhs ist dec ps ns) decls)
728expandParamsD rhs ist dec ps ns (PInstance info f cs n params ty cn decls)
729 = PInstance info f
730 (map (expandParams dec ps ns []) cs)
731 n
732 (map (expandParams dec ps ns []) params)
733 (expandParams dec ps ns [] ty)
734 cn
735 (map (expandParamsD rhs ist dec ps ns) decls)
736expandParamsD rhs ist dec ps ns d = d
738mapsnd f (x, t) = (x, f t)
740-- Calculate a priority for a type, for deciding elaboration order
741-- * if it's just a type variable or concrete type, do it early (0)
742-- * if there's only type variables and injective constructors, do it next (1)
743-- * if there's a function type, next (2)
744-- * finally, everything else (3)
746getPriority :: IState -> PTerm -> Int
747getPriority i tm = 1 -- pri tm
748 where
749 pri (PRef _ n) =
750 case lookupP n (tt_ctxt i) of
751 ((P (DCon _ _) _ _):_) -> 1
752 ((P (TCon _ _) _ _):_) -> 1
753 ((P Ref _ _):_) -> 1
754 [] -> 0 -- must be locally bound, if it's not an error...
755 pri (PPi _ _ x y) = max 5 (max (pri x) (pri y))
756 pri (PTrue _) = 0
757 pri (PFalse _) = 0
758 pri (PRefl _ _) = 1
759 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
760 pri (PRewrite _ l r _) = max 1 (max (pri l) (pri r))
761 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
762 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
763 pri (PTyped l r) = pri l
764 pri (PPair _ l r) = max 1 (max (pri l) (pri r))
765 pri (PDPair _ l t r) = max 1 (max (pri l) (max (pri t) (pri r)))
766 pri (PAlternative a as) = maximum (map pri as)
767 pri (PConstant _) = 0
768 pri Placeholder = 1
769 pri _ = 3
771addStatics :: Name -> Term -> PTerm -> Idris ()
772addStatics n tm ptm =
773 do let (statics, dynamics) = initStatics tm ptm
774 let stnames = nub $ concatMap freeNames (map snd statics)
775 let dnames = nub $ concatMap freeNames (map snd dynamics)
776 when (not (null statics)) $
777 logLvl 7 $ show n ++ " " ++ show statics ++ "\n" ++ show dynamics
778 ++ "\n" ++ show stnames ++ "\n" ++ show dnames
779 let statics' = nub $ map fst statics ++
780 filter (\x -> not (elem x dnames)) stnames
781 let stpos = staticList statics' tm
782 i <- getIState
783 putIState $ i { idris_statics = addDef n stpos (idris_statics i) }
784 addIBC (IBCStatic n)
785 where
786 initStatics (Bind n (Pi ty) sc) (PPi p _ _ s)
787 = let (static, dynamic) = initStatics (instantiate (P Bound n ty) sc) s in
788 if pstatic p == Static then ((n, ty) : static, dynamic)
789 else (static, (n, ty) : dynamic)
790 initStatics t pt = ([], [])
792 staticList sts (Bind n (Pi _) sc) = (n `elem` sts) : staticList sts sc
793 staticList _ _ = []
795-- Dealing with implicit arguments
797-- Add constraint bindings from using block
799addUsingConstraints :: SyntaxInfo -> FC -> PTerm -> Idris PTerm
800addUsingConstraints syn fc t
801 = do ist <- get
802 let ns = namesIn [] ist t
803 let cs = getConstraints t -- check declared constraints
804 let addconsts = uconsts \\ cs
805 -- if all names in the arguments of addconsts appear in ns,
806 -- add the constraint implicitly
807 return (doAdd addconsts ns t)
808 where uconsts = filter uconst (using syn)
809 uconst (UConstraint _ _) = True
810 uconst _ = False
812 doAdd [] _ t = t
813 -- if all of args in ns, then add it
814 doAdd (UConstraint c args : cs) ns t
815 | all (\n -> elem n ns) args
816 = PPi (Constraint False Dynamic "") (MN 0 "cu")
817 (mkConst c args) (doAdd cs ns t)
818 | otherwise = doAdd cs ns t
820 mkConst c args = PApp fc (PRef fc c)
821 (map (\n -> PExp 0 False (PRef fc n) "") args)
823 getConstraints (PPi (Constraint _ _ _) _ c sc)
824 = getcapp c ++ getConstraints sc
825 getConstraints (PPi _ _ c sc) = getConstraints sc
826 getConstraints _ = []
828 getcapp (PApp _ (PRef _ c) args)
829 = do ns <- mapM getName args
830 return (UConstraint c ns)
831 getcapp _ = []
833 getName (PExp _ _ (PRef _ n) _) = return n
834 getName _ = []
836-- Add implicit Pi bindings for any names in the term which appear in an
837-- argument position.
839-- This has become a right mess already. Better redo it some time...
841implicit :: SyntaxInfo -> Name -> PTerm -> Idris PTerm
842implicit syn n ptm = implicit' syn [] n ptm
844implicit' :: SyntaxInfo -> [Name] -> Name -> PTerm -> Idris PTerm
845implicit' syn ignore n ptm
846 = do i <- getIState
847 let (tm', impdata) = implicitise syn ignore i ptm
848-- let (tm'', spos) = findStatics i tm'
849 putIState $ i { idris_implicits = addDef n impdata (idris_implicits i) }
850 addIBC (IBCImp n)
851 logLvl 5 ("Implicit " ++ show n ++ " " ++ show impdata)
852-- i <- get
853-- putIState $ i { idris_statics = addDef n spos (idris_statics i) }
854 return tm'
856implicitise :: SyntaxInfo -> [Name] -> IState -> PTerm -> (PTerm, [PArg])
857implicitise syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
858 let (declimps, ns') = execState (imps True [] tm) ([], [])
859 ns = filter (\n -> implicitable n || elem n (map fst uvars)) $
860 ns' \\ (map fst pvars ++ no_imp syn ++ ignore)
861 nsOrder = filter (not . inUsing) ns ++ filter inUsing ns in
862 if null ns
863 then (tm, reverse declimps)
864 else implicitise syn ignore ist (pibind uvars nsOrder tm)
865 where
866 uvars = map ipair (filter uimplicit (using syn))
867 pvars = syn_params syn
869 inUsing n = n `elem` map fst uvars
871 ipair (UImplicit x y) = (x, y)
872 uimplicit (UImplicit _ _) = True
873 uimplicit _ = False
875 dropAll (x:xs) ys | x `elem` ys = dropAll xs ys
876 | otherwise = x : dropAll xs ys
877 dropAll [] ys = []
879 imps top env (PApp _ f as)
880 = do (decls, ns) <- get
881 let isn = concatMap (namesIn uvars ist) (map getTm as)
882 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
883 imps top env (PPi (Imp l _ doc) n ty sc)
884 = do let isn = nub (namesIn uvars ist ty) `dropAll` [n]
885 (decls , ns) <- get
886 put (PImp (getPriority ist ty) l n ty doc : decls,
887 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
888 imps True (n:env) sc
889 imps top env (PPi (Exp l _ doc) n ty sc)
890 = do let isn = nub (namesIn uvars ist ty ++ case sc of
891 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
892 _ -> [])
893 (decls, ns) <- get -- ignore decls in HO types
894 put (PExp (getPriority ist ty) l ty doc : decls,
895 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
896 imps True (n:env) sc
897 imps top env (PPi (Constraint l _ doc) n ty sc)
898 = do let isn = nub (namesIn uvars ist ty ++ case sc of
899 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
900 _ -> [])
901 (decls, ns) <- get -- ignore decls in HO types
902 put (PConstraint 10 l ty doc : decls,
903 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
904 imps True (n:env) sc
905 imps top env (PPi (TacImp l _ scr doc) n ty sc)
906 = do let isn = nub (namesIn uvars ist ty ++ case sc of
907 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
908 _ -> [])
909 (decls, ns) <- get -- ignore decls in HO types
910 put (PTacImplicit 10 l n scr ty doc : decls,
911 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
912 imps True (n:env) sc
913 imps top env (PEq _ 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 (PRewrite _ l r _)
918 = do (decls, ns) <- get
919 let isn = namesIn uvars ist l ++ namesIn uvars ist r
920 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
921 imps top env (PTyped l r)
922 = imps top env l
923 imps top env (PPair _ l r)
924 = do (decls, ns) <- get
925 let isn = namesIn uvars ist l ++ namesIn uvars ist r
926 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
927 imps top env (PDPair _ (PRef _ n) t r)
928 = do (decls, ns) <- get
929 let isn = nub (namesIn uvars ist t ++ namesIn uvars ist r) \\ [n]
930 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
931 imps top env (PDPair _ l t r)
932 = do (decls, ns) <- get
933 let isn = namesIn uvars ist l ++ namesIn uvars ist t ++
934 namesIn uvars ist r
935 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
936 imps top env (PAlternative a as)
937 = do (decls, ns) <- get
938 let isn = concatMap (namesIn uvars ist) as
939 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
940 imps top env (PLam n ty sc)
941 = do imps False env ty
942 imps False (n:env) sc
943 imps top env (PHidden tm) = imps False env tm
944 imps top env (PUnifyLog tm) = imps False env tm
945 imps top env _ = return ()
947 pibind using [] sc = sc
948 pibind using (n:ns) sc
949 = case lookup n using of
950 Just ty -> PPi (Imp False Dynamic "") n ty (pibind using ns sc)
951 Nothing -> PPi (Imp False Dynamic "") n Placeholder
952 (pibind using ns sc)
954-- Add implicit arguments in function calls
955addImplPat :: IState -> PTerm -> PTerm
956addImplPat = addImpl' True [] []
958addImplBound :: IState -> [Name] -> PTerm -> PTerm
959addImplBound ist ns = addImpl' False ns [] ist
961addImplBoundInf :: IState -> [Name] -> [Name] -> PTerm -> PTerm
962addImplBoundInf ist ns inf = addImpl' False ns inf ist
964addImpl :: IState -> PTerm -> PTerm
965addImpl = addImpl' False [] []
967-- TODO: in patterns, don't add implicits to function names guarded by constructors
968-- and *not* inside a PHidden
970addImpl' :: Bool -> [Name] -> [Name] -> IState -> PTerm -> PTerm
971addImpl' inpat env infns ist ptm = ai (zip env (repeat Nothing)) ptm
972 where
973 ai env (PRef fc f)
974 | f `elem` infns = PInferRef fc f
975 | not (f `elem` map fst env) = handleErr $ aiFn inpat inpat ist fc f []
976 ai env (PHidden (PRef fc f))
977 | not (f `elem` map fst env) = handleErr $ aiFn inpat False ist fc f []
978 ai env (PEq fc l r) = let l' = ai env l
979 r' = ai env r in
980 PEq fc l' r'
981 ai env (PRewrite fc l r g) = let l' = ai env l
982 r' = ai env r
983 g' = fmap (ai env) g in
984 PRewrite fc l' r' g'
985 ai env (PTyped l r) = let l' = ai env l
986 r' = ai env r in
987 PTyped l' r'
988 ai env (PPair fc l r) = let l' = ai env l
989 r' = ai env r in
990 PPair fc l' r'
991 ai env (PDPair fc l t r) = let l' = ai env l
992 t' = ai env t
993 r' = ai env r in
994 PDPair fc l' t' r'
995 ai env (PAlternative a as) = let as' = map (ai env) as in
996 PAlternative a as'
997 ai env (PApp fc (PInferRef _ f) as)
998 = let as' = map (fmap (ai env)) as in
999 PApp fc (PInferRef fc f) as'
1000 ai env (PApp fc ftm@(PRef _ f) as)
1001 | f `elem` infns = ai env (PApp fc (PInferRef fc f) as)
1002 | not (f `elem` map fst env)
1003 = let as' = map (fmap (ai env)) as in
1004 handleErr $ aiFn inpat False ist fc f as'
1005 | Just (Just ty) <- lookup f env
1006 = let as' = map (fmap (ai env)) as
1007 arity = getPArity ty in
1008 mkPApp fc arity ftm as'
1009 ai env (PApp fc f as) = let f' = ai env f
1010 as' = map (fmap (ai env)) as in
1011 mkPApp fc 1 f' as'
1012 ai env (PCase fc c os) = let c' = ai env c
1013 os' = map (pmap (ai env)) os in
1014 PCase fc c' os'
1015 ai env (PLam n ty sc) = let ty' = ai env ty
1016 sc' = ai ((n, Just ty):env) sc in
1017 PLam n ty' sc'
1018 ai env (PLet n ty val sc)
1019 = let ty' = ai env ty
1020 val' = ai env val
1021 sc' = ai ((n, Just ty):env) sc in
1022 PLet n ty' val' sc'
1023 ai env (PPi p n ty sc) = let ty' = ai env ty
1024 sc' = ai ((n, Just ty):env) sc in
1025 PPi p n ty' sc'
1026 ai env (PHidden tm) = PHidden (ai env tm)
1027 ai env (PProof ts) = PProof (map (fmap (ai env)) ts)
1028 ai env (PTactics ts) = PTactics (map (fmap (ai env)) ts)
1029 ai env (PUnifyLog tm) = PUnifyLog (ai env tm)
1030 ai env tm = tm
1032 handleErr (Left err) = PElabError err
1033 handleErr (Right x) = x
1035-- if in a pattern, and there are no arguments, and there's no possible
1036-- names with zero explicit arguments, don't add implicits.
1038aiFn :: Bool -> Bool -> IState -> FC -> Name -> [PArg] -> Either Err PTerm
1039aiFn inpat True ist fc f []
1040 = case lookupDef f (tt_ctxt ist) of
1041 [] -> Right $ PPatvar fc f
1042 alts -> let ialts = lookupCtxt f (idris_implicits ist) in
1043 -- trace (show f ++ " " ++ show (fc, any (all imp) ialts, ialts, any constructor alts)) $
1044 if (not (vname f) || tcname f
1045 || any constructor alts || any allImp ialts)
1046 then aiFn inpat False ist fc f [] -- use it as a constructor
1047 else Right $ PPatvar fc f
1048 where imp (PExp _ _ _ _) = False
1049 imp _ = True
1050 allImp [] = False
1051 allImp xs = all imp xs
1052 constructor (TyDecl (DCon _ _) _) = True
1053 constructor _ = False
1055 vname (UN n) = True -- non qualified
1056 vname _ = False
1058aiFn inpat expat ist fc f as
1059 | f `elem` primNames = Right $ PApp fc (PRef fc f) as
1060aiFn inpat expat ist fc f as
1061 -- This is where namespaces get resolved by adding PAlternative
1062 = case lookupCtxtName f (idris_implicits ist) of
1063 [(f',ns)] -> Right $ mkPApp fc (length ns) (PRef fc f') (insertImpl ns as)
1064 [] -> if f `elem` idris_metavars ist
1065 then Right $ PApp fc (PRef fc f) as
1066 else Right $ mkPApp fc (length as) (PRef fc f) as
1067 alts -> Right $
1068 PAlternative True $
1069 map (\(f', ns) -> mkPApp fc (length ns) (PRef fc f')
1070 (insertImpl ns as)) alts
1071 where
1072 insertImpl :: [PArg] -> [PArg] -> [PArg]
1073 insertImpl (PExp p l ty _ : ps) (PExp _ _ tm d : given) =
1074 PExp p l tm d : insertImpl ps given
1075 insertImpl (PConstraint p l ty _ : ps) (PConstraint _ _ tm d : given) =
1076 PConstraint p l tm d : insertImpl ps given
1077 insertImpl (PConstraint p l ty d : ps) given =
1078 PConstraint p l (PResolveTC fc) d : insertImpl ps given
1079 insertImpl (PImp p l n ty d : ps) given =
1080 case find n given [] of
1081 Just (tm, given') -> PImp p l n tm "" : insertImpl ps given'
1082 Nothing -> PImp p l n Placeholder "" : insertImpl ps given
1083 insertImpl (PTacImplicit p l n sc ty d : ps) given =
1084 case find n given [] of
1085 Just (tm, given') -> PTacImplicit p l n sc tm "" : insertImpl ps given'
1086 Nothing -> if inpat
1087 then PTacImplicit p l n sc Placeholder "" : insertImpl ps given
1088 else PTacImplicit p l n sc sc "" : insertImpl ps given
1089 insertImpl expected [] = []
1090 insertImpl _ given = given
1092 find n [] acc = Nothing
1093 find n (PImp _ _ n' t _ : gs) acc
1094 | n == n' = Just (t, reverse acc ++ gs)
1095 find n (PTacImplicit _ _ n' _ t _ : gs) acc
1096 | n == n' = Just (t, reverse acc ++ gs)
1097 find n (g : gs) acc = find n gs (g : acc)
1099-- replace non-linear occurrences with _
1100-- ASSUMPTION: This is called before adding 'alternatives' because otherwise
1101-- it is hard to get right!
1103stripLinear :: IState -> PTerm -> PTerm
1104stripLinear i tm = evalState (sl tm) [] where
1105 sl :: PTerm -> State [Name] PTerm
1106 sl (PRef fc f)
1107 | (_:_) <- lookupTy f (tt_ctxt i)
1108 = return $ PRef fc f
1109 | otherwise = do ns <- get
1110 if (f `elem` ns)
1111 then return Placeholder
1112 else do put (f : ns)
1113 return (PRef fc f)
1114 sl (PPatvar fc f)
1115 = do ns <- get
1116 if (f `elem` ns)
1117 then return Placeholder
1118 else do put (f : ns)
1119 return (PPatvar fc f)
1120 sl (PApp fc fn args) = do fn' <- sl fn
1121 args' <- mapM slA args
1122 return $ PApp fc fn' args'
1123 where slA (PImp p l n t d) = do t' <- sl t
1124 return $ PImp p l n t' d
1125 slA (PExp p l t d) = do t' <- sl t
1126 return $ PExp p l t' d
1127 slA (PConstraint p l t d)
1128 = do t' <- sl t
1129 return $ PConstraint p l t' d
1130 slA (PTacImplicit p l n sc t d)
1131 = do t' <- sl t
1132 return $ PTacImplicit p l n sc t' d
1133 sl x = return x
1135mkPApp fc a f [] = f
1136mkPApp fc a f as = let rest = drop a as in
1137 appRest fc (PApp fc f (take a as)) rest
1138 where
1139 appRest fc f [] = f
1140 appRest fc f (a : as) = appRest fc (PApp fc f [a]) as
1142-- Find 'static' argument positions
1143-- (the declared ones, plus any names in argument position in the declared
1144-- statics)
1145-- FIXME: It's possible that this really has to happen after elaboration
1147findStatics :: IState -> PTerm -> (PTerm, [Bool])
1148findStatics ist tm = trace (showImp True tm) $
1149 let (ns, ss) = fs tm in
1150 runState (pos ns ss tm) []
1151 where fs (PPi p n t sc)
1152 | Static <- pstatic p
1153 = let (ns, ss) = fs sc in
1154 (namesIn [] ist t : ns, n : ss)
1155 | otherwise = let (ns, ss) = fs sc in
1156 (ns, ss)
1157 fs _ = ([], [])
1159 inOne n ns = length (filter id (map (elem n) ns)) == 1
1161 pos ns ss (PPi p n t sc)
1162 | elem n ss = do sc' <- pos ns ss sc
1163 spos <- get
1164 put (True : spos)
1165 return (PPi (p { pstatic = Static }) n t sc')
1166 | otherwise = do sc' <- pos ns ss sc
1167 spos <- get
1168 put (False : spos)
1169 return (PPi p n t sc')
1170 pos ns ss t = return t
1172-- Debugging/logging stuff
1174dumpDecls :: [PDecl] -> String
1175dumpDecls [] = ""
1176dumpDecls (d:ds) = dumpDecl d ++ "\n" ++ dumpDecls ds
1178dumpDecl (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
1179dumpDecl (PTy _ _ _ _ n t) = "tydecl " ++ show n ++ " : " ++ showImp True t
1180dumpDecl (PClauses _ _ n cs) = "pat " ++ show n ++ "\t" ++ showSep "\n\t" (map (showCImp True) cs)
1181dumpDecl (PData _ _ _ _ d) = showDImp True d
1182dumpDecl (PParams _ ns ps) = "params {" ++ show ns ++ "\n" ++ dumpDecls ps ++ "}\n"
1183dumpDecl (PNamespace n ps) = "namespace {" ++ n ++ "\n" ++ dumpDecls ps ++ "}\n"
1184dumpDecl (PSyntax _ syn) = "syntax " ++ show syn
1185dumpDecl (PClass _ _ _ cs n ps ds)
1186 = "class " ++ show cs ++ " " ++ show n ++ " " ++ show ps ++ "\n" ++ dumpDecls ds
1187dumpDecl (PInstance _ _ cs n _ t _ ds)
1188 = "instance " ++ show cs ++ " " ++ show n ++ " " ++ show t ++ "\n" ++ dumpDecls ds
1189dumpDecl _ = "..."
1190-- dumpDecl (PImport i) = "import " ++ i
1192-- for 6.12/7 compatibility
1193data EitherErr a b = LeftErr a | RightOK b
1195instance Monad (EitherErr a) where
1196 return = RightOK
1198 (LeftErr e) >>= k = LeftErr e
1199 RightOK v >>= k = k v
1201toEither (LeftErr e) = Left e
1202toEither (RightOK ho) = Right ho
1204-- syntactic match of a against b, returning pair of variables in a
1205-- and what they match. Returns the pair that failed if not a match.
1207matchClause :: IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1208matchClause = matchClause' False
1210matchClause' :: Bool -> IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1211matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
1212 matchArg x y = match (fullApp (getTm x)) (fullApp (getTm y))
1214 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1215 fullApp x = x
1217 match' x y = match (fullApp x) (fullApp y)
1218 match (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x]) x'
1219 | PConstant (I _) <- getTm x = match (getTm x) x'
1220 match x' (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x])
1221 | PConstant (I _) <- getTm x = match (getTm x) x'
1222 match (PApp _ (PRef _ (UN "lazy")) [_,x]) x' = match (getTm x) x'
1223 match x (PApp _ (PRef _ (UN "lazy")) [_,x']) = match x (getTm x')
1224 match (PApp _ f args) (PApp _ f' args')
1225 | length args == length args'
1226 = do mf <- match' f f'
1227 ms <- zipWithM matchArg args args'
1228 return (mf ++ concat ms)
1229-- match (PRef _ n) (PRef _ n') | n == n' = return []
1230-- | otherwise = Nothing
1231 match (PRef f n) (PApp _ x []) = match (PRef f n) x
1232 match (PPatvar f n) xr = match (PRef f n) xr
1233 match xr (PPatvar f n) = match xr (PRef f n)
1234 match (PApp _ x []) (PRef f n) = match x (PRef f n)
1235 match (PRef _ n) tm@(PRef _ n')
1236 | n == n' && not names &&
1237 (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1238 = return [(n, tm)]
1239 | n == n' = return []
1240 match (PRef _ n) tm
1241 | not names && (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1242 = return [(n, tm)]
1243 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
1244 mr <- match' r r'
1245 return (ml ++ mr)
1246 match (PRewrite _ l r _) (PRewrite _ l' r' _)
1247 = do ml <- match' l l'
1248 mr <- match' r r'
1249 return (ml ++ mr)
1250 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
1251 mr <- match r r'
1252 return (ml ++ mr)
1253 match (PTyped l r) x = match l x
1254 match x (PTyped l r) = match x l
1255 match (PPair _ l r) (PPair _ l' r') = do ml <- match' l l'
1256 mr <- match' r r'
1257 return (ml ++ mr)
1258 match (PDPair _ l t r) (PDPair _ l' t' r') = do ml <- match' l l'
1259 mt <- match' t t'
1260 mr <- match' r r'
1261 return (ml ++ mt ++ mr)
1262 match (PAlternative a as) (PAlternative a' as')
1263 = do ms <- zipWithM match' as as'
1264 return (concat ms)
1265 match a@(PAlternative _ as) b
1266 = do let ms = zipWith match' as (repeat b)
1267 case (rights (map toEither ms)) of
1268 (x: _) -> return x
1269 _ -> LeftErr (a, b)
1270 match (PCase _ _ _) _ = return [] -- lifted out
1271 match (PMetavar _) _ = return [] -- modified
1272 match (PInferRef _ _) _ = return [] -- modified
1273 match (PQuote _) _ = return []
1274 match (PProof _) _ = return []
1275 match (PTactics _) _ = return []
1276 match (PRefl _ _) (PRefl _ _) = return []
1277 match (PResolveTC _) (PResolveTC _) = return []
1278 match (PTrue _) (PTrue _) = return []
1279 match (PFalse _) (PFalse _) = return []
1280 match (PReturn _) (PReturn _) = return []
1281 match (PPi _ _ t s) (PPi _ _ t' s') = do mt <- match' t t'
1282 ms <- match' s s'
1283 return (mt ++ ms)
1284 match (PLam _ t s) (PLam _ t' s') = do mt <- match' t t'
1285 ms <- match' s s'
1286 return (mt ++ ms)
1287 match (PLet _ t ty s) (PLet _ t' ty' s') = do mt <- match' t t'
1288 mty <- match' ty ty'
1289 ms <- match' s s'
1290 return (mt ++ mty ++ ms)
1291 match (PHidden x) (PHidden y) = match' x y
1292 match (PUnifyLog x) y = match' x y
1293 match x (PUnifyLog y) = match' x y
1294 match Placeholder _ = return []
1295 match _ Placeholder = return []
1296 match (PResolveTC _) _ = return []
1297 match a b | a == b = return []
1298 | otherwise = LeftErr (a, b)
1300 checkRpts (RightOK ms) = check ms where
1301 check ((n,t):xs)
1302 | Just t' <- lookup n xs = if t/=t' && t/=Placeholder && t'/=Placeholder
1303 then Left (t, t')
1304 else check xs
1305 check (_:xs) = check xs
1306 check [] = Right ms
1307 checkRpts (LeftErr x) = Left x
1309substMatches :: [(Name, PTerm)] -> PTerm -> PTerm
1310substMatches ms = substMatchesShadow ms []
1312substMatchesShadow :: [(Name, PTerm)] -> [Name] -> PTerm -> PTerm
1313substMatchesShadow [] shs t = t
1314substMatchesShadow ((n,tm):ns) shs t
1315 = substMatchShadow n shs tm (substMatchesShadow ns shs t)
1317substMatch :: Name -> PTerm -> PTerm -> PTerm
1318substMatch n = substMatchShadow n []
1320substMatchShadow :: Name -> [Name] -> PTerm -> PTerm -> PTerm
1321substMatchShadow n shs tm t = sm shs t where
1322 sm xs (PRef _ n') | n == n' = tm
1323 sm xs (PLam x t sc) = PLam x (sm xs t) (sm xs sc)
1324 sm xs (PPi p x t sc)
1325 | x `elem` xs
1326 = let x' = nextName x in
1327 PPi p x' (sm (x':xs) (substMatch x (PRef (FC "" 0) x') t))
1328 (sm (x':xs) (substMatch x (PRef (FC "" 0) x') sc))
1329 | otherwise = PPi p x (sm xs t) (sm (x : xs) sc)
1330 sm xs (PApp f x as) = fullApp $ PApp f (sm xs x) (map (fmap (sm xs)) as)
1331 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
1332 sm xs (PEq f x y) = PEq f (sm xs x) (sm xs y)
1333 sm xs (PRewrite f x y tm) = PRewrite f (sm xs x) (sm xs y)
1334 (fmap (sm xs) tm)
1335 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
1336 sm xs (PPair f x y) = PPair f (sm xs x) (sm xs y)
1337 sm xs (PDPair f x t y) = PDPair f (sm xs x) (sm xs t) (sm xs y)
1338 sm xs (PAlternative a as) = PAlternative a (map (sm xs) as)
1339 sm xs (PHidden x) = PHidden (sm xs x)
1340 sm xs (PUnifyLog x) = PUnifyLog (sm xs x)
1341 sm xs x = x
1343 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1344 fullApp x = x
1346shadow :: Name -> Name -> PTerm -> PTerm
1347shadow n n' t = sm t where
1348 sm (PRef fc x) | n == x = PRef fc n'
1349 sm (PLam x t sc) = PLam x (sm t) (sm sc)
1350 sm (PPi p x t sc) = PPi p x (sm t) (sm sc)
1351 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
1352 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
1353 sm (PEq f x y) = PEq f (sm x) (sm y)
1354 sm (PRewrite f x y tm) = PRewrite f (sm x) (sm y) (fmap sm tm)
1355 sm (PTyped x y) = PTyped (sm x) (sm y)
1356 sm (PPair f x y) = PPair f (sm x) (sm y)
1357 sm (PDPair f x t y) = PDPair f (sm x) (sm t) (sm y)
1358 sm (PAlternative a as) = PAlternative a (map sm as)
1359 sm (PHidden x) = PHidden (sm x)
1360 sm (PUnifyLog x) = PUnifyLog (sm x)
1361 sm x = x