on 0875310 help sign in
Idris-dev/src/Idris/AbsSyntax.hs
1871 lines 78 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntax(module Idris.AbsSyntax, module Idris.AbsSyntaxTree) where
6import Idris.Core.TT
7import Idris.Core.Evaluate
8import Idris.Core.Elaborate hiding (Tactic(..))
9import Idris.Core.Typecheck
10import Idris.AbsSyntaxTree
11import Idris.Colours
12import Idris.IdeSlave
13import IRTS.CodegenCommon
14import Util.DynamicLinker
16import Paths_idris
18import System.Console.Haskeline
19import System.IO
21import Control.Monad.State
22import Control.Monad.Error(throwError)
24import Data.List
25import Data.Char
26import qualified Data.Text as T
27import Data.Either
28import qualified Data.Map as M
29import Data.Maybe
30import qualified Data.Set as S
31import Data.Word (Word)
33import Debug.Trace
35import Control.Monad.Error (throwError, catchError)
36import System.IO.Error(isUserError, ioeGetErrorString, tryIOError)
38import Util.Pretty
39import Util.ScreenSize
40import Util.System
42getContext :: Idris Context
43getContext = do i <- getIState; return (tt_ctxt i)
45forCodegen :: Codegen -> [(Codegen, a)] -> [a]
46forCodegen tgt xs = [x | (tgt', x) <- xs, tgt == tgt']
48getObjectFiles :: Codegen -> Idris [FilePath]
49getObjectFiles tgt = do i <- getIState; return (forCodegen tgt $ idris_objs i)
51addObjectFile :: Codegen -> FilePath -> Idris ()
52addObjectFile tgt f = do i <- getIState; putIState $ i { idris_objs = nub $ (tgt, f) : idris_objs i }
54getLibs :: Codegen -> Idris [String]
55getLibs tgt = do i <- getIState; return (forCodegen tgt $ idris_libs i)
57addLib :: Codegen -> String -> Idris ()
58addLib tgt f = do i <- getIState; putIState $ i { idris_libs = nub $ (tgt, f) : idris_libs i }
60getFlags :: Codegen -> Idris [String]
61getFlags tgt = do i <- getIState; return (forCodegen tgt $ idris_cgflags i)
63addFlag :: Codegen -> String -> Idris ()
64addFlag tgt f = do i <- getIState; putIState $ i { idris_cgflags = nub $ (tgt, f) : idris_cgflags i }
66addDyLib :: [String] -> Idris (Either DynamicLib String)
67addDyLib libs = do i <- getIState
68 let ls = idris_dynamic_libs i
69 let importdirs = opt_importdirs (idris_options i)
70 case mapMaybe (findDyLib ls) libs of
71 x:_ -> return (Left x)
72 [] -> do
73 handle <- lift . lift .
74 mapM (\l -> catchIO (tryLoadLib importdirs l)
75 (\_ -> return Nothing)) $ libs
76 case msum handle of
77 Nothing -> return (Right $ "Could not load dynamic alternatives \"" ++
78 concat (intersperse "," libs) ++ "\"")
79 Just x -> do putIState $ i { idris_dynamic_libs = x:ls }
80 return (Left x)
81 where findDyLib :: [DynamicLib] -> String -> Maybe DynamicLib
82 findDyLib [] l = Nothing
83 findDyLib (lib:libs) l | l == lib_name lib = Just lib
84 | otherwise = findDyLib libs l
87addHdr :: Codegen -> String -> Idris ()
88addHdr tgt f = do i <- getIState; putIState $ i { idris_hdrs = nub $ (tgt, f) : idris_hdrs i }
90addLangExt :: LanguageExt -> Idris ()
91addLangExt TypeProviders = do i <- getIState
92 putIState $ i {
93 idris_language_extensions = TypeProviders : idris_language_extensions i
94 }
95addLangExt ErrorReflection = do i <- getIState
96 putIState $ i {
97 idris_language_extensions = ErrorReflection : idris_language_extensions i
98 }
100addTrans :: (Term, Term) -> Idris ()
101addTrans t = do i <- getIState
102 putIState $ i { idris_transforms = t : idris_transforms i }
104addErrRev :: (Term, Term) -> Idris ()
105addErrRev t = do i <- getIState
106 putIState $ i { idris_errRev = t : idris_errRev i }
108totcheck :: (FC, Name) -> Idris ()
109totcheck n = do i <- getIState; putIState $ i { idris_totcheck = idris_totcheck i ++ [n] }
111defer_totcheck :: (FC, Name) -> Idris ()
112defer_totcheck n
113 = do i <- getIState;
114 putIState $ i { idris_defertotcheck = nub (idris_defertotcheck i ++ [n]) }
116clear_totcheck :: Idris ()
117clear_totcheck = do i <- getIState; putIState $ i { idris_totcheck = [] }
119setFlags :: Name -> [FnOpt] -> Idris ()
120setFlags n fs = do i <- getIState; putIState $ i { idris_flags = addDef n fs (idris_flags i) }
122setAccessibility :: Name -> Accessibility -> Idris ()
123setAccessibility n a
124 = do i <- getIState
125 let ctxt = setAccess n a (tt_ctxt i)
126 putIState $ i { tt_ctxt = ctxt }
128setTotality :: Name -> Totality -> Idris ()
129setTotality n a
130 = do i <- getIState
131 let ctxt = setTotal n a (tt_ctxt i)
132 putIState $ i { tt_ctxt = ctxt }
134getTotality :: Name -> Idris Totality
135getTotality n
136 = do i <- getIState
137 case lookupTotal n (tt_ctxt i) of
138 [t] -> return t
139 _ -> return (Total [])
141-- Get coercions which might return the required type
142getCoercionsTo :: IState -> Type -> [Name]
143getCoercionsTo i ty =
144 let cs = idris_coercions i
145 (fn,_) = unApply (getRetTy ty) in
146 findCoercions fn cs
147 where findCoercions t [] = []
148 findCoercions t (n : ns) =
149 let ps = case lookupTy n (tt_ctxt i) of
150 [ty'] -> case unApply (getRetTy ty') of
151 (t', _) ->
152 if t == t' then [n] else []
153 _ -> [] in
154 ps ++ findCoercions t ns
156addToCG :: Name -> CGInfo -> Idris ()
157addToCG n cg
158 = do i <- getIState
159 putIState $ i { idris_callgraph = addDef n cg (idris_callgraph i) }
161addTyInferred :: Name -> Idris ()
162addTyInferred n
163 = do i <- getIState
164 putIState $ i { idris_tyinfodata =
165 addDef n TIPartial (idris_tyinfodata i) }
167addTyInfConstraints :: FC -> [(Term, Term)] -> Idris ()
168addTyInfConstraints fc ts = do logLvl 2 $ "TI missing: " ++ show ts
169 mapM_ addConstraint ts
170 return ()
171 where addConstraint (x, y) = findMVApps x y
173 findMVApps x y
174 = do let (fx, argsx) = unApply x
175 let (fy, argsy) = unApply y
176 if (not (fx == fy))
177 then do
178 tryAddMV fx y
179 tryAddMV fy x
180 else mapM_ addConstraint (zip argsx argsy)
182 tryAddMV (P _ mv _) y =
183 do ist <- get
184 case lookup mv (idris_metavars ist) of
185 Just _ -> addConstraintRule mv y
186 _ -> return ()
187 tryAddMV _ _ = return ()
189 addConstraintRule :: Name -> Term -> Idris ()
190 addConstraintRule n t
191 = do ist <- get
192 logLvl 1 $ "TI constraint: " ++ show (n, t)
193 case lookupCtxt n (idris_tyinfodata ist) of
194 [TISolution ts] ->
195 do mapM_ (checkConsistent t) ts
196 let ti' = addDef n (TISolution (t : ts))
197 (idris_tyinfodata ist)
198 put $ ist { idris_tyinfodata = ti' }
199 _ ->
200 do let ti' = addDef n (TISolution [t])
201 (idris_tyinfodata ist)
202 put $ ist { idris_tyinfodata = ti' }
204 -- Check a solution is consistent with previous solutions
205 -- Meaning: If heads are both data types, they had better be the
206 -- same.
207 checkConsistent :: Term -> Term -> Idris ()
208 checkConsistent x y =
209 do let (fx, _) = unApply x
210 let (fy, _) = unApply y
211 case (fx, fy) of
212 (P (TCon _ _) n _, P (TCon _ _) n' _) -> errWhen (n/=n)
213 (P (TCon _ _) n _, Constant _) -> errWhen True
214 (Constant _, P (TCon _ _) n' _) -> errWhen True
215 (P (DCon _ _) n _, P (DCon _ _) n' _) -> errWhen (n/=n)
216 _ -> return ()
218 where errWhen True
219 = throwError (At fc
220 (CantUnify False x y (Msg "") [] 0))
221 errWhen False = return ()
223isTyInferred :: Name -> Idris Bool
224isTyInferred n
225 = do i <- getIState
226 case lookupCtxt n (idris_tyinfodata i) of
227 [TIPartial] -> return True
228 _ -> return False
230-- | Adds error handlers for a particular function and argument. If names are
231-- ambiguous, all matching handlers are updated.
232addFunctionErrorHandlers :: Name -> Name -> [Name] -> Idris ()
233addFunctionErrorHandlers f arg hs =
234 do i <- getIState
235 let oldHandlers = idris_function_errorhandlers i
236 let newHandlers = flip (addDef f) oldHandlers $
237 case lookupCtxtExact f oldHandlers of
238 Nothing -> M.singleton arg (S.fromList hs)
239 Just (oldHandlers) -> M.insertWith S.union arg (S.fromList hs) oldHandlers
240 -- will always be one of those two, thus no extra case
241 putIState $ i { idris_function_errorhandlers = newHandlers }
243getFunctionErrorHandlers :: Name -> Name -> Idris [Name]
244getFunctionErrorHandlers f arg = do i <- getIState
245 return . maybe [] S.toList $
246 undefined --lookup arg =<< lookupCtxtExact f (idris_function_errorhandlers i)
249-- Trace all the names in a call graph starting at the given name
250getAllNames :: Name -> Idris [Name]
251getAllNames n = allNames [] n
253allNames :: [Name] -> Name -> Idris [Name]
254allNames ns n | n `elem` ns = return []
255allNames ns n = do i <- getIState
256 case lookupCtxtExact n (idris_callgraph i) of
257 Just ns' -> do more <- mapM (allNames (n:ns)) (map fst (calls ns'))
258 return (nub (n : concat more))
259 _ -> return [n]
261addCoercion :: Name -> Idris ()
262addCoercion n = do i <- getIState
263 putIState $ i { idris_coercions = nub $ n : idris_coercions i }
265addDocStr :: Name -> String -> Idris ()
266addDocStr n doc
267 = do i <- getIState
268 putIState $ i { idris_docstrings = addDef n doc (idris_docstrings i) }
270addNameHint :: Name -> Name -> Idris ()
271addNameHint ty n
272 = do i <- getIState
273 ty' <- case lookupCtxtName ty (idris_implicits i) of
274 [(tyn, _)] -> return tyn
275 [] -> throwError (NoSuchVariable ty)
276 tyns -> throwError (CantResolveAlts (map show (map fst tyns)))
277 let ns' = case lookupCtxt ty' (idris_namehints i) of
278 [ns] -> ns ++ [n]
279 _ -> [n]
280 putIState $ i { idris_namehints = addDef ty' ns' (idris_namehints i) }
282getNameHints :: IState -> Name -> [Name]
283getNameHints i (UN arr) | arr == txt "->" = [sUN "f",sUN "g"]
284getNameHints i n =
285 case lookupCtxt n (idris_namehints i) of
286 [ns] -> ns
287 _ -> []
289addToCalledG :: Name -> [Name] -> Idris ()
290addToCalledG n ns = return () -- TODO
292-- Add a class instance function. Dodgy hack: Put integer instances first in the
293-- list so they are resolved by default.
294-- Dodgy hack 2: put constraint chasers (@@) last
296addInstance :: Bool -> Name -> Name -> Idris ()
297addInstance int n i
298 = do ist <- getIState
299 case lookupCtxt n (idris_classes ist) of
300 [CI a b c d e ins] ->
301 do let cs = addDef n (CI a b c d e (addI i ins)) (idris_classes ist)
302 putIState $ ist { idris_classes = cs }
303 _ -> do let cs = addDef n (CI (sMN 0 "none") [] [] [] [] [i]) (idris_classes ist)
304 putIState $ ist { idris_classes = cs }
305 where addI i ins | int = i : ins
306 | chaser n = ins ++ [i]
307 | otherwise = insI i ins
308 insI i [] = [i]
309 insI i (n : ns) | chaser n = i : n : ns
310 | otherwise = n : insI i ns
312 chaser (UN nm)
313 | ('@':'@':_) <- str nm = True
314 chaser (NS n _) = chaser n
315 chaser _ = False
317addClass :: Name -> ClassInfo -> Idris ()
318addClass n i
319 = do ist <- getIState
320 let i' = case lookupCtxt n (idris_classes ist) of
321 [c] -> c { class_instances = class_instances i }
322 _ -> i
323 putIState $ ist { idris_classes = addDef n i' (idris_classes ist) }
325addIBC :: IBCWrite -> Idris ()
326addIBC ibc@(IBCDef n)
327 = do i <- getIState
328 when (notDef (ibc_write i)) $
329 putIState $ i { ibc_write = ibc : ibc_write i }
330 where notDef [] = True
331 notDef (IBCDef n': is) | n == n' = False
332 notDef (_ : is) = notDef is
333addIBC ibc = do i <- getIState; putIState $ i { ibc_write = ibc : ibc_write i }
335clearIBC :: Idris ()
336clearIBC = do i <- getIState; putIState $ i { ibc_write = [] }
338resetNameIdx :: Idris ()
339resetNameIdx = do i <- getIState
340 put (i { idris_nameIdx = (0, emptyContext) })
342-- Used to preserve sharing of names
343addNameIdx :: Name -> Idris (Int, Name)
344addNameIdx n = do i <- getIState
345 let (i', x) = addNameIdx' i n
346 return x
348addNameIdx' :: IState -> Name -> (IState, (Int, Name))
349addNameIdx' i n
350 = let idxs = snd (idris_nameIdx i) in
351 case lookupCtxt n idxs of
352 [x] -> (i, x)
353 _ -> let i' = fst (idris_nameIdx i) + 1 in
354 (i { idris_nameIdx = (i', addDef n (i', n) idxs) }, (i', n))
356getHdrs :: Codegen -> Idris [String]
357getHdrs tgt = do i <- getIState; return (forCodegen tgt $ idris_hdrs i)
359setErrLine :: Int -> Idris ()
360setErrLine x = do i <- getIState;
361 case (errLine i) of
362 Nothing -> putIState $ i { errLine = Just x }
363 Just _ -> return ()
365clearErr :: Idris ()
366clearErr = do i <- getIState
367 putIState $ i { errLine = Nothing }
369getSO :: Idris (Maybe String)
370getSO = do i <- getIState
371 return (compiled_so i)
373setSO :: Maybe String -> Idris ()
374setSO s = do i <- getIState
375 putIState $ (i { compiled_so = s })
377getIState :: Idris IState
378getIState = get
380putIState :: IState -> Idris ()
381putIState = put
383-- | A version of liftIO that puts errors into the exception type of the Idris monad
384runIO :: IO a -> Idris a
385runIO x = liftIO (tryIOError x) >>= either (throwError . Msg . show) return
386-- TODO: create specific Idris exceptions for specific IO errors such as "openFile: does not exist"
388getName :: Idris Int
389getName = do i <- getIState;
390 let idx = idris_name i;
391 putIState $ (i { idris_name = idx + 1 })
392 return idx
394addInternalApp :: FilePath -> Int -> PTerm -> Idris ()
395addInternalApp fp l t
396 = do i <- getIState
397 putIState (i { idris_lineapps = ((fp, l), t) : idris_lineapps i })
399getInternalApp :: FilePath -> Int -> Idris PTerm
400getInternalApp fp l = do i <- getIState
401 case lookup (fp, l) (idris_lineapps i) of
402 Just n' -> return n'
403 Nothing -> return Placeholder
404 -- TODO: What if it's not there?
406-- Pattern definitions are only used for coverage checking, so erase them
407-- when we're done
408clearOrigPats :: Idris ()
409clearOrigPats = do i <- get
410 let ps = idris_patdefs i
411 let ps' = mapCtxt (\ (_,miss) -> ([], miss)) ps
412 put (i { idris_patdefs = ps' })
414-- Erase types from Ps in the context (basically ending up with what's in
415-- the .ibc, which is all we need after all the analysis is done)
416clearPTypes :: Idris ()
417clearPTypes = do i <- get
418 let ctxt = tt_ctxt i
419 put (i { tt_ctxt = mapDefCtxt pErase ctxt })
420 where pErase (CaseOp c t tys orig tot cds)
421 = CaseOp c t tys orig [] (pErase' cds)
422 pErase x = x
423 pErase' (CaseDefs _ (cs, c) _ rs)
424 = let c' = (cs, fmap pEraseType c) in
425 CaseDefs c' c' c' rs
427checkUndefined :: FC -> Name -> Idris ()
428checkUndefined fc n
429 = do i <- getContext
430 case lookupTy n i of
431 (_:_) -> throwError . Msg $ show fc ++ ":" ++
432 show n ++ " already defined"
433 _ -> return ()
435isUndefined :: FC -> Name -> Idris Bool
436isUndefined fc n
437 = do i <- getContext
438 case lookupTy n i of
439 (_:_) -> return False
440 _ -> return True
442setContext :: Context -> Idris ()
443setContext ctxt = do i <- getIState; putIState $ (i { tt_ctxt = ctxt } )
445updateContext :: (Context -> Context) -> Idris ()
446updateContext f = do i <- getIState; putIState $ (i { tt_ctxt = f (tt_ctxt i) } )
448addConstraints :: FC -> (Int, [UConstraint]) -> Idris ()
449addConstraints fc (v, cs)
450 = do i <- getIState
451 let ctxt = tt_ctxt i
452 let ctxt' = ctxt { uconstraints = cs ++ uconstraints ctxt,
453 next_tvar = v }
454 let ics = zip cs (repeat fc) ++ idris_constraints i
455 putIState $ i { tt_ctxt = ctxt', idris_constraints = ics }
457addDeferred = addDeferred' Ref
458addDeferredTyCon = addDeferred' (TCon 0 0)
460addDeferred' :: NameType -> [(Name, (Int, Maybe Name, Type, Bool))] -> Idris ()
461addDeferred' nt ns
462 = do mapM_ (\(n, (i, _, t, _)) -> updateContext (addTyDecl n nt (tidyNames [] t))) ns
463 i <- getIState
464 putIState $ i { idris_metavars = map (\(n, (i, top, _, isTopLevel)) -> (n, (top, i, isTopLevel))) ns ++
465 idris_metavars i }
466 where tidyNames used (Bind (MN i x) b sc)
467 = let n' = uniqueName (UN x) used in
468 Bind n' b $ tidyNames (n':used) sc
469 tidyNames used (Bind n b sc)
470 = let n' = uniqueName n used in
471 Bind n' b $ tidyNames (n':used) sc
472 tidyNames used b = b
474solveDeferred :: Name -> Idris ()
475solveDeferred n = do i <- getIState
476 putIState $ i { idris_metavars =
477 filter (\(n', _) -> n/=n')
478 (idris_metavars i) }
480getUndefined :: Idris [Name]
481getUndefined = do i <- getIState
482 return (map fst (idris_metavars i) \\ primDefs)
484getWidth :: Idris ConsoleWidth
485getWidth = fmap idris_consolewidth getIState
487setWidth :: ConsoleWidth -> Idris ()
488setWidth w = do ist <- getIState
489 put ist { idris_consolewidth = w }
491renderWidth :: Idris Int
492renderWidth = do iw <- getWidth
493 case iw of
494 InfinitelyWide -> return 100000000
495 ColsWide n -> return (max n 1)
496 AutomaticWidth -> runIO getScreenWidth
499iRender :: Doc a -> Idris (SimpleDoc a)
500iRender d = do w <- getWidth
501 ist <- getIState
502 let ideSlave = case idris_outputmode ist of
503 IdeSlave _ -> True
504 _ -> False
505 case w of
506 InfinitelyWide -> return $ renderPretty 1.0 1000000000 d
507 ColsWide n -> return $
508 if n < 1
509 then renderPretty 1.0 1000000000 d
510 else renderPretty 0.8 n d
511 AutomaticWidth | ideSlave -> return $ renderPretty 1.0 1000000000 d
512 | otherwise -> do width <- runIO getScreenWidth
513 return $ renderPretty 0.8 width d
515ihPrintResult :: Handle -> String -> Idris ()
516ihPrintResult h s = do i <- getIState
517 case idris_outputmode i of
518 RawOutput -> case s of
519 "" -> return ()
520 s -> runIO $ hPutStrLn h s
521 IdeSlave n ->
522 let good = SexpList [SymbolAtom "ok", toSExp s] in
523 runIO $ hPutStrLn h $ convSExp "return" good n
525-- | Write a pretty-printed term to the console with semantic coloring
526consoleDisplayAnnotated :: Handle -> Doc OutputAnnotation -> Idris ()
527consoleDisplayAnnotated h output = do ist <- getIState
528 rendered <- iRender $ output
529 runIO . hPutStrLn h .
530 displayDecorated (consoleDecorate ist) $
531 rendered
534-- | Write pretty-printed output to IDESlave with semantic annotations
535ideSlaveReturnAnnotated :: Integer -> Handle -> Doc OutputAnnotation -> Idris ()
536ideSlaveReturnAnnotated n h out = do ist <- getIState
537 (str, spans) <- fmap displaySpans .
538 iRender .
539 fmap (fancifyAnnots ist) $
540 out
541 let good = [SymbolAtom "ok", toSExp str, toSExp spans]
542 runIO . hPutStrLn h $ convSExp "return" good n
544ihPrintTermWithType :: Handle -> Doc OutputAnnotation -> Doc OutputAnnotation -> Idris ()
545ihPrintTermWithType h tm ty = do ist <- getIState
546 let output = tm <+> colon <+> ty
547 case idris_outputmode ist of
548 RawOutput -> consoleDisplayAnnotated h output
549 IdeSlave n -> ideSlaveReturnAnnotated n h output
551-- | Pretty-print a collection of overloadings to REPL or IDESlave - corresponds to :t name
552ihPrintFunTypes :: Handle -> [(Name, Bool)] -> Name -> [(Name, PTerm)] -> Idris ()
553ihPrintFunTypes h bnd n [] = ihPrintError h $ "No such variable " ++ show n
554ihPrintFunTypes h bnd n overloads = do imp <- impShow
555 ist <- getIState
556 let output = vsep (map (uncurry (ppOverload imp)) overloads)
557 case idris_outputmode ist of
558 RawOutput -> consoleDisplayAnnotated h output
559 IdeSlave n -> ideSlaveReturnAnnotated n h output
560 where fullName n = prettyName True bnd n
561 ppOverload imp n tm = fullName n <+> colon <+> align (pprintPTerm imp bnd tm)
563ihRenderResult :: Handle -> Doc OutputAnnotation -> Idris ()
564ihRenderResult h d = do ist <- getIState
565 case idris_outputmode ist of
566 RawOutput -> consoleDisplayAnnotated h d
567 IdeSlave n -> ideSlaveReturnAnnotated n h d
569fancifyAnnots :: IState -> OutputAnnotation -> OutputAnnotation
570fancifyAnnots ist annot@(AnnName n _ _) =
571 do let ctxt = tt_ctxt ist
572 case () of
573 _ | isDConName n ctxt -> AnnName n (Just DataOutput) Nothing
574 _ | isFnName n ctxt -> AnnName n (Just FunOutput) Nothing
575 _ | isTConName n ctxt -> AnnName n (Just TypeOutput) Nothing
576 _ | otherwise -> annot
577fancifyAnnots _ annot = annot
579type1Doc :: Doc OutputAnnotation
580type1Doc = (annotate AnnConstType $ text "Type 1")
582-- | Show an error with semantic highlighting
583ihRenderError :: Handle -> Doc OutputAnnotation -> Idris ()
584ihRenderError h e = do ist <- getIState
585 case idris_outputmode ist of
586 RawOutput -> consoleDisplayAnnotated h e
587 IdeSlave n -> do
588 (str, spans) <- fmap displaySpans .
589 iRender .
590 fmap (fancifyAnnots ist) $
591 e
592 let good = [SymbolAtom "error", toSExp str, toSExp spans]
593 runIO . hPutStrLn h $ convSExp "return" good n
595ihPrintError :: Handle -> String -> Idris ()
596ihPrintError h s = do i <- getIState
597 case idris_outputmode i of
598 RawOutput -> case s of
599 "" -> return ()
600 s -> runIO $ hPutStrLn h s
601 IdeSlave n ->
602 let good = SexpList [SymbolAtom "error", toSExp s] in
603 runIO . hPutStrLn h $ convSExp "return" good n
605ihputStrLn :: Handle -> String -> Idris ()
606ihputStrLn h s = do i <- getIState
607 case idris_outputmode i of
608 RawOutput -> runIO $ hPutStrLn h s
609 IdeSlave n -> runIO . hPutStrLn h $ convSExp "write-string" s n
611iputStrLn = ihputStrLn stdout
612iPrintError = ihPrintError stdout
613iPrintResult = ihPrintResult stdout
614iWarn = ihWarn stdout
616ideslavePutSExp :: SExpable a => String -> a -> Idris ()
617ideslavePutSExp cmd info = do i <- getIState
618 case idris_outputmode i of
619 IdeSlave n -> runIO . putStrLn $ convSExp cmd info n
620 _ -> return ()
622-- this needs some typing magic and more structured output towards emacs
623iputGoal :: SimpleDoc OutputAnnotation -> Idris ()
624iputGoal g = do i <- getIState
625 case idris_outputmode i of
626 RawOutput -> runIO $ putStrLn (displayDecorated (consoleDecorate i) g)
627 IdeSlave n -> runIO . putStrLn $
628 convSExp "write-goal" (displayS (fmap (fancifyAnnots i) g) "") n
630isetPrompt :: String -> Idris ()
631isetPrompt p = do i <- getIState
632 case idris_outputmode i of
633 IdeSlave n -> runIO . putStrLn $ convSExp "set-prompt" p n
635ihWarn :: Handle -> FC -> Doc OutputAnnotation -> Idris ()
636ihWarn h fc err = do i <- getIState
637 err' <- iRender . fmap (fancifyAnnots i) $ err
638 case idris_outputmode i of
639 RawOutput ->
640 runIO $
641 hPutStrLn h (show fc ++ ":" ++ displayDecorated (consoleDecorate i) err')
642 IdeSlave n ->
643 do let (str, spans) = displaySpans err'
644 runIO . hPutStrLn h $
645 convSExp "warning" (fc_fname fc, fc_line fc, fc_column fc, str, spans) n
647setLogLevel :: Int -> Idris ()
648setLogLevel l = do i <- getIState
649 let opts = idris_options i
650 let opt' = opts { opt_logLevel = l }
651 putIState $ i { idris_options = opt' }
653setCmdLine :: [Opt] -> Idris ()
654setCmdLine opts = do i <- getIState
655 let iopts = idris_options i
656 putIState $ i { idris_options = iopts { opt_cmdline = opts } }
658getCmdLine :: Idris [Opt]
659getCmdLine = do i <- getIState
660 return (opt_cmdline (idris_options i))
662getDumpDefun :: Idris (Maybe FilePath)
663getDumpDefun = do i <- getIState
664 return $ findC (opt_cmdline (idris_options i))
665 where findC [] = Nothing
666 findC (DumpDefun x : _) = Just x
667 findC (_ : xs) = findC xs
669getDumpCases :: Idris (Maybe FilePath)
670getDumpCases = do i <- getIState
671 return $ findC (opt_cmdline (idris_options i))
672 where findC [] = Nothing
673 findC (DumpCases x : _) = Just x
674 findC (_ : xs) = findC xs
676logLevel :: Idris Int
677logLevel = do i <- getIState
678 return (opt_logLevel (idris_options i))
680setErrContext :: Bool -> Idris ()
681setErrContext t = do i <- getIState
682 let opts = idris_options i
683 let opt' = opts { opt_errContext = t }
684 putIState $ i { idris_options = opt' }
686errContext :: Idris Bool
687errContext = do i <- getIState
688 return (opt_errContext (idris_options i))
690useREPL :: Idris Bool
691useREPL = do i <- getIState
692 return (opt_repl (idris_options i))
694setREPL :: Bool -> Idris ()
695setREPL t = do i <- getIState
696 let opts = idris_options i
697 let opt' = opts { opt_repl = t }
698 putIState $ i { idris_options = opt' }
700showOrigErr :: Idris Bool
701showOrigErr = do i <- getIState
702 return (opt_origerr (idris_options i))
704setShowOrigErr :: Bool -> Idris ()
705setShowOrigErr b = do i <- getIState
706 let opts = idris_options i
707 let opt' = opts { opt_origerr = b }
708 putIState $ i { idris_options = opt' }
710setNoBanner :: Bool -> Idris ()
711setNoBanner n = do i <- getIState
712 let opts = idris_options i
713 let opt' = opts { opt_nobanner = n }
714 putIState $ i { idris_options = opt' }
716getNoBanner :: Idris Bool
717getNoBanner = do i <- getIState
718 let opts = idris_options i
719 return (opt_nobanner opts)
721setQuiet :: Bool -> Idris ()
722setQuiet q = do i <- getIState
723 let opts = idris_options i
724 let opt' = opts { opt_quiet = q }
725 putIState $ i { idris_options = opt' }
727getQuiet :: Idris Bool
728getQuiet = do i <- getIState
729 let opts = idris_options i
730 return (opt_quiet opts)
732setCodegen :: Codegen -> Idris ()
733setCodegen t = do i <- getIState
734 let opts = idris_options i
735 let opt' = opts { opt_codegen = t }
736 putIState $ i { idris_options = opt' }
738codegen :: Idris Codegen
739codegen = do i <- getIState
740 return (opt_codegen (idris_options i))
742setOutputTy :: OutputType -> Idris ()
743setOutputTy t = do i <- getIState
744 let opts = idris_options i
745 let opt' = opts { opt_outputTy = t }
746 putIState $ i { idris_options = opt' }
748outputTy :: Idris OutputType
749outputTy = do i <- getIState
750 return $ opt_outputTy $ idris_options i
752setIdeSlave :: Bool -> Idris ()
753setIdeSlave True = do i <- getIState
754 putIState $ i { idris_outputmode = (IdeSlave 0), idris_colourRepl = False }
755setIdeSlave False = return ()
757setTargetTriple :: String -> Idris ()
758setTargetTriple t = do i <- getIState
759 let opts = idris_options i
760 opt' = opts { opt_triple = t }
761 putIState $ i { idris_options = opt' }
763targetTriple :: Idris String
764targetTriple = do i <- getIState
765 return (opt_triple (idris_options i))
767setTargetCPU :: String -> Idris ()
768setTargetCPU t = do i <- getIState
769 let opts = idris_options i
770 opt' = opts { opt_cpu = t }
771 putIState $ i { idris_options = opt' }
773targetCPU :: Idris String
774targetCPU = do i <- getIState
775 return (opt_cpu (idris_options i))
777setOptLevel :: Word -> Idris ()
778setOptLevel t = do i <- getIState
779 let opts = idris_options i
780 opt' = opts { opt_optLevel = t }
781 putIState $ i { idris_options = opt' }
783optLevel :: Idris Word
784optLevel = do i <- getIState
785 return (opt_optLevel (idris_options i))
787verbose :: Idris Bool
788verbose = do i <- getIState
789 return (opt_verbose (idris_options i))
791setVerbose :: Bool -> Idris ()
792setVerbose t = do i <- getIState
793 let opts = idris_options i
794 let opt' = opts { opt_verbose = t }
795 putIState $ i { idris_options = opt' }
797typeInType :: Idris Bool
798typeInType = do i <- getIState
799 return (opt_typeintype (idris_options i))
801setTypeInType :: Bool -> Idris ()
802setTypeInType t = do i <- getIState
803 let opts = idris_options i
804 let opt' = opts { opt_typeintype = t }
805 putIState $ i { idris_options = opt' }
807coverage :: Idris Bool
808coverage = do i <- getIState
809 return (opt_coverage (idris_options i))
811setCoverage :: Bool -> Idris ()
812setCoverage t = do i <- getIState
813 let opts = idris_options i
814 let opt' = opts { opt_coverage = t }
815 putIState $ i { idris_options = opt' }
817setIBCSubDir :: FilePath -> Idris ()
818setIBCSubDir fp = do i <- getIState
819 let opts = idris_options i
820 let opt' = opts { opt_ibcsubdir = fp }
821 putIState $ i { idris_options = opt' }
823valIBCSubDir :: IState -> Idris FilePath
824valIBCSubDir i = return (opt_ibcsubdir (idris_options i))
826addImportDir :: FilePath -> Idris ()
827addImportDir fp = do i <- getIState
828 let opts = idris_options i
829 let opt' = opts { opt_importdirs = fp : opt_importdirs opts }
830 putIState $ i { idris_options = opt' }
832setImportDirs :: [FilePath] -> Idris ()
833setImportDirs fps = do i <- getIState
834 let opts = idris_options i
835 let opt' = opts { opt_importdirs = fps }
836 putIState $ i { idris_options = opt' }
838allImportDirs :: Idris [FilePath]
839allImportDirs = do i <- getIState
840 let optdirs = opt_importdirs (idris_options i)
841 return ("." : reverse optdirs)
843colourise :: Idris Bool
844colourise = do i <- getIState
845 return $ idris_colourRepl i
847setColourise :: Bool -> Idris ()
848setColourise b = do i <- getIState
849 putIState $ i { idris_colourRepl = b }
851setOutH :: Handle -> Idris ()
852setOutH h = do i <- getIState
853 putIState $ i { idris_outh = h }
855impShow :: Idris Bool
856impShow = do i <- getIState
857 return (opt_showimp (idris_options i))
859setImpShow :: Bool -> Idris ()
860setImpShow t = do i <- getIState
861 let opts = idris_options i
862 let opt' = opts { opt_showimp = t }
863 putIState $ i { idris_options = opt' }
865setColour :: ColourType -> IdrisColour -> Idris ()
866setColour ct c = do i <- getIState
867 let newTheme = setColour' ct c (idris_colourTheme i)
868 putIState $ i { idris_colourTheme = newTheme }
869 where setColour' KeywordColour c t = t { keywordColour = c }
870 setColour' BoundVarColour c t = t { boundVarColour = c }
871 setColour' ImplicitColour c t = t { implicitColour = c }
872 setColour' FunctionColour c t = t { functionColour = c }
873 setColour' TypeColour c t = t { typeColour = c }
874 setColour' DataColour c t = t { dataColour = c }
875 setColour' PromptColour c t = t { promptColour = c }
877logLvl :: Int -> String -> Idris ()
878logLvl l str = do i <- getIState
879 let lvl = opt_logLevel (idris_options i)
880 when (lvl >= l) $
881 case idris_outputmode i of
882 RawOutput -> do runIO $ putStrLn str
883 IdeSlave n ->
884 do let good = SexpList [IntegerAtom (toInteger l), toSExp str]
885 runIO $ putStrLn $ convSExp "log" good n
887cmdOptType :: Opt -> Idris Bool
888cmdOptType x = do i <- getIState
889 return $ x `elem` opt_cmdline (idris_options i)
891iLOG :: String -> Idris ()
892iLOG = logLvl 1
894noErrors :: Idris Bool
895noErrors = do i <- getIState
896 case errLine i of
897 Nothing -> return True
898 _ -> return False
900setTypeCase :: Bool -> Idris ()
901setTypeCase t = do i <- getIState
902 let opts = idris_options i
903 let opt' = opts { opt_typecase = t }
904 putIState $ i { idris_options = opt' }
907-- Dealing with parameters
909expandParams :: (Name -> Name) -> [(Name, PTerm)] ->
910 [Name] -> -- all names
911 [Name] -> -- names with no declaration
912 PTerm -> PTerm
913expandParams dec ps ns infs tm = en tm
914 where
915 -- if we shadow a name (say in a lambda binding) that is used in a call to
916 -- a lifted function, we need access to both names - once in the scope of the
917 -- binding and once to call the lifted functions. So we'll explicitly shadow
918 -- it. (Yes, it's a hack. The alternative would be to resolve names earlier
919 -- but we didn't...)
921 mkShadow (UN n) = MN 0 n
922 mkShadow (MN i n) = MN (i+1) n
923 mkShadow (NS x s) = NS (mkShadow x) s
925 en (PLam n t s)
926 | n `elem` (map fst ps ++ ns)
927 = let n' = mkShadow n in
928 PLam n' (en t) (en (shadow n n' s))
929 | otherwise = PLam n (en t) (en s)
930 en (PPi p n t s)
931 | n `elem` (map fst ps ++ ns)
932 = let n' = mkShadow n in
933 PPi p n' (en t) (en (shadow n n' s))
934 | otherwise = PPi p n (en t) (en s)
935 en (PLet n ty v s)
936 | n `elem` (map fst ps ++ ns)
937 = let n' = mkShadow n in
938 PLet n' (en ty) (en v) (en (shadow n n' s))
939 | otherwise = PLet n (en ty) (en v) (en s)
940 -- FIXME: Should only do this in a type signature!
941 en (PDPair f p (PRef f' n) t r)
942 | n `elem` (map fst ps ++ ns) && t /= Placeholder
943 = let n' = mkShadow n in
944 PDPair f p (PRef f' n') (en t) (en (shadow n n' r))
945 en (PEq f l r) = PEq f (en l) (en r)
946 en (PRewrite f l r g) = PRewrite f (en l) (en r) (fmap en g)
947 en (PTyped l r) = PTyped (en l) (en r)
948 en (PPair f p l r) = PPair f p (en l) (en r)
949 en (PDPair f p l t r) = PDPair f p (en l) (en t) (en r)
950 en (PAlternative a as) = PAlternative a (map en as)
951 en (PHidden t) = PHidden (en t)
952 en (PUnifyLog t) = PUnifyLog (en t)
953 en (PDisamb ds t) = PDisamb ds (en t)
954 en (PNoImplicits t) = PNoImplicits (en t)
955 en (PDoBlock ds) = PDoBlock (map (fmap en) ds)
956 en (PProof ts) = PProof (map (fmap en) ts)
957 en (PTactics ts) = PTactics (map (fmap en) ts)
959 en (PQuote (Var n))
960 | n `nselem` ns = PQuote (Var (dec n))
961 en (PApp fc (PInferRef fc' n) as)
962 | n `nselem` ns = PApp fc (PInferRef fc' (dec n))
963 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
964 en (PApp fc (PRef fc' n) as)
965 | n `elem` infs = PApp fc (PInferRef fc' (dec n))
966 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
967 | n `nselem` ns = PApp fc (PRef fc' (dec n))
968 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
969 en (PAppBind fc (PRef fc' n) as)
970 | n `elem` infs = PAppBind fc (PInferRef fc' (dec n))
971 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
972 | n `nselem` ns = PAppBind fc (PRef fc' (dec n))
973 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
974 en (PRef fc n)
975 | n `elem` infs = PApp fc (PInferRef fc (dec n))
976 (map (pexp . (PRef fc)) (map fst ps))
977 | n `nselem` ns = PApp fc (PRef fc (dec n))
978 (map (pexp . (PRef fc)) (map fst ps))
979 en (PInferRef fc n)
980 | n `nselem` ns = PApp fc (PInferRef fc (dec n))
981 (map (pexp . (PRef fc)) (map fst ps))
982 en (PApp fc f as) = PApp fc (en f) (map (fmap en) as)
983 en (PAppBind fc f as) = PAppBind fc (en f) (map (fmap en) as)
984 en (PCase fc c os) = PCase fc (en c) (map (pmap en) os)
985 en t = t
987 nselem x [] = False
988 nselem x (y : xs) | nseq x y = True
989 | otherwise = nselem x xs
991 nseq x y = nsroot x == nsroot y
993expandParamsD :: Bool -> -- True = RHS only
994 IState ->
995 (Name -> Name) -> [(Name, PTerm)] -> [Name] -> PDecl -> PDecl
996expandParamsD rhsonly ist dec ps ns (PTy doc syn fc o n ty)
997 = if n `elem` ns && (not rhsonly)
998 then -- trace (show (n, expandParams dec ps ns ty)) $
999 PTy doc syn fc o (dec n) (piBindp expl_param ps (expandParams dec ps ns [] ty))
1000 else --trace (show (n, expandParams dec ps ns ty)) $
1001 PTy doc syn fc o n (expandParams dec ps ns [] ty)
1002expandParamsD rhsonly ist dec ps ns (PPostulate doc syn fc o n ty)
1003 = if n `elem` ns && (not rhsonly)
1004 then -- trace (show (n, expandParams dec ps ns ty)) $
1005 PPostulate doc syn fc o (dec n) (piBind ps
1006 (expandParams dec ps ns [] ty))
1007 else --trace (show (n, expandParams dec ps ns ty)) $
1008 PPostulate doc syn fc o n (expandParams dec ps ns [] ty)
1009expandParamsD rhsonly ist dec ps ns (PClauses fc opts n cs)
1010 = let n' = if n `elem` ns then dec n else n in
1011 PClauses fc opts n' (map expandParamsC cs)
1012 where
1013 expandParamsC (PClause fc n lhs ws rhs ds)
1014 = let -- ps' = updateps True (namesIn ist rhs) (zip ps [0..])
1015 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
1016 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
1017 n' = if n `elem` ns then dec n else n
1018 -- names bound on the lhs should not be expanded on the rhs
1019 ns' = removeBound lhs ns in
1020 PClause fc n' lhs'
1021 (map (expandParams dec ps'' ns' []) ws)
1022 (expandParams dec ps'' ns' [] rhs)
1023 (map (expandParamsD True ist dec ps'' ns') ds)
1024 expandParamsC (PWith fc n lhs ws wval ds)
1025 = let -- ps' = updateps True (namesIn ist wval) (zip ps [0..])
1026 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
1027 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
1028 n' = if n `elem` ns then dec n else n
1029 ns' = removeBound lhs ns in
1030 PWith fc n' lhs'
1031 (map (expandParams dec ps'' ns' []) ws)
1032 (expandParams dec ps'' ns' [] wval)
1033 (map (expandParamsD rhsonly ist dec ps'' ns') ds)
1034 updateps yn nm [] = []
1035 updateps yn nm (((a, t), i):as)
1036 | (a `elem` nm) == yn = (a, t) : updateps yn nm as
1037 | otherwise = (sMN i (show n ++ "_u"), t) : updateps yn nm as
1039 removeBound lhs ns = ns \\ nub (bnames lhs)
1041 bnames (PRef _ n) = [n]
1042 bnames (PApp _ _ args) = concatMap bnames (map getTm args)
1043 bnames (PPair _ _ l r) = bnames l ++ bnames r
1044 bnames (PDPair _ _ l Placeholder r) = bnames l ++ bnames r
1045 bnames _ = []
1047expandParamsD rhs ist dec ps ns (PData doc syn fc co pd)
1048 = PData doc syn fc co (expandPData pd)
1049 where
1050 -- just do the type decl, leave constructors alone (parameters will be
1051 -- added implicitly)
1052 expandPData (PDatadecl n ty cons)
1053 = if n `elem` ns
1054 then PDatadecl (dec n) (piBind ps (expandParams dec ps ns [] ty))
1055 (map econ cons)
1056 else PDatadecl n (expandParams dec ps ns [] ty) (map econ cons)
1057 econ (doc, n, t, fc, fs)
1058 = (doc, dec n, piBindp expl ps (expandParams dec ps ns [] t), fc, fs)
1059expandParamsD rhs ist dec ps ns (PParams f params pds)
1060 = PParams f (ps ++ map (mapsnd (expandParams dec ps ns [])) params)
1061 (map (expandParamsD True ist dec ps ns) pds)
1062-- (map (expandParamsD ist dec ps ns) pds)
1063expandParamsD rhs ist dec ps ns (PMutual f pds)
1064 = PMutual f (map (expandParamsD rhs ist dec ps ns) pds)
1065expandParamsD rhs ist dec ps ns (PClass doc info f cs n params decls)
1066 = PClass doc info f
1067 (map (expandParams dec ps ns []) cs)
1069 (map (mapsnd (expandParams dec ps ns [])) params)
1070 (map (expandParamsD rhs ist dec ps ns) decls)
1071expandParamsD rhs ist dec ps ns (PInstance info f cs n params ty cn decls)
1072 = PInstance info f
1073 (map (expandParams dec ps ns []) cs)
1075 (map (expandParams dec ps ns []) params)
1076 (expandParams dec ps ns [] ty)
1077 cn
1078 (map (expandParamsD rhs ist dec ps ns) decls)
1079expandParamsD rhs ist dec ps ns d = d
1081mapsnd f (x, t) = (x, f t)
1083-- Calculate a priority for a type, for deciding elaboration order
1084-- * if it's just a type variable or concrete type, do it early (0)
1085-- * if there's only type variables and injective constructors, do it next (1)
1086-- * if there's a function type, next (2)
1087-- * finally, everything else (3)
1089getPriority :: IState -> PTerm -> Int
1090getPriority i tm = 1 -- pri tm
1091 where
1092 pri (PRef _ n) =
1093 case lookupP n (tt_ctxt i) of
1094 ((P (DCon _ _) _ _):_) -> 1
1095 ((P (TCon _ _) _ _):_) -> 1
1096 ((P Ref _ _):_) -> 1
1097 [] -> 0 -- must be locally bound, if it's not an error...
1098 pri (PPi _ _ x y) = max 5 (max (pri x) (pri y))
1099 pri (PTrue _ _) = 0
1100 pri (PFalse _) = 0
1101 pri (PRefl _ _) = 1
1102 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
1103 pri (PRewrite _ l r _) = max 1 (max (pri l) (pri r))
1104 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
1105 pri (PAppBind _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
1106 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
1107 pri (PTyped l r) = pri l
1108 pri (PPair _ _ l r) = max 1 (max (pri l) (pri r))
1109 pri (PDPair _ _ l t r) = max 1 (max (pri l) (max (pri t) (pri r)))
1110 pri (PAlternative a as) = maximum (map pri as)
1111 pri (PConstant _) = 0
1112 pri Placeholder = 1
1113 pri _ = 3
1115addStatics :: Name -> Term -> PTerm -> Idris ()
1116addStatics n tm ptm =
1117 do let (statics, dynamics) = initStatics tm ptm
1118 let stnames = nub $ concatMap freeArgNames (map snd statics)
1119 let dnames = nub $ concatMap freeArgNames (map snd dynamics)
1120 -- also get the arguments which are 'uniquely inferrable' from
1121 -- statics (see sec 4.2 of "Scrapping Your Inefficient Engine")
1122 let statics' = nub $ map fst statics ++
1123 filter (\x -> not (elem x dnames)) stnames
1124 let stpos = staticList statics' tm
1125 i <- getIState
1126 when (not (null statics)) $
1127 logLvl 5 $ show n ++ " " ++ show statics' ++ "\n" ++ show dynamics
1128 ++ "\n" ++ show stnames ++ "\n" ++ show dnames
1129 putIState $ i { idris_statics = addDef n stpos (idris_statics i) }
1130 addIBC (IBCStatic n)
1131 where
1132 initStatics (Bind n (Pi ty) sc) (PPi p _ _ s)
1133 = let (static, dynamic) = initStatics (instantiate (P Bound n ty) sc) s in
1134 if pstatic p == Static then ((n, ty) : static, dynamic)
1135 else if (not (searchArg p))
1136 then (static, (n, ty) : dynamic)
1137 else (static, dynamic)
1138 initStatics t pt = ([], [])
1140 freeArgNames (Bind n (Pi ty) sc)
1141 = nub $ freeArgNames ty
1142 freeArgNames tm = let (_, args) = unApply tm in
1143 concatMap freeNames args
1145 -- if a name appears in a type class or tactic implicit index, it doesn't
1146 -- affect its 'uniquely inferrable' from a static status since these are
1147 -- resolved by searching.
1148 searchArg (Constraint _ _ _) = True
1149 searchArg (TacImp _ _ _ _) = True
1150 searchArg _ = False
1152 staticList sts (Bind n (Pi _) sc) = (n `elem` sts) : staticList sts sc
1153 staticList _ _ = []
1155-- Dealing with implicit arguments
1157-- Add constraint bindings from using block
1159addUsingConstraints :: SyntaxInfo -> FC -> PTerm -> Idris PTerm
1160addUsingConstraints syn fc t
1161 = do ist <- get
1162 let ns = namesIn [] ist t
1163 let cs = getConstraints t -- check declared constraints
1164 let addconsts = uconsts \\ cs
1165 -- if all names in the arguments of addconsts appear in ns,
1166 -- add the constraint implicitly
1167 return (doAdd addconsts ns t)
1168 where uconsts = filter uconst (using syn)
1169 uconst (UConstraint _ _) = True
1170 uconst _ = False
1172 doAdd [] _ t = t
1173 -- if all of args in ns, then add it
1174 doAdd (UConstraint c args : cs) ns t
1175 | all (\n -> elem n ns) args
1176 = PPi (Constraint [] Dynamic "") (sMN 0 "cu")
1177 (mkConst c args) (doAdd cs ns t)
1178 | otherwise = doAdd cs ns t
1180 mkConst c args = PApp fc (PRef fc c)
1181 (map (\n -> PExp 0 [] (PRef fc n) "") args)
1183 getConstraints (PPi (Constraint _ _ _) _ c sc)
1184 = getcapp c ++ getConstraints sc
1185 getConstraints (PPi _ _ c sc) = getConstraints sc
1186 getConstraints _ = []
1188 getcapp (PApp _ (PRef _ c) args)
1189 = do ns <- mapM getName args
1190 return (UConstraint c ns)
1191 getcapp _ = []
1193 getName (PExp _ _ (PRef _ n) _) = return n
1194 getName _ = []
1196-- Add implicit Pi bindings for any names in the term which appear in an
1197-- argument position.
1199-- This has become a right mess already. Better redo it some time...
1201implicit :: SyntaxInfo -> Name -> PTerm -> Idris PTerm
1202implicit syn n ptm = implicit' syn [] n ptm
1204implicit' :: SyntaxInfo -> [Name] -> Name -> PTerm -> Idris PTerm
1205implicit' syn ignore n ptm
1206 = do i <- getIState
1207 let (tm', impdata) = implicitise syn ignore i ptm
1208-- let (tm'', spos) = findStatics i tm'
1209 putIState $ i { idris_implicits = addDef n impdata (idris_implicits i) }
1210 addIBC (IBCImp n)
1211 logLvl 5 ("Implicit " ++ show n ++ " " ++ show impdata)
1212-- i <- get
1213-- putIState $ i { idris_statics = addDef n spos (idris_statics i) }
1214 return tm'
1216implicitise :: SyntaxInfo -> [Name] -> IState -> PTerm -> (PTerm, [PArg])
1217implicitise syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
1218 let (declimps, ns') = execState (imps True [] tm) ([], [])
1219 ns = filter (\n -> implicitable n || elem n (map fst uvars)) $
1220 ns' \\ (map fst pvars ++ no_imp syn ++ ignore)
1221 nsOrder = filter (not . inUsing) ns ++ filter inUsing ns in
1222 if null ns
1223 then (tm, reverse declimps)
1224 else implicitise syn ignore ist (pibind uvars nsOrder tm)
1225 where
1226 uvars = map ipair (filter uimplicit (using syn))
1227 pvars = syn_params syn
1229 inUsing n = n `elem` map fst uvars
1231 ipair (UImplicit x y) = (x, y)
1232 uimplicit (UImplicit _ _) = True
1233 uimplicit _ = False
1235 dropAll (x:xs) ys | x `elem` ys = dropAll xs ys
1236 | otherwise = x : dropAll xs ys
1237 dropAll [] ys = []
1239 imps top env (PApp _ f as)
1240 = do (decls, ns) <- get
1241 let isn = concatMap (namesIn uvars ist) (map getTm as)
1242 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1243 imps top env (PPi (Imp l _ doc _) n ty sc)
1244 = do let isn = nub (namesIn uvars ist ty) `dropAll` [n]
1245 (decls , ns) <- get
1246 put (PImp (getPriority ist ty) True l n Placeholder doc : decls,
1247 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1248 imps True (n:env) sc
1249 imps top env (PPi (Exp l _ doc _) n ty sc)
1250 = do let isn = nub (namesIn uvars ist ty ++ case sc of
1251 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
1252 _ -> [])
1253 (decls, ns) <- get -- ignore decls in HO types
1254 put (PExp (getPriority ist ty) l Placeholder doc : decls,
1255 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1256 imps True (n:env) sc
1257 imps top env (PPi (Constraint l _ doc) n ty sc)
1258 = do let isn = nub (namesIn uvars ist ty ++ case sc of
1259 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
1260 _ -> [])
1261 (decls, ns) <- get -- ignore decls in HO types
1262 put (PConstraint 10 l Placeholder doc : decls,
1263 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1264 imps True (n:env) sc
1265 imps top env (PPi (TacImp l _ scr doc) n ty sc)
1266 = do let isn = nub (namesIn uvars ist ty ++ case sc of
1267 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
1268 _ -> [])
1269 (decls, ns) <- get -- ignore decls in HO types
1270 put (PTacImplicit 10 l n scr Placeholder doc : decls,
1271 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1272 imps True (n:env) sc
1273 imps top env (PEq _ l r)
1274 = do (decls, ns) <- get
1275 let isn = namesIn uvars ist l ++ namesIn uvars ist r
1276 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1277 imps top env (PRewrite _ l r _)
1278 = do (decls, ns) <- get
1279 let isn = namesIn uvars ist l ++ namesIn uvars ist r
1280 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1281 imps top env (PTyped l r)
1282 = imps top env l
1283 imps top env (PPair _ _ l r)
1284 = do (decls, ns) <- get
1285 let isn = namesIn uvars ist l ++ namesIn uvars ist r
1286 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1287 imps top env (PDPair _ _ (PRef _ n) t r)
1288 = do (decls, ns) <- get
1289 let isn = nub (namesIn uvars ist t ++ namesIn uvars ist r) \\ [n]
1290 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
1291 imps top env (PDPair _ _ l t r)
1292 = do (decls, ns) <- get
1293 let isn = namesIn uvars ist l ++ namesIn uvars ist t ++
1294 namesIn uvars ist r
1295 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
1296 imps top env (PAlternative a as)
1297 = do (decls, ns) <- get
1298 let isn = concatMap (namesIn uvars ist) as
1299 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1300 imps top env (PLam n ty sc)
1301 = do imps False env ty
1302 imps False (n:env) sc
1303 imps top env (PHidden tm) = imps False env tm
1304 imps top env (PUnifyLog tm) = imps False env tm
1305 imps top env (PNoImplicits tm) = imps False env tm
1306 imps top env _ = return ()
1308 pibind using [] sc = sc
1309 pibind using (n:ns) sc
1310 = case lookup n using of
1311 Just ty -> PPi (Imp [] Dynamic "" False) n ty (pibind using ns sc)
1312 Nothing -> PPi (Imp [] Dynamic "" False) n Placeholder
1313 (pibind using ns sc)
1315-- Add implicit arguments in function calls
1316addImplPat :: IState -> PTerm -> PTerm
1317addImplPat = addImpl' True [] []
1319addImplBound :: IState -> [Name] -> PTerm -> PTerm
1320addImplBound ist ns = addImpl' False ns [] ist
1322addImplBoundInf :: IState -> [Name] -> [Name] -> PTerm -> PTerm
1323addImplBoundInf ist ns inf = addImpl' False ns inf ist
1325addImpl :: IState -> PTerm -> PTerm
1326addImpl = addImpl' False [] []
1328-- TODO: in patterns, don't add implicits to function names guarded by constructors
1329-- and *not* inside a PHidden
1331addImpl' :: Bool -> [Name] -> [Name] -> IState -> PTerm -> PTerm
1332addImpl' inpat env infns ist ptm
1333 = mkUniqueNames env (ai (zip env (repeat Nothing)) [] ptm)
1334 where
1335 ai env ds (PRef fc f)
1336 | f `elem` infns = PInferRef fc f
1337 | not (f `elem` map fst env) = handleErr $ aiFn inpat inpat ist fc f ds []
1338 ai env ds (PHidden (PRef fc f))
1339 | not (f `elem` map fst env) = handleErr $ aiFn inpat False ist fc f ds []
1340 ai env ds (PEq fc l r)
1341 = let l' = ai env ds l
1342 r' = ai env ds r in
1343 PEq fc l' r'
1344 ai env ds (PRewrite fc l r g)
1345 = let l' = ai env ds l
1346 r' = ai env ds r
1347 g' = fmap (ai env ds) g in
1348 PRewrite fc l' r' g'
1349 ai env ds (PTyped l r)
1350 = let l' = ai env ds l
1351 r' = ai env ds r in
1352 PTyped l' r'
1353 ai env ds (PPair fc p l r)
1354 = let l' = ai env ds l
1355 r' = ai env ds r in
1356 PPair fc p l' r'
1357 ai env ds (PDPair fc p l t r)
1358 = let l' = ai env ds l
1359 t' = ai env ds t
1360 r' = ai env ds r in
1361 PDPair fc p l' t' r'
1362 ai env ds (PAlternative a as)
1363 = let as' = map (ai env ds) as in
1364 PAlternative a as'
1365 ai env _ (PDisamb ds' as) = ai env ds' as
1366 ai env ds (PApp fc (PInferRef _ f) as)
1367 = let as' = map (fmap (ai env ds)) as in
1368 PApp fc (PInferRef fc f) as'
1369 ai env ds (PApp fc ftm@(PRef _ f) as)
1370 | f `elem` infns = ai env ds (PApp fc (PInferRef fc f) as)
1371 | not (f `elem` map fst env)
1372 = let as' = map (fmap (ai env ds)) as in
1373 handleErr $ aiFn inpat False ist fc f ds as'
1374 | Just (Just ty) <- lookup f env =
1375 let as' = map (fmap (ai env ds)) as
1376 arity = getPArity ty in
1377 mkPApp fc arity ftm as'
1378 ai env ds (PApp fc f as)
1379 = let f' = ai env ds f
1380 as' = map (fmap (ai env ds)) as in
1381 mkPApp fc 1 f' as'
1382 ai env ds (PCase fc c os)
1383 = let c' = ai env ds c
1384 os' = map (pmap (ai env ds)) os in
1385 PCase fc c' os'
1386 ai env ds (PLam n ty sc)
1387 = let ty' = ai env ds ty
1388 sc' = ai ((n, Just ty):env) ds sc in
1389 PLam n ty' sc'
1390 ai env ds (PLet n ty val sc)
1391 = let ty' = ai env ds ty
1392 val' = ai env ds val
1393 sc' = ai ((n, Just ty):env) ds sc in
1394 PLet n ty' val' sc'
1395 ai env ds (PPi p n ty sc)
1396 = let ty' = ai env ds ty
1397 sc' = ai ((n, Just ty):env) ds sc in
1398 PPi p n ty' sc'
1399 ai env ds (PGoal fc r n sc)
1400 = let r' = ai env ds r
1401 sc' = ai ((n, Nothing):env) ds sc in
1402 PGoal fc r' n sc'
1403 ai env ds (PHidden tm) = PHidden (ai env ds tm)
1404 ai env ds (PProof ts) = PProof (map (fmap (ai env ds)) ts)
1405 ai env ds (PTactics ts) = PTactics (map (fmap (ai env ds)) ts)
1406 ai env ds (PRefl fc tm) = PRefl fc (ai env ds tm)
1407 ai env ds (PUnifyLog tm) = PUnifyLog (ai env ds tm)
1408 ai env ds (PNoImplicits tm) = PNoImplicits (ai env ds tm)
1409 ai env ds tm = tm
1411 handleErr (Left err) = PElabError err
1412 handleErr (Right x) = x
1414-- if in a pattern, and there are no arguments, and there's no possible
1415-- names with zero explicit arguments, don't add implicits.
1417aiFn :: Bool -> Bool -> IState -> FC -> Name -> [[T.Text]] -> [PArg] -> Either Err PTerm
1418aiFn inpat True ist fc f ds []
1419 = case lookupDef f (tt_ctxt ist) of
1420 [] -> Right $ PPatvar fc f
1421 alts -> let ialts = lookupCtxtName f (idris_implicits ist) in
1422 -- trace (show f ++ " " ++ show (fc, any (all imp) ialts, ialts, any constructor alts)) $
1423 if (not (vname f) || tcname f
1424 || any (conCaf (tt_ctxt ist)) ialts)
1425-- any constructor alts || any allImp ialts))
1426 then aiFn inpat False ist fc f ds [] -- use it as a constructor
1427 else Right $ PPatvar fc f
1428 where imp (PExp _ _ _ _) = False
1429 imp _ = True
1430-- allImp [] = False
1431 allImp xs = all imp xs
1432 constructor (TyDecl (DCon _ _) _) = True
1433 constructor _ = False
1435 conCaf ctxt (n, cia) = isDConName n ctxt && allImp cia
1437 vname (UN n) = True -- non qualified
1438 vname _ = False
1440aiFn inpat expat ist fc f ds as
1441 | f `elem` primNames = Right $ PApp fc (PRef fc f) as
1442aiFn inpat expat ist fc f ds as
1443 -- This is where namespaces get resolved by adding PAlternative
1444 = do let ns = lookupCtxtName f (idris_implicits ist)
1445 let nh = filter (\(n, _) -> notHidden n) ns
1446 let ns' = case trimAlts ds nh of
1447 [] -> nh
1448 x -> x
1449 case ns' of
1450 [(f',ns)] -> Right $ mkPApp fc (length ns) (PRef fc f') (insertImpl ns as)
1451 [] -> if f `elem` (map fst (idris_metavars ist))
1452 then Right $ PApp fc (PRef fc f) as
1453 else Right $ mkPApp fc (length as) (PRef fc f) as
1454 alts -> Right $
1455 PAlternative True $
1456 map (\(f', ns) -> mkPApp fc (length ns) (PRef fc f')
1457 (insertImpl ns as)) alts
1458 where
1459 trimAlts [] alts = alts
1460 trimAlts ns alts
1461 = filter (\(x, _) -> any (\d -> d `isPrefixOf` nspace x) ns) alts
1463 nspace (NS _ s) = s
1464 nspace _ = []
1466 notHidden n = case getAccessibility n of
1467 Hidden -> False
1468 _ -> True
1470 getAccessibility n
1471 = case lookupDefAcc n False (tt_ctxt ist) of
1472 [(n,t)] -> t
1473 _ -> Public
1476 insertImpl :: [PArg] -> [PArg] -> [PArg]
1477 insertImpl (PExp p l ty _ : ps) (PExp _ _ tm d : given) =
1478 PExp p l tm d : insertImpl ps given
1479 insertImpl (PConstraint p l ty _ : ps) (PConstraint _ _ tm d : given) =
1480 PConstraint p l tm d : insertImpl ps given
1481 insertImpl (PConstraint p l ty d : ps) given =
1482 PConstraint p l (PResolveTC fc) d : insertImpl ps given
1483 insertImpl (PImp p _ l n ty d : ps) given =
1484 case find n given [] of
1485 Just (tm, given') -> PImp p False l n tm "" : insertImpl ps given'
1486 Nothing -> PImp p True l n Placeholder "" : insertImpl ps given
1487 insertImpl (PTacImplicit p l n sc' ty d : ps) given =
1488 let sc = addImpl ist sc' in
1489 case find n given [] of
1490 Just (tm, given') -> PTacImplicit p l n sc tm "" : insertImpl ps given'
1491 Nothing -> if inpat
1492 then PTacImplicit p l n sc Placeholder "" : insertImpl ps given
1493 else PTacImplicit p l n sc sc "" : insertImpl ps given
1494 insertImpl expected [] = []
1495 insertImpl _ given = given
1497 find n [] acc = Nothing
1498 find n (PImp _ _ _ n' t _ : gs) acc
1499 | n == n' = Just (t, reverse acc ++ gs)
1500 find n (PTacImplicit _ _ n' _ t _ : gs) acc
1501 | n == n' = Just (t, reverse acc ++ gs)
1502 find n (g : gs) acc = find n gs (g : acc)
1504-- replace non-linear occurrences with _
1505-- ASSUMPTION: This is called before adding 'alternatives' because otherwise
1506-- it is hard to get right!
1508stripLinear :: IState -> PTerm -> PTerm
1509stripLinear i tm = evalState (sl tm) [] where
1510 sl :: PTerm -> State [Name] PTerm
1511 sl (PRef fc f)
1512 | (_:_) <- lookupTy f (tt_ctxt i)
1513 = return $ PRef fc f
1514 | otherwise = do ns <- get
1515 if (f `elem` ns)
1516 then return Placeholder
1517 else do put (f : ns)
1518 return (PRef fc f)
1519 sl (PPatvar fc f)
1520 = do ns <- get
1521 if (f `elem` ns)
1522 then return Placeholder
1523 else do put (f : ns)
1524 return (PPatvar fc f)
1525 sl t@(PAlternative _ (a : as)) = do sl a
1526 return t
1527 sl (PApp fc fn args) = do fn' <- sl fn
1528 args' <- mapM slA args
1529 return $ PApp fc fn' args'
1530 where slA (PImp p m l n t d) = do t' <- sl t
1531 return $ PImp p m l n t' d
1532 slA (PExp p l t d) = do t' <- sl t
1533 return $ PExp p l t' d
1534 slA (PConstraint p l t d)
1535 = do t' <- sl t
1536 return $ PConstraint p l t' d
1537 slA (PTacImplicit p l n sc t d)
1538 = do t' <- sl t
1539 return $ PTacImplicit p l n sc t' d
1540 sl x = return x
1542-- Remove functions which aren't applied to anything, which must then
1543-- be resolved by unification. Assume names resolved and alternatives
1544-- filled in (so no ambiguity).
1546stripUnmatchable :: IState -> PTerm -> PTerm
1547stripUnmatchable i (PApp fc fn args) = PApp fc fn (fmap (fmap su) args) where
1548 su :: PTerm -> PTerm
1549 su (PRef fc f)
1550 | (Bind n (Pi t) sc :_) <- lookupTy f (tt_ctxt i)
1551 = Placeholder
1552 su (PApp fc fn args)
1553 = PApp fc fn (fmap (fmap su) args)
1554 su (PAlternative b alts)
1555 = let alts' = filter (/= Placeholder) (map su alts) in
1556 if null alts' then Placeholder
1557 else PAlternative b alts'
1558 su (PPair fc p l r) = PPair fc p (su l) (su r)
1559 su (PDPair fc p l t r) = PDPair fc p (su l) (su t) (su r)
1560 su t = t
1561stripUnmatchable i tm = tm
1563mkPApp fc a f [] = f
1564mkPApp fc a f as = let rest = drop a as in
1565 appRest fc (PApp fc f (take a as)) rest
1566 where
1567 appRest fc f [] = f
1568 appRest fc f (a : as) = appRest fc (PApp fc f [a]) as
1570-- Find 'static' argument positions
1571-- (the declared ones, plus any names in argument position in the declared
1572-- statics)
1573-- FIXME: It's possible that this really has to happen after elaboration
1575findStatics :: IState -> PTerm -> (PTerm, [Bool])
1576findStatics ist tm = trace (show tm) $
1577 let (ns, ss) = fs tm in
1578 runState (pos ns ss tm) []
1579 where fs (PPi p n t sc)
1580 | Static <- pstatic p
1581 = let (ns, ss) = fs sc in
1582 (namesIn [] ist t : ns, n : ss)
1583 | otherwise = let (ns, ss) = fs sc in
1584 (ns, ss)
1585 fs _ = ([], [])
1587 inOne n ns = length (filter id (map (elem n) ns)) == 1
1589 pos ns ss (PPi p n t sc)
1590 | elem n ss = do sc' <- pos ns ss sc
1591 spos <- get
1592 put (True : spos)
1593 return (PPi (p { pstatic = Static }) n t sc')
1594 | otherwise = do sc' <- pos ns ss sc
1595 spos <- get
1596 put (False : spos)
1597 return (PPi p n t sc')
1598 pos ns ss t = return t
1600-- for 6.12/7 compatibility
1601data EitherErr a b = LeftErr a | RightOK b
1603instance Monad (EitherErr a) where
1604 return = RightOK
1606 (LeftErr e) >>= k = LeftErr e
1607 RightOK v >>= k = k v
1609toEither (LeftErr e) = Left e
1610toEither (RightOK ho) = Right ho
1612-- syntactic match of a against b, returning pair of variables in a
1613-- and what they match. Returns the pair that failed if not a match.
1615matchClause :: IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1616matchClause = matchClause' False
1618matchClause' :: Bool -> IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1619matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
1620 matchArg x y = match (fullApp (getTm x)) (fullApp (getTm y))
1622 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1623 fullApp x = x
1625 match' x y = match (fullApp x) (fullApp y)
1626 match (PApp _ (PRef _ (NS (UN fi) [b])) [_,_,x]) x'
1627 | fi == txt "fromInteger" && b == txt "builtins",
1628 PConstant (I _) <- getTm x = match (getTm x) x'
1629 match x' (PApp _ (PRef _ (NS (UN fi) [b])) [_,_,x])
1630 | fi == txt "fromInteger" && b == txt "builtins",
1631 PConstant (I _) <- getTm x = match (getTm x) x'
1632 match (PApp _ (PRef _ (UN l)) [_,x]) x' | l == txt "lazy" = match (getTm x) x'
1633 match x (PApp _ (PRef _ (UN l)) [_,x']) | l == txt "lazy" = match x (getTm x')
1634 match (PApp _ f args) (PApp _ f' args')
1635 | length args == length args'
1636 = do mf <- match' f f'
1637 ms <- zipWithM matchArg args args'
1638 return (mf ++ concat ms)
1639-- match (PRef _ n) (PRef _ n') | n == n' = return []
1640-- | otherwise = Nothing
1641 match (PRef f n) (PApp _ x []) = match (PRef f n) x
1642 match (PPatvar f n) xr = match (PRef f n) xr
1643 match xr (PPatvar f n) = match xr (PRef f n)
1644 match (PApp _ x []) (PRef f n) = match x (PRef f n)
1645 match (PRef _ n) tm@(PRef _ n')
1646 | n == n' && not names &&
1647 (not (isConName n (tt_ctxt i) || isFnName n (tt_ctxt i))
1648 || tm == Placeholder)
1649 = return [(n, tm)]
1650 | n == n' = return []
1651 match (PRef _ n) tm
1652 | not names && (not (isConName n (tt_ctxt i) ||
1653 isFnName n (tt_ctxt i)) || tm == Placeholder)
1654 = return [(n, tm)]
1655 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
1656 mr <- match' r r'
1657 return (ml ++ mr)
1658 match (PRewrite _ l r _) (PRewrite _ l' r' _)
1659 = do ml <- match' l l'
1660 mr <- match' r r'
1661 return (ml ++ mr)
1662 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
1663 mr <- match r r'
1664 return (ml ++ mr)
1665 match (PTyped l r) x = match l x
1666 match x (PTyped l r) = match x l
1667 match (PPair _ _ l r) (PPair _ _ l' r') = do ml <- match' l l'
1668 mr <- match' r r'
1669 return (ml ++ mr)
1670 match (PDPair _ _ l t r) (PDPair _ _ l' t' r') = do ml <- match' l l'
1671 mt <- match' t t'
1672 mr <- match' r r'
1673 return (ml ++ mt ++ mr)
1674 match (PAlternative a as) (PAlternative a' as')
1675 = do ms <- zipWithM match' as as'
1676 return (concat ms)
1677 match a@(PAlternative _ as) b
1678 = do let ms = zipWith match' as (repeat b)
1679 case (rights (map toEither ms)) of
1680 (x: _) -> return x
1681 _ -> LeftErr (a, b)
1682 match (PCase _ _ _) _ = return [] -- lifted out
1683 match (PMetavar _) _ = return [] -- modified
1684 match (PInferRef _ _) _ = return [] -- modified
1685 match (PQuote _) _ = return []
1686 match (PProof _) _ = return []
1687 match (PTactics _) _ = return []
1688 match (PRefl _ _) (PRefl _ _) = return []
1689 match (PResolveTC _) (PResolveTC _) = return []
1690 match (PTrue _ _) (PTrue _ _) = return []
1691 match (PFalse _) (PFalse _) = return []
1692 match (PReturn _) (PReturn _) = return []
1693 match (PPi _ _ t s) (PPi _ _ t' s') = do mt <- match' t t'
1694 ms <- match' s s'
1695 return (mt ++ ms)
1696 match (PLam _ t s) (PLam _ t' s') = do mt <- match' t t'
1697 ms <- match' s s'
1698 return (mt ++ ms)
1699 match (PLet _ t ty s) (PLet _ t' ty' s') = do mt <- match' t t'
1700 mty <- match' ty ty'
1701 ms <- match' s s'
1702 return (mt ++ mty ++ ms)
1703 match (PHidden x) (PHidden y) = match' x y
1704 match (PUnifyLog x) y = match' x y
1705 match x (PUnifyLog y) = match' x y
1706 match (PNoImplicits x) y = match' x y
1707 match x (PNoImplicits y) = match' x y
1708 match Placeholder _ = return []
1709 match _ Placeholder = return []
1710 match (PResolveTC _) _ = return []
1711 match a b | a == b = return []
1712 | otherwise = LeftErr (a, b)
1714 checkRpts (RightOK ms) = check ms where
1715 check ((n,t):xs)
1716 | Just t' <- lookup n xs = if t/=t' && t/=Placeholder && t'/=Placeholder
1717 then Left (t, t')
1718 else check xs
1719 check (_:xs) = check xs
1720 check [] = Right ms
1721 checkRpts (LeftErr x) = Left x
1723substMatches :: [(Name, PTerm)] -> PTerm -> PTerm
1724substMatches ms = substMatchesShadow ms []
1726substMatchesShadow :: [(Name, PTerm)] -> [Name] -> PTerm -> PTerm
1727substMatchesShadow [] shs t = t
1728substMatchesShadow ((n,tm):ns) shs t
1729 = substMatchShadow n shs tm (substMatchesShadow ns shs t)
1731substMatch :: Name -> PTerm -> PTerm -> PTerm
1732substMatch n = substMatchShadow n []
1734substMatchShadow :: Name -> [Name] -> PTerm -> PTerm -> PTerm
1735substMatchShadow n shs tm t = sm shs t where
1736 sm xs (PRef _ n') | n == n' = tm
1737 sm xs (PLam x t sc) = PLam x (sm xs t) (sm xs sc)
1738 sm xs (PPi p x t sc)
1739 | x `elem` xs
1740 = let x' = nextName x in
1741 PPi p x' (sm (x':xs) (substMatch x (PRef emptyFC x') t))
1742 (sm (x':xs) (substMatch x (PRef emptyFC x') sc))
1743 | otherwise = PPi p x (sm xs t) (sm (x : xs) sc)
1744 sm xs (PApp f x as) = fullApp $ PApp f (sm xs x) (map (fmap (sm xs)) as)
1745 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
1746 sm xs (PEq f x y) = PEq f (sm xs x) (sm xs y)
1747 sm xs (PRewrite f x y tm) = PRewrite f (sm xs x) (sm xs y)
1748 (fmap (sm xs) tm)
1749 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
1750 sm xs (PPair f p x y) = PPair f p (sm xs x) (sm xs y)
1751 sm xs (PDPair f p x t y) = PDPair f p (sm xs x) (sm xs t) (sm xs y)
1752 sm xs (PAlternative a as) = PAlternative a (map (sm xs) as)
1753 sm xs (PHidden x) = PHidden (sm xs x)
1754 sm xs (PUnifyLog x) = PUnifyLog (sm xs x)
1755 sm xs (PNoImplicits x) = PNoImplicits (sm xs x)
1756 sm xs x = x
1758 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1759 fullApp x = x
1761shadow :: Name -> Name -> PTerm -> PTerm
1762shadow n n' t = sm t where
1763 sm (PRef fc x) | n == x = PRef fc n'
1764 sm (PLam x t sc) | n /= x = PLam x (sm t) (sm sc)
1765 sm (PPi p x t sc) | n /=x = PPi p x (sm t) (sm sc)
1766 sm (PLet x t v sc) | n /= x = PLet x (sm t) (sm v) (sm sc)
1767 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
1768 sm (PAppBind f x as) = PAppBind f (sm x) (map (fmap sm) as)
1769 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
1770 sm (PEq f x y) = PEq f (sm x) (sm y)
1771 sm (PRewrite f x y tm) = PRewrite f (sm x) (sm y) (fmap sm tm)
1772 sm (PTyped x y) = PTyped (sm x) (sm y)
1773 sm (PPair f p x y) = PPair f p (sm x) (sm y)
1774 sm (PDPair f p x t y) = PDPair f p (sm x) (sm t) (sm y)
1775 sm (PAlternative a as) = PAlternative a (map sm as)
1776 sm (PTactics ts) = PTactics (map (fmap sm) ts)
1777 sm (PProof ts) = PProof (map (fmap sm) ts)
1778 sm (PHidden x) = PHidden (sm x)
1779 sm (PUnifyLog x) = PUnifyLog (sm x)
1780 sm (PNoImplicits x) = PNoImplicits (sm x)
1781 sm x = x
1783-- Rename any binders which are repeated (so that we don't have to mess
1784-- about with shadowing anywhere else).
1786mkUniqueNames :: [Name] -> PTerm -> PTerm
1787mkUniqueNames env tm = evalState (mkUniq tm) env where
1788 inScope = boundNamesIn tm
1790 mkUniqA arg = do t' <- mkUniq (getTm arg)
1791 return (arg { getTm = t' })
1793 -- FIXME: Probably ought to do this for completeness! It's fine as
1794 -- long as there are no bindings inside tactics though.
1795 mkUniqT tac = return tac
1797 mkUniq :: PTerm -> State [Name] PTerm
1798 mkUniq (PLam n ty sc)
1799 = do env <- get
1800 (n', sc') <-
1801 if n `elem` env
1802 then do let n' = uniqueName n (env ++ inScope)
1803 return (n', shadow n n' sc)
1804 else return (n, sc)
1805 put (n' : env)
1806 ty' <- mkUniq ty
1807 sc'' <- mkUniq sc'
1808 return $! PLam n' ty' sc''
1809 mkUniq (PPi p n ty sc)
1810 = do env <- get
1811 (n', sc') <-
1812 if n `elem` env
1813 then do let n' = uniqueName n (env ++ inScope)
1814 return (n', shadow n n' sc)
1815 else return (n, sc)
1816 put (n' : env)
1817 ty' <- mkUniq ty
1818 sc'' <- mkUniq sc'
1819 return $! PPi p n' ty' sc''
1820 mkUniq (PLet n ty val sc)
1821 = do env <- get
1822 (n', sc') <-
1823 if n `elem` env
1824 then do let n' = uniqueName n (env ++ inScope)
1825 return (n', shadow n n' sc)
1826 else return (n, sc)
1827 put (n' : env)
1828 ty' <- mkUniq ty; val' <- mkUniq val
1829 sc'' <- mkUniq sc'
1830 return $! PLet n' ty' val' sc''
1831 mkUniq (PApp fc t args)
1832 = do t' <- mkUniq t
1833 args' <- mapM mkUniqA args
1834 return $! PApp fc t' args'
1835 mkUniq (PAppBind fc t args)
1836 = do t' <- mkUniq t
1837 args' <- mapM mkUniqA args
1838 return $! PAppBind fc t' args'
1839 mkUniq (PCase fc t alts)
1840 = do t' <- mkUniq t
1841 alts' <- mapM (\(x,y)-> do x' <- mkUniq x; y' <- mkUniq y
1842 return (x', y')) alts
1843 return $! PCase fc t' alts'
1844 mkUniq (PPair fc p l r)
1845 = do l' <- mkUniq l; r' <- mkUniq r
1846 return $! PPair fc p l' r'
1847 mkUniq (PDPair fc p (PRef fc' n) t sc)
1848 | t /= Placeholder
1849 = do env <- get
1850 (n', sc') <- if n `elem` env
1851 then do let n' = uniqueName n (env ++ inScope)
1852 return (n', shadow n n' sc)
1853 else return (n, sc)
1854 put (n' : env)
1855 t' <- mkUniq t
1856 sc'' <- mkUniq sc'
1857 return $! PDPair fc p (PRef fc' n') t' sc''
1858 mkUniq (PDPair fc p l t r)
1859 = do l' <- mkUniq l; t' <- mkUniq t; r' <- mkUniq r
1860 return $! PDPair fc p l' t' r'
1861 mkUniq (PAlternative b as)
1862 = liftM (PAlternative b) (mapM mkUniq as)
1863 mkUniq (PHidden t) = liftM PHidden (mkUniq t)
1864 mkUniq (PUnifyLog t) = liftM PUnifyLog (mkUniq t)
1865 mkUniq (PDisamb n t) = liftM (PDisamb n) (mkUniq t)
1866 mkUniq (PNoImplicits t) = liftM PNoImplicits (mkUniq t)
1867 mkUniq (PProof ts) = liftM PProof (mapM mkUniqT ts)
1868 mkUniq (PTactics ts) = liftM PTactics (mapM mkUniqT ts)
1869 mkUniq t = return t