on d8a8fcf help sign in
Idris-dev/src/Idris/AbsSyntax.hs
1436 lines 60 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 Idris.Colours
13import IRTS.CodegenCommon
14import Util.DynamicLinker
16import Paths_idris
18import System.Console.Haskeline
20import Control.Monad.State
22import Data.List
23import Data.Char
24import Data.Either
25import Data.Maybe
26import Data.Word (Word)
28import Debug.Trace
30import Util.Pretty
31import Util.System
33getContext :: Idris Context
34getContext = do i <- getIState; return (tt_ctxt i)
36forCodegen :: Codegen -> [(Codegen, a)] -> [a]
37forCodegen tgt xs = [x | (tgt', x) <- xs, tgt == tgt']
39getObjectFiles :: Codegen -> Idris [FilePath]
40getObjectFiles tgt = do i <- getIState; return (forCodegen tgt $ idris_objs i)
42addObjectFile :: Codegen -> FilePath -> Idris ()
43addObjectFile tgt f = do i <- getIState; putIState $ i { idris_objs = nub $ (tgt, f) : idris_objs i }
45getLibs :: Codegen -> Idris [String]
46getLibs tgt = do i <- getIState; return (forCodegen tgt $ idris_libs i)
48addLib :: Codegen -> String -> Idris ()
49addLib tgt f = do i <- getIState; putIState $ i { idris_libs = nub $ (tgt, f) : idris_libs i }
51getFlags :: Codegen -> Idris [String]
52getFlags tgt = do i <- getIState; return (forCodegen tgt $ idris_cgflags i)
54addFlag :: Codegen -> String -> Idris ()
55addFlag tgt f = do i <- getIState; putIState $ i { idris_cgflags = nub $ (tgt, f) : idris_cgflags i }
57addDyLib :: [String] -> Idris (Either DynamicLib String)
58addDyLib libs = do i <- getIState
59 let ls = idris_dynamic_libs i
60 case mapMaybe (findDyLib ls) libs of
61 x:_ -> return (Left x)
62 [] -> do
63 handle <- lift $ mapM (\l -> catchIO (tryLoadLib l) (\_ -> return Nothing)) $ libs
64 case msum handle of
65 Nothing -> return (Right $ "Could not load dynamic alternatives \"" ++
66 concat (intersperse "," libs) ++ "\"")
67 Just x -> do putIState $ i { idris_dynamic_libs = x:ls }
68 return (Left x)
69 where findDyLib :: [DynamicLib] -> String -> Maybe DynamicLib
70 findDyLib [] l = Nothing
71 findDyLib (lib:libs) l | l == lib_name lib = Just lib
72 | otherwise = findDyLib libs l
75addHdr :: Codegen -> String -> Idris ()
76addHdr tgt f = do i <- getIState; putIState $ i { idris_hdrs = nub $ (tgt, f) : idris_hdrs i }
78addLangExt :: LanguageExt -> Idris ()
79addLangExt TypeProviders = do i <- getIState
80 putIState $ i {
81 idris_language_extensions = TypeProviders : idris_language_extensions i
82 }
83addLangExt ErrorReflection = do i <- getIState
84 putIState $ i {
85 idris_language_extensions = ErrorReflection : idris_language_extensions i
86 }
88addTrans :: (Term, Term) -> Idris ()
89addTrans t = do i <- getIState
90 putIState $ i { idris_transforms = t : idris_transforms i }
92totcheck :: (FC, Name) -> Idris ()
93totcheck n = do i <- getIState; putIState $ i { idris_totcheck = idris_totcheck i ++ [n] }
95clear_totcheck :: Idris ()
96clear_totcheck = do i <- getIState; putIState $ i { idris_totcheck = [] }
98setFlags :: Name -> [FnOpt] -> Idris ()
99setFlags n fs = do i <- getIState; putIState $ i { idris_flags = addDef n fs (idris_flags i) }
101setAccessibility :: Name -> Accessibility -> Idris ()
102setAccessibility n a
103 = do i <- getIState
104 let ctxt = setAccess n a (tt_ctxt i)
105 putIState $ i { tt_ctxt = ctxt }
107setTotality :: Name -> Totality -> Idris ()
108setTotality n a
109 = do i <- getIState
110 let ctxt = setTotal n a (tt_ctxt i)
111 putIState $ i { tt_ctxt = ctxt }
113getTotality :: Name -> Idris Totality
114getTotality n
115 = do i <- getIState
116 case lookupTotal n (tt_ctxt i) of
117 [t] -> return t
118 _ -> return (Total [])
120-- Get coercions which might return the required type
121getCoercionsTo :: IState -> Type -> [Name]
122getCoercionsTo i ty =
123 let cs = idris_coercions i
124 (fn,_) = unApply (getRetTy ty) in
125 findCoercions fn cs
126 where findCoercions t [] = []
127 findCoercions t (n : ns) =
128 let ps = case lookupTy n (tt_ctxt i) of
129 [ty] -> case unApply (getRetTy ty) of
130 (t', _) ->
131 if t == t' then [n] else []
132 _ -> [] in
133 ps ++ findCoercions t ns
135addToCG :: Name -> CGInfo -> Idris ()
136addToCG n cg
137 = do i <- getIState
138 putIState $ i { idris_callgraph = addDef n cg (idris_callgraph i) }
140addCoercion :: Name -> Idris ()
141addCoercion n = do i <- getIState
142 putIState $ i { idris_coercions = nub $ n : idris_coercions i }
144addDocStr :: Name -> String -> Idris ()
145addDocStr n doc
146 = do i <- getIState
147 putIState $ i { idris_docstrings = addDef n doc (idris_docstrings i) }
149addToCalledG :: Name -> [Name] -> Idris ()
150addToCalledG n ns = return () -- TODO
152-- Add a class instance function. Dodgy hack: Put integer instances first in the
153-- list so they are resolved by default.
154-- Dodgy hack 2: put constraint chasers (@@) last
156addInstance :: Bool -> Name -> Name -> Idris ()
157addInstance int n i
158 = do ist <- getIState
159 case lookupCtxt n (idris_classes ist) of
160 [CI a b c d ins] ->
161 do let cs = addDef n (CI a b c d (addI i ins)) (idris_classes ist)
162 putIState $ ist { idris_classes = cs }
163 _ -> do let cs = addDef n (CI (MN 0 "none") [] [] [] [i]) (idris_classes ist)
164 putIState $ ist { idris_classes = cs }
165 where addI i ins | int = i : ins
166 | chaser n = ins ++ [i]
167 | otherwise = insI i ins
168 insI i [] = [i]
169 insI i (n : ns) | chaser n = i : n : ns
170 | otherwise = n : insI i ns
172 chaser (UN ('@':'@':_)) = True
173 chaser (NS n _) = chaser n
174 chaser _ = False
176addClass :: Name -> ClassInfo -> Idris ()
177addClass n i
178 = do ist <- getIState
179 let i' = case lookupCtxt n (idris_classes ist) of
180 [c] -> c { class_instances = class_instances i }
181 _ -> i
182 putIState $ ist { idris_classes = addDef n i' (idris_classes ist) }
184addIBC :: IBCWrite -> Idris ()
185addIBC ibc@(IBCDef n)
186 = do i <- getIState
187 when (notDef (ibc_write i)) $
188 putIState $ i { ibc_write = ibc : ibc_write i }
189 where notDef [] = True
190 notDef (IBCDef n': is) | n == n' = False
191 notDef (_ : is) = notDef is
192addIBC ibc = do i <- getIState; putIState $ i { ibc_write = ibc : ibc_write i }
194clearIBC :: Idris ()
195clearIBC = do i <- getIState; putIState $ i { ibc_write = [] }
197getHdrs :: Codegen -> Idris [String]
198getHdrs tgt = do i <- getIState; return (forCodegen tgt $ idris_hdrs i)
200setErrLine :: Int -> Idris ()
201setErrLine x = do i <- getIState;
202 case (errLine i) of
203 Nothing -> putIState $ i { errLine = Just x }
204 Just _ -> return ()
206clearErr :: Idris ()
207clearErr = do i <- getIState
208 putIState $ i { errLine = Nothing }
210getSO :: Idris (Maybe String)
211getSO = do i <- getIState
212 return (compiled_so i)
214setSO :: Maybe String -> Idris ()
215setSO s = do i <- getIState
216 putIState $ (i { compiled_so = s })
218getIState :: Idris IState
219getIState = get
221putIState :: IState -> Idris ()
222putIState = put
224getName :: Idris Int
225getName = do i <- getIState;
226 let idx = idris_name i;
227 putIState $ (i { idris_name = idx + 1 })
228 return idx
230checkUndefined :: FC -> Name -> Idris ()
231checkUndefined fc n
232 = do i <- getContext
233 case lookupTy n i of
234 (_:_) -> fail $ show fc ++ ":" ++
235 show n ++ " already defined"
236 _ -> return ()
238isUndefined :: FC -> Name -> Idris Bool
239isUndefined fc n
240 = do i <- getContext
241 case lookupTy n i of
242 (_:_) -> return False
243 _ -> return True
245setContext :: Context -> Idris ()
246setContext ctxt = do i <- getIState; putIState $ (i { tt_ctxt = ctxt } )
248updateContext :: (Context -> Context) -> Idris ()
249updateContext f = do i <- getIState; putIState $ (i { tt_ctxt = f (tt_ctxt i) } )
251addConstraints :: FC -> (Int, [UConstraint]) -> Idris ()
252addConstraints fc (v, cs)
253 = do i <- getIState
254 let ctxt = tt_ctxt i
255 let ctxt' = ctxt { uconstraints = cs ++ uconstraints ctxt,
256 next_tvar = v }
257 let ics = zip cs (repeat fc) ++ idris_constraints i
258 putIState $ i { tt_ctxt = ctxt', idris_constraints = ics }
260addDeferred = addDeferred' Ref
261addDeferredTyCon = addDeferred' (TCon 0 0)
263addDeferred' :: NameType -> [(Name, Type)] -> Idris ()
264addDeferred' nt ns
265 = do mapM_ (\(n, t) -> updateContext (addTyDecl n nt (tidyNames [] t))) ns
266 i <- getIState
267 putIState $ i { idris_metavars = map fst ns ++ idris_metavars i }
268 where tidyNames used (Bind (MN i x) b sc)
269 = let n' = uniqueName (UN x) used in
270 Bind n' b $ tidyNames (n':used) sc
271 tidyNames used (Bind n b sc)
272 = let n' = uniqueName n used in
273 Bind n' b $ tidyNames (n':used) sc
274 tidyNames used b = b
276solveDeferred :: Name -> Idris ()
277solveDeferred n = do i <- getIState
278 putIState $ i { idris_metavars = idris_metavars i \\ [n] }
280iResult :: String -> Idris ()
281iResult s = do i <- getIState
282 case idris_outputmode i of
283 RawOutput -> case s of
284 "" -> return ()
285 s -> liftIO $ putStrLn s
286 IdeSlave n ->
287 let good = SexpList [SymbolAtom "ok", toSExp s] in
288 liftIO $ putStrLn $ convSExp "return" good n
290iFail :: String -> Idris ()
291iFail s = do i <- getIState
292 case idris_outputmode i of
293 RawOutput -> case s of
294 "" -> return ()
295 s -> liftIO $ putStrLn s
296 IdeSlave n ->
297 let good = SexpList [SymbolAtom "error", toSExp s] in
298 liftIO . putStrLn $ convSExp "return" good n
300iputStrLn :: String -> Idris ()
301iputStrLn s = do i <- getIState
302 case idris_outputmode i of
303 RawOutput -> liftIO $ putStrLn s
304 IdeSlave n ->
305 case span (/=':') s of
306 (fn, ':':rest) -> case span isDigit rest of
307 ([], ':':msg) -> write
308 ([], msg) -> write
309 (num, ':':msg) -> iWarn (FC fn (read num)) msg
310 _ -> write
311 where write = liftIO . putStrLn $ convSExp "write-string" s n
313ideslavePutSExp :: SExpable a => String -> a -> Idris ()
314ideslavePutSExp cmd info = do i <- getIState
315 case idris_outputmode i of
316 IdeSlave n -> liftIO . putStrLn $ convSExp cmd info n
317 _ -> return ()
319-- this needs some typing magic and more structured output towards emacs
320iputGoal :: String -> Idris ()
321iputGoal s = do i <- getIState
322 case idris_outputmode i of
323 RawOutput -> liftIO $ putStrLn s
324 IdeSlave n -> liftIO . putStrLn $ convSExp "write-goal" s n
326isetPrompt :: String -> Idris ()
327isetPrompt p = do i <- getIState
328 case idris_outputmode i of
329 IdeSlave n -> liftIO . putStrLn $ convSExp "set-prompt" p n
331iWarn :: FC -> String -> Idris ()
332iWarn fc err = do i <- getIState
333 case idris_outputmode i of
334 RawOutput -> liftIO $ putStrLn (show fc ++ ":" ++ err)
335 IdeSlave n -> liftIO . putStrLn $ convSExp "warning" (fc_fname fc, fc_line fc, err) n
337setLogLevel :: Int -> Idris ()
338setLogLevel l = do i <- getIState
339 let opts = idris_options i
340 let opt' = opts { opt_logLevel = l }
341 putIState $ i { idris_options = opt' }
343setCmdLine :: [Opt] -> Idris ()
344setCmdLine opts = do i <- getIState
345 let iopts = idris_options i
346 putIState $ i { idris_options = iopts { opt_cmdline = opts } }
348getCmdLine :: Idris [Opt]
349getCmdLine = do i <- getIState
350 return (opt_cmdline (idris_options i))
352getDumpDefun :: Idris (Maybe FilePath)
353getDumpDefun = do i <- getIState
354 return $ findC (opt_cmdline (idris_options i))
355 where findC [] = Nothing
356 findC (DumpDefun x : _) = Just x
357 findC (_ : xs) = findC xs
359getDumpCases :: Idris (Maybe FilePath)
360getDumpCases = do i <- getIState
361 return $ findC (opt_cmdline (idris_options i))
362 where findC [] = Nothing
363 findC (DumpCases x : _) = Just x
364 findC (_ : xs) = findC xs
366logLevel :: Idris Int
367logLevel = do i <- getIState
368 return (opt_logLevel (idris_options i))
370setErrContext :: Bool -> Idris ()
371setErrContext t = do i <- getIState
372 let opts = idris_options i
373 let opt' = opts { opt_errContext = t }
374 putIState $ i { idris_options = opt' }
376errContext :: Idris Bool
377errContext = do i <- getIState
378 return (opt_errContext (idris_options i))
380useREPL :: Idris Bool
381useREPL = do i <- getIState
382 return (opt_repl (idris_options i))
384setREPL :: Bool -> Idris ()
385setREPL t = do i <- getIState
386 let opts = idris_options i
387 let opt' = opts { opt_repl = t }
388 putIState $ i { idris_options = opt' }
390setQuiet :: Bool -> Idris ()
391setQuiet q = do i <- getIState
392 let opts = idris_options i
393 let opt' = opts { opt_quiet = q }
394 putIState $ i { idris_options = opt' }
396getQuiet :: Idris Bool
397getQuiet = do i <- getIState
398 let opts = idris_options i
399 return (opt_quiet opts)
401setCodegen :: Codegen -> Idris ()
402setCodegen t = do i <- getIState
403 let opts = idris_options i
404 let opt' = opts { opt_codegen = t }
405 putIState $ i { idris_options = opt' }
407codegen :: Idris Codegen
408codegen = do i <- getIState
409 return (opt_codegen (idris_options i))
411setOutputTy :: OutputType -> Idris ()
412setOutputTy t = do i <- getIState
413 let opts = idris_options i
414 let opt' = opts { opt_outputTy = t }
415 putIState $ i { idris_options = opt' }
417outputTy :: Idris OutputType
418outputTy = do i <- getIState
419 return $ opt_outputTy $ idris_options i
421setIdeSlave :: Bool -> Idris ()
422setIdeSlave True = do i <- getIState
423 putIState $ i { idris_outputmode = (IdeSlave 0) }
424setIdeSlave False = return ()
426setTargetTriple :: String -> Idris ()
427setTargetTriple t = do i <- getIState
428 let opts = idris_options i
429 opt' = opts { opt_triple = t }
430 putIState $ i { idris_options = opt' }
432targetTriple :: Idris String
433targetTriple = do i <- getIState
434 return (opt_triple (idris_options i))
436setTargetCPU :: String -> Idris ()
437setTargetCPU t = do i <- getIState
438 let opts = idris_options i
439 opt' = opts { opt_cpu = t }
440 putIState $ i { idris_options = opt' }
442targetCPU :: Idris String
443targetCPU = do i <- getIState
444 return (opt_cpu (idris_options i))
446setOptLevel :: Word -> Idris ()
447setOptLevel t = do i <- getIState
448 let opts = idris_options i
449 opt' = opts { opt_optLevel = t }
450 putIState $ i { idris_options = opt' }
452optLevel :: Idris Word
453optLevel = do i <- getIState
454 return (opt_optLevel (idris_options i))
456verbose :: Idris Bool
457verbose = do i <- getIState
458 return (opt_verbose (idris_options i))
460setVerbose :: Bool -> Idris ()
461setVerbose t = do i <- getIState
462 let opts = idris_options i
463 let opt' = opts { opt_verbose = t }
464 putIState $ i { idris_options = opt' }
466typeInType :: Idris Bool
467typeInType = do i <- getIState
468 return (opt_typeintype (idris_options i))
470setTypeInType :: Bool -> Idris ()
471setTypeInType t = do i <- getIState
472 let opts = idris_options i
473 let opt' = opts { opt_typeintype = t }
474 putIState $ i { idris_options = opt' }
476coverage :: Idris Bool
477coverage = do i <- getIState
478 return (opt_coverage (idris_options i))
480setCoverage :: Bool -> Idris ()
481setCoverage t = do i <- getIState
482 let opts = idris_options i
483 let opt' = opts { opt_coverage = t }
484 putIState $ i { idris_options = opt' }
486setIBCSubDir :: FilePath -> Idris ()
487setIBCSubDir fp = do i <- getIState
488 let opts = idris_options i
489 let opt' = opts { opt_ibcsubdir = fp }
490 putIState $ i { idris_options = opt' }
492valIBCSubDir :: IState -> Idris FilePath
493valIBCSubDir i = return (opt_ibcsubdir (idris_options i))
495addImportDir :: FilePath -> Idris ()
496addImportDir fp = do i <- getIState
497 let opts = idris_options i
498 let opt' = opts { opt_importdirs = fp : opt_importdirs opts }
499 putIState $ i { idris_options = opt' }
501setImportDirs :: [FilePath] -> Idris ()
502setImportDirs fps = do i <- getIState
503 let opts = idris_options i
504 let opt' = opts { opt_importdirs = fps }
505 putIState $ i { idris_options = opt' }
507allImportDirs :: Idris [FilePath]
508allImportDirs = do i <- getIState
509 let optdirs = opt_importdirs (idris_options i)
510 return ("." : reverse optdirs)
512colourise :: Idris Bool
513colourise = do i <- getIState
514 return $ idris_colourRepl i
516setColourise :: Bool -> Idris ()
517setColourise b = do i <- getIState
518 putIState $ i { idris_colourRepl = b }
520impShow :: Idris Bool
521impShow = do i <- getIState
522 return (opt_showimp (idris_options i))
524setImpShow :: Bool -> Idris ()
525setImpShow t = do i <- getIState
526 let opts = idris_options i
527 let opt' = opts { opt_showimp = t }
528 putIState $ i { idris_options = opt' }
530setColour :: ColourType -> IdrisColour -> Idris ()
531setColour ct c = do i <- getIState
532 let newTheme = setColour' ct c (idris_colourTheme i)
533 putIState $ i { idris_colourTheme = newTheme }
534 where setColour' KeywordColour c t = t { keywordColour = c }
535 setColour' BoundVarColour c t = t { boundVarColour = c }
536 setColour' ImplicitColour c t = t { implicitColour = c }
537 setColour' FunctionColour c t = t { functionColour = c }
538 setColour' TypeColour c t = t { typeColour = c }
539 setColour' DataColour c t = t { dataColour = c }
540 setColour' PromptColour c t = t { promptColour = c }
542logLvl :: Int -> String -> Idris ()
543logLvl l str = do i <- getIState
544 let lvl = opt_logLevel (idris_options i)
545 when (lvl >= l)
546 $ do liftIO (putStrLn str)
547 putIState $ i { idris_log = idris_log i ++ str ++ "\n" }
549cmdOptType :: Opt -> Idris Bool
550cmdOptType x = do i <- getIState
551 return $ x `elem` opt_cmdline (idris_options i)
553iLOG :: String -> Idris ()
554iLOG = logLvl 1
556noErrors :: Idris Bool
557noErrors = do i <- getIState
558 case errLine i of
559 Nothing -> return True
560 _ -> return False
562setTypeCase :: Bool -> Idris ()
563setTypeCase t = do i <- getIState
564 let opts = idris_options i
565 let opt' = opts { opt_typecase = t }
566 putIState $ i { idris_options = opt' }
569-- For inferring types of things
571bi = FC "builtin" 0
573inferTy = MN 0 "__Infer"
574inferCon = MN 0 "__infer"
575inferDecl = PDatadecl inferTy
576 PType
577 [("", inferCon, PPi impl (MN 0 "A") PType (
578 PPi expl (MN 0 "a") (PRef bi (MN 0 "A"))
579 (PRef bi inferTy)), bi)]
581infTerm t = PApp bi (PRef bi inferCon) [pimp (MN 0 "A") Placeholder, pexp t]
582infP = P (TCon 6 0) inferTy (TType (UVal 0))
584getInferTerm, getInferType :: Term -> Term
585getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
586getInferTerm (App (App _ _) tm) = tm
587getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
589getInferType (Bind n b sc) = Bind n b $ getInferType sc
590getInferType (App (App _ ty) _) = ty
592-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
594primNames = [unitTy, unitCon,
595 falseTy, pairTy, pairCon,
596 eqTy, eqCon, inferTy, inferCon]
598unitTy = MN 0 "__Unit"
599unitCon = MN 0 "__II"
600unitDecl = PDatadecl unitTy PType
601 [("", unitCon, PRef bi unitTy, bi)]
603falseTy = MN 0 "__False"
604falseDecl = PDatadecl falseTy PType []
606pairTy = MN 0 "__Pair"
607pairCon = MN 0 "__MkPair"
608pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
609 [("", pairCon, PPi impl (n "A") PType (
610 PPi impl (n "B") PType (
611 PPi expl (n "a") (PRef bi (n "A")) (
612 PPi expl (n "b") (PRef bi (n "B"))
613 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
614 pexp (PRef bi (n "B"))])))), bi)]
615 where n a = MN 0 a
617eqTy = UN "="
618eqCon = UN "refl"
619eqDecl = PDatadecl eqTy (piBind [(n "a", PType), (n "b", PType),
620 (n "x", PRef bi (n "a")), (n "y", PRef bi (n "b"))]
621 PType)
622 [("", eqCon, PPi impl (n "a") PType (
623 PPi impl (n "x") (PRef bi (n "a"))
624 (PApp bi (PRef bi eqTy) [pimp (n "a") Placeholder,
625 pimp (n "b") Placeholder,
626 pexp (PRef bi (n "x")),
627 pexp (PRef bi (n "x"))])), bi)]
628 where n a = MN 0 a
630-- Defined in builtins.idr
631sigmaTy = UN "Exists"
632existsCon = UN "Ex_intro"
634piBind :: [(Name, PTerm)] -> PTerm -> PTerm
635piBind = piBindp expl
637piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
638piBindp p [] t = t
639piBindp p ((n, ty):ns) t = PPi p n ty (piBind ns t)
641-- Dealing with parameters
643expandParams :: (Name -> Name) -> [(Name, PTerm)] ->
644 [Name] -> -- all names
645 [Name] -> -- names with no declaration
646 PTerm -> PTerm
647expandParams dec ps ns infs tm = en tm
648 where
649 -- if we shadow a name (say in a lambda binding) that is used in a call to
650 -- a lifted function, we need access to both names - once in the scope of the
651 -- binding and once to call the lifted functions. So we'll explicitly shadow
652 -- it. (Yes, it's a hack. The alternative would be to resolve names earlier
653 -- but we didn't...)
655 mkShadow (UN n) = MN 0 n
656 mkShadow (MN i n) = MN (i+1) n
657 mkShadow (NS x s) = NS (mkShadow x) s
659 en (PLam n t s)
660 | n `elem` (map fst ps ++ ns)
661 = let n' = mkShadow n in
662 PLam n' (en t) (en (shadow n n' s))
663 | otherwise = PLam n (en t) (en s)
664 en (PPi p n t s)
665 | n `elem` (map fst ps ++ ns)
666 = let n' = mkShadow n in
667 PPi p n' (en t) (en (shadow n n' s))
668 | otherwise = PPi p n (en t) (en s)
669 en (PLet n ty v s)
670 | n `elem` (map fst ps ++ ns)
671 = let n' = mkShadow n in
672 PLet n' (en ty) (en v) (en (shadow n n' s))
673 | otherwise = PLet n (en ty) (en v) (en s)
674 -- FIXME: Should only do this in a type signature!
675 en (PDPair f (PRef f' n) t r)
676 | n `elem` (map fst ps ++ ns) && t /= Placeholder
677 = let n' = mkShadow n in
678 PDPair f (PRef f' n') (en t) (en (shadow n n' r))
679 en (PEq f l r) = PEq f (en l) (en r)
680 en (PRewrite f l r g) = PRewrite f (en l) (en r) (fmap en g)
681 en (PTyped l r) = PTyped (en l) (en r)
682 en (PPair f l r) = PPair f (en l) (en r)
683 en (PDPair f l t r) = PDPair f (en l) (en t) (en r)
684 en (PAlternative a as) = PAlternative a (map en as)
685 en (PHidden t) = PHidden (en t)
686 en (PUnifyLog t) = PUnifyLog (en t)
687 en (PDoBlock ds) = PDoBlock (map (fmap en) ds)
688 en (PProof ts) = PProof (map (fmap en) ts)
689 en (PTactics ts) = PTactics (map (fmap en) ts)
691 en (PQuote (Var n))
692 | n `nselem` ns = PQuote (Var (dec n))
693 en (PApp fc (PInferRef fc' n) as)
694 | n `nselem` ns = PApp fc (PInferRef fc' (dec n))
695 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
696 en (PApp fc (PRef fc' n) as)
697 | n `elem` infs = PApp fc (PInferRef fc' (dec n))
698 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
699 | n `nselem` ns = PApp fc (PRef fc' (dec n))
700 (map (pexp . (PRef fc)) (map fst ps) ++ (map (fmap en) as))
701 en (PRef fc n)
702 | n `elem` infs = PApp fc (PInferRef fc (dec n))
703 (map (pexp . (PRef fc)) (map fst ps))
704 | n `nselem` ns = PApp fc (PRef fc (dec n))
705 (map (pexp . (PRef fc)) (map fst ps))
706 en (PInferRef fc n)
707 | n `nselem` ns = PApp fc (PInferRef fc (dec n))
708 (map (pexp . (PRef fc)) (map fst ps))
709 en (PApp fc f as) = PApp fc (en f) (map (fmap en) as)
710 en (PCase fc c os) = PCase fc (en c) (map (pmap en) os)
711 en t = t
713 nselem x [] = False
714 nselem x (y : xs) | nseq x y = True
715 | otherwise = nselem x xs
717 nseq x y = nsroot x == nsroot y
719expandParamsD :: Bool -> -- True = RHS only
720 IState ->
721 (Name -> Name) -> [(Name, PTerm)] -> [Name] -> PDecl -> PDecl
722expandParamsD rhsonly ist dec ps ns (PTy doc syn fc o n ty)
723 = if n `elem` ns && (not rhsonly)
724 then -- trace (show (n, expandParams dec ps ns ty)) $
725 PTy doc syn fc o (dec n) (piBind ps (expandParams dec ps ns [] ty))
726 else --trace (show (n, expandParams dec ps ns ty)) $
727 PTy doc syn fc o n (expandParams dec ps ns [] ty)
728expandParamsD rhsonly ist dec ps ns (PPostulate doc syn fc o n ty)
729 = if n `elem` ns && (not rhsonly)
730 then -- trace (show (n, expandParams dec ps ns ty)) $
731 PPostulate doc syn fc o (dec n) (piBind ps
732 (expandParams dec ps ns [] ty))
733 else --trace (show (n, expandParams dec ps ns ty)) $
734 PPostulate doc syn fc o n (expandParams dec ps ns [] ty)
735expandParamsD rhsonly ist dec ps ns (PClauses fc opts n cs)
736 = let n' = if n `elem` ns then dec n else n in
737 PClauses fc opts n' (map expandParamsC cs)
738 where
739 expandParamsC (PClause fc n lhs ws rhs ds)
740 = let -- ps' = updateps True (namesIn ist rhs) (zip ps [0..])
741 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
742 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
743 n' = if n `elem` ns then dec n else n
744 -- names bound on the lhs should not be expanded on the rhs
745 ns' = removeBound lhs ns in
746 PClause fc n' lhs'
747 (map (expandParams dec ps'' ns' []) ws)
748 (expandParams dec ps'' ns' [] rhs)
749 (map (expandParamsD True ist dec ps'' ns') ds)
750 expandParamsC (PWith fc n lhs ws wval ds)
751 = let -- ps' = updateps True (namesIn ist wval) (zip ps [0..])
752 ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..])
753 lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs)
754 n' = if n `elem` ns then dec n else n
755 ns' = removeBound lhs ns in
756 PWith fc n' lhs'
757 (map (expandParams dec ps'' ns' []) ws)
758 (expandParams dec ps'' ns' [] wval)
759 (map (expandParamsD rhsonly ist dec ps'' ns') ds)
760 updateps yn nm [] = []
761 updateps yn nm (((a, t), i):as)
762 | (a `elem` nm) == yn = (a, t) : updateps yn nm as
763 | otherwise = (MN i (show n ++ "_u"), t) : updateps yn nm as
765 removeBound lhs ns = ns \\ nub (bnames lhs)
767 bnames (PRef _ n) = [n]
768 bnames (PApp _ _ args) = concatMap bnames (map getTm args)
769 bnames (PPair _ l r) = bnames l ++ bnames r
770 bnames (PDPair _ l Placeholder r) = bnames l ++ bnames r
771 bnames _ = []
773expandParamsD rhs ist dec ps ns (PData doc syn fc co pd)
774 = PData doc syn fc co (expandPData pd)
775 where
776 -- just do the type decl, leave constructors alone (parameters will be
777 -- added implicitly)
778 expandPData (PDatadecl n ty cons)
779 = if n `elem` ns
780 then PDatadecl (dec n) (piBind ps (expandParams dec ps ns [] ty))
781 (map econ cons)
782 else PDatadecl n (expandParams dec ps ns [] ty) (map econ cons)
783 econ (doc, n, t, fc)
784 = (doc, dec n, piBindp expl ps (expandParams dec ps ns [] t), fc)
785expandParamsD rhs ist dec ps ns (PParams f params pds)
786 = PParams f (ps ++ map (mapsnd (expandParams dec ps ns [])) params)
787 (map (expandParamsD True ist dec ps ns) pds)
788-- (map (expandParamsD ist dec ps ns) pds)
789expandParamsD rhs ist dec ps ns (PMutual f pds)
790 = PMutual f (map (expandParamsD rhs ist dec ps ns) pds)
791expandParamsD rhs ist dec ps ns (PClass doc info f cs n params decls)
792 = PClass doc info f
793 (map (expandParams dec ps ns []) cs)
794 n
795 (map (mapsnd (expandParams dec ps ns [])) params)
796 (map (expandParamsD rhs ist dec ps ns) decls)
797expandParamsD rhs ist dec ps ns (PInstance info f cs n params ty cn decls)
798 = PInstance info f
799 (map (expandParams dec ps ns []) cs)
800 n
801 (map (expandParams dec ps ns []) params)
802 (expandParams dec ps ns [] ty)
803 cn
804 (map (expandParamsD rhs ist dec ps ns) decls)
805expandParamsD rhs ist dec ps ns d = d
807mapsnd f (x, t) = (x, f t)
809-- Calculate a priority for a type, for deciding elaboration order
810-- * if it's just a type variable or concrete type, do it early (0)
811-- * if there's only type variables and injective constructors, do it next (1)
812-- * if there's a function type, next (2)
813-- * finally, everything else (3)
815getPriority :: IState -> PTerm -> Int
816getPriority i tm = 1 -- pri tm
817 where
818 pri (PRef _ n) =
819 case lookupP n (tt_ctxt i) of
820 ((P (DCon _ _) _ _):_) -> 1
821 ((P (TCon _ _) _ _):_) -> 1
822 ((P Ref _ _):_) -> 1
823 [] -> 0 -- must be locally bound, if it's not an error...
824 pri (PPi _ _ x y) = max 5 (max (pri x) (pri y))
825 pri (PTrue _) = 0
826 pri (PFalse _) = 0
827 pri (PRefl _ _) = 1
828 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
829 pri (PRewrite _ l r _) = max 1 (max (pri l) (pri r))
830 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
831 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
832 pri (PTyped l r) = pri l
833 pri (PPair _ l r) = max 1 (max (pri l) (pri r))
834 pri (PDPair _ l t r) = max 1 (max (pri l) (max (pri t) (pri r)))
835 pri (PAlternative a as) = maximum (map pri as)
836 pri (PConstant _) = 0
837 pri Placeholder = 1
838 pri _ = 3
840addStatics :: Name -> Term -> PTerm -> Idris ()
841addStatics n tm ptm =
842 do let (statics, dynamics) = initStatics tm ptm
843 let stnames = nub $ concatMap freeNames (map snd statics)
844 let dnames = nub $ concatMap freeNames (map snd dynamics)
845 when (not (null statics)) $
846 logLvl 7 $ show n ++ " " ++ show statics ++ "\n" ++ show dynamics
847 ++ "\n" ++ show stnames ++ "\n" ++ show dnames
848 let statics' = nub $ map fst statics ++
849 filter (\x -> not (elem x dnames)) stnames
850 let stpos = staticList statics' tm
851 i <- getIState
852 putIState $ i { idris_statics = addDef n stpos (idris_statics i) }
853 addIBC (IBCStatic n)
854 where
855 initStatics (Bind n (Pi ty) sc) (PPi p _ _ s)
856 = let (static, dynamic) = initStatics (instantiate (P Bound n ty) sc) s in
857 if pstatic p == Static then ((n, ty) : static, dynamic)
858 else (static, (n, ty) : dynamic)
859 initStatics t pt = ([], [])
861 staticList sts (Bind n (Pi _) sc) = (n `elem` sts) : staticList sts sc
862 staticList _ _ = []
864-- Dealing with implicit arguments
866-- Add constraint bindings from using block
868addUsingConstraints :: SyntaxInfo -> FC -> PTerm -> Idris PTerm
869addUsingConstraints syn fc t
870 = do ist <- get
871 let ns = namesIn [] ist t
872 let cs = getConstraints t -- check declared constraints
873 let addconsts = uconsts \\ cs
874 -- if all names in the arguments of addconsts appear in ns,
875 -- add the constraint implicitly
876 return (doAdd addconsts ns t)
877 where uconsts = filter uconst (using syn)
878 uconst (UConstraint _ _) = True
879 uconst _ = False
881 doAdd [] _ t = t
882 -- if all of args in ns, then add it
883 doAdd (UConstraint c args : cs) ns t
884 | all (\n -> elem n ns) args
885 = PPi (Constraint False Dynamic "") (MN 0 "cu")
886 (mkConst c args) (doAdd cs ns t)
887 | otherwise = doAdd cs ns t
889 mkConst c args = PApp fc (PRef fc c)
890 (map (\n -> PExp 0 False (PRef fc n) "") args)
892 getConstraints (PPi (Constraint _ _ _) _ c sc)
893 = getcapp c ++ getConstraints sc
894 getConstraints (PPi _ _ c sc) = getConstraints sc
895 getConstraints _ = []
897 getcapp (PApp _ (PRef _ c) args)
898 = do ns <- mapM getName args
899 return (UConstraint c ns)
900 getcapp _ = []
902 getName (PExp _ _ (PRef _ n) _) = return n
903 getName _ = []
905-- Add implicit Pi bindings for any names in the term which appear in an
906-- argument position.
908-- This has become a right mess already. Better redo it some time...
910implicit :: SyntaxInfo -> Name -> PTerm -> Idris PTerm
911implicit syn n ptm = implicit' syn [] n ptm
913implicit' :: SyntaxInfo -> [Name] -> Name -> PTerm -> Idris PTerm
914implicit' syn ignore n ptm
915 = do i <- getIState
916 let (tm', impdata) = implicitise syn ignore i ptm
917-- let (tm'', spos) = findStatics i tm'
918 putIState $ i { idris_implicits = addDef n impdata (idris_implicits i) }
919 addIBC (IBCImp n)
920 logLvl 5 ("Implicit " ++ show n ++ " " ++ show impdata)
921-- i <- get
922-- putIState $ i { idris_statics = addDef n spos (idris_statics i) }
923 return tm'
925implicitise :: SyntaxInfo -> [Name] -> IState -> PTerm -> (PTerm, [PArg])
926implicitise syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
927 let (declimps, ns') = execState (imps True [] tm) ([], [])
928 ns = filter (\n -> implicitable n || elem n (map fst uvars)) $
929 ns' \\ (map fst pvars ++ no_imp syn ++ ignore)
930 nsOrder = filter (not . inUsing) ns ++ filter inUsing ns in
931 if null ns
932 then (tm, reverse declimps)
933 else implicitise syn ignore ist (pibind uvars nsOrder tm)
934 where
935 uvars = map ipair (filter uimplicit (using syn))
936 pvars = syn_params syn
938 inUsing n = n `elem` map fst uvars
940 ipair (UImplicit x y) = (x, y)
941 uimplicit (UImplicit _ _) = True
942 uimplicit _ = False
944 dropAll (x:xs) ys | x `elem` ys = dropAll xs ys
945 | otherwise = x : dropAll xs ys
946 dropAll [] ys = []
948 imps top env (PApp _ f as)
949 = do (decls, ns) <- get
950 let isn = concatMap (namesIn uvars ist) (map getTm as)
951 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
952 imps top env (PPi (Imp l _ doc) n ty sc)
953 = do let isn = nub (namesIn uvars ist ty) `dropAll` [n]
954 (decls , ns) <- get
955 put (PImp (getPriority ist ty) l n ty doc : decls,
956 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
957 imps True (n:env) sc
958 imps top env (PPi (Exp l _ doc) n ty sc)
959 = do let isn = nub (namesIn uvars ist ty ++ case sc of
960 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
961 _ -> [])
962 (decls, ns) <- get -- ignore decls in HO types
963 put (PExp (getPriority ist ty) l ty doc : decls,
964 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
965 imps True (n:env) sc
966 imps top env (PPi (Constraint l _ doc) n ty sc)
967 = do let isn = nub (namesIn uvars ist ty ++ case sc of
968 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
969 _ -> [])
970 (decls, ns) <- get -- ignore decls in HO types
971 put (PConstraint 10 l ty doc : decls,
972 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
973 imps True (n:env) sc
974 imps top env (PPi (TacImp l _ scr doc) n ty sc)
975 = do let isn = nub (namesIn uvars ist ty ++ case sc of
976 (PRef _ x) -> namesIn uvars ist sc `dropAll` [n]
977 _ -> [])
978 (decls, ns) <- get -- ignore decls in HO types
979 put (PTacImplicit 10 l n scr ty doc : decls,
980 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
981 imps True (n:env) sc
982 imps top env (PEq _ l r)
983 = do (decls, ns) <- get
984 let isn = namesIn uvars ist l ++ namesIn uvars ist r
985 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
986 imps top env (PRewrite _ l r _)
987 = do (decls, ns) <- get
988 let isn = namesIn uvars ist l ++ namesIn uvars ist r
989 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
990 imps top env (PTyped l r)
991 = imps top env l
992 imps top env (PPair _ l r)
993 = do (decls, ns) <- get
994 let isn = namesIn uvars ist l ++ namesIn uvars ist r
995 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
996 imps top env (PDPair _ (PRef _ n) t r)
997 = do (decls, ns) <- get
998 let isn = nub (namesIn uvars ist t ++ namesIn uvars ist r) \\ [n]
999 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
1000 imps top env (PDPair _ l t r)
1001 = do (decls, ns) <- get
1002 let isn = namesIn uvars ist l ++ namesIn uvars ist t ++
1003 namesIn uvars ist r
1004 put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls)))))
1005 imps top env (PAlternative a as)
1006 = do (decls, ns) <- get
1007 let isn = concatMap (namesIn uvars ist) as
1008 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1009 imps top env (PLam n ty sc)
1010 = do imps False env ty
1011 imps False (n:env) sc
1012 imps top env (PHidden tm) = imps False env tm
1013 imps top env (PUnifyLog tm) = imps False env tm
1014 imps top env _ = return ()
1016 pibind using [] sc = sc
1017 pibind using (n:ns) sc
1018 = case lookup n using of
1019 Just ty -> PPi (Imp False Dynamic "") n ty (pibind using ns sc)
1020 Nothing -> PPi (Imp False Dynamic "") n Placeholder
1021 (pibind using ns sc)
1023-- Add implicit arguments in function calls
1024addImplPat :: IState -> PTerm -> PTerm
1025addImplPat = addImpl' True [] []
1027addImplBound :: IState -> [Name] -> PTerm -> PTerm
1028addImplBound ist ns = addImpl' False ns [] ist
1030addImplBoundInf :: IState -> [Name] -> [Name] -> PTerm -> PTerm
1031addImplBoundInf ist ns inf = addImpl' False ns inf ist
1033addImpl :: IState -> PTerm -> PTerm
1034addImpl = addImpl' False [] []
1036-- TODO: in patterns, don't add implicits to function names guarded by constructors
1037-- and *not* inside a PHidden
1039addImpl' :: Bool -> [Name] -> [Name] -> IState -> PTerm -> PTerm
1040addImpl' inpat env infns ist ptm = ai (zip env (repeat Nothing)) ptm
1041 where
1042 ai env (PRef fc f)
1043 | f `elem` infns = PInferRef fc f
1044 | not (f `elem` map fst env) = handleErr $ aiFn inpat inpat ist fc f []
1045 ai env (PHidden (PRef fc f))
1046 | not (f `elem` map fst env) = handleErr $ aiFn inpat False ist fc f []
1047 ai env (PEq fc l r) = let l' = ai env l
1048 r' = ai env r in
1049 PEq fc l' r'
1050 ai env (PRewrite fc l r g) = let l' = ai env l
1051 r' = ai env r
1052 g' = fmap (ai env) g in
1053 PRewrite fc l' r' g'
1054 ai env (PTyped l r) = let l' = ai env l
1055 r' = ai env r in
1056 PTyped l' r'
1057 ai env (PPair fc l r) = let l' = ai env l
1058 r' = ai env r in
1059 PPair fc l' r'
1060 ai env (PDPair fc l t r) = let l' = ai env l
1061 t' = ai env t
1062 r' = ai env r in
1063 PDPair fc l' t' r'
1064 ai env (PAlternative a as) = let as' = map (ai env) as in
1065 PAlternative a as'
1066 ai env (PApp fc (PInferRef _ f) as)
1067 = let as' = map (fmap (ai env)) as in
1068 PApp fc (PInferRef fc f) as'
1069 ai env (PApp fc ftm@(PRef _ f) as)
1070 | f `elem` infns = ai env (PApp fc (PInferRef fc f) as)
1071 | not (f `elem` map fst env)
1072 = let as' = map (fmap (ai env)) as in
1073 handleErr $ aiFn inpat False ist fc f as'
1074 | Just (Just ty) <- lookup f env
1075 = let as' = map (fmap (ai env)) as
1076 arity = getPArity ty in
1077 mkPApp fc arity ftm as'
1078 ai env (PApp fc f as) = let f' = ai env f
1079 as' = map (fmap (ai env)) as in
1080 mkPApp fc 1 f' as'
1081 ai env (PCase fc c os) = let c' = ai env c
1082 os' = map (pmap (ai env)) os in
1083 PCase fc c' os'
1084 ai env (PLam n ty sc) = let ty' = ai env ty
1085 sc' = ai ((n, Just ty):env) sc in
1086 PLam n ty' sc'
1087 ai env (PLet n ty val sc)
1088 = let ty' = ai env ty
1089 val' = ai env val
1090 sc' = ai ((n, Just ty):env) sc in
1091 PLet n ty' val' sc'
1092 ai env (PPi p n ty sc) = let ty' = ai env ty
1093 sc' = ai ((n, Just ty):env) sc in
1094 PPi p n ty' sc'
1095 ai env (PGoal fc r n sc) = let r' = ai env r
1096 sc' = ai ((n, Nothing):env) sc in
1097 PGoal fc r' n sc'
1098 ai env (PHidden tm) = PHidden (ai env tm)
1099 ai env (PProof ts) = PProof (map (fmap (ai env)) ts)
1100 ai env (PTactics ts) = PTactics (map (fmap (ai env)) ts)
1101 ai env (PRefl fc tm) = PRefl fc (ai env tm)
1102 ai env (PUnifyLog tm) = PUnifyLog (ai env tm)
1103 ai env tm = tm
1105 handleErr (Left err) = PElabError err
1106 handleErr (Right x) = x
1108-- if in a pattern, and there are no arguments, and there's no possible
1109-- names with zero explicit arguments, don't add implicits.
1111aiFn :: Bool -> Bool -> IState -> FC -> Name -> [PArg] -> Either Err PTerm
1112aiFn inpat True ist fc f []
1113 = case lookupDef f (tt_ctxt ist) of
1114 [] -> Right $ PPatvar fc f
1115 alts -> let ialts = lookupCtxt f (idris_implicits ist) in
1116 -- trace (show f ++ " " ++ show (fc, any (all imp) ialts, ialts, any constructor alts)) $
1117 if (not (vname f) || tcname f
1118 || any constructor alts || any allImp ialts)
1119 then aiFn inpat False ist fc f [] -- use it as a constructor
1120 else Right $ PPatvar fc f
1121 where imp (PExp _ _ _ _) = False
1122 imp _ = True
1123 allImp [] = False
1124 allImp xs = all imp xs
1125 constructor (TyDecl (DCon _ _) _) = True
1126 constructor _ = False
1128 vname (UN n) = True -- non qualified
1129 vname _ = False
1131aiFn inpat expat ist fc f as
1132 | f `elem` primNames = Right $ PApp fc (PRef fc f) as
1133aiFn inpat expat ist fc f as
1134 -- This is where namespaces get resolved by adding PAlternative
1135 = case lookupCtxtName f (idris_implicits ist) of
1136 [(f',ns)] -> Right $ mkPApp fc (length ns) (PRef fc f') (insertImpl ns as)
1137 [] -> if f `elem` idris_metavars ist
1138 then Right $ PApp fc (PRef fc f) as
1139 else Right $ mkPApp fc (length as) (PRef fc f) as
1140 alts -> Right $
1141 PAlternative True $
1142 map (\(f', ns) -> mkPApp fc (length ns) (PRef fc f')
1143 (insertImpl ns as)) alts
1144 where
1145 insertImpl :: [PArg] -> [PArg] -> [PArg]
1146 insertImpl (PExp p l ty _ : ps) (PExp _ _ tm d : given) =
1147 PExp p l tm d : insertImpl ps given
1148 insertImpl (PConstraint p l ty _ : ps) (PConstraint _ _ tm d : given) =
1149 PConstraint p l tm d : insertImpl ps given
1150 insertImpl (PConstraint p l ty d : ps) given =
1151 PConstraint p l (PResolveTC fc) d : insertImpl ps given
1152 insertImpl (PImp p l n ty d : ps) given =
1153 case find n given [] of
1154 Just (tm, given') -> PImp p l n tm "" : insertImpl ps given'
1155 Nothing -> PImp p l n Placeholder "" : insertImpl ps given
1156 insertImpl (PTacImplicit p l n sc ty d : ps) given =
1157 case find n given [] of
1158 Just (tm, given') -> PTacImplicit p l n sc tm "" : insertImpl ps given'
1159 Nothing -> if inpat
1160 then PTacImplicit p l n sc Placeholder "" : insertImpl ps given
1161 else PTacImplicit p l n sc sc "" : insertImpl ps given
1162 insertImpl expected [] = []
1163 insertImpl _ given = given
1165 find n [] acc = Nothing
1166 find n (PImp _ _ n' t _ : gs) acc
1167 | n == n' = Just (t, reverse acc ++ gs)
1168 find n (PTacImplicit _ _ n' _ t _ : gs) acc
1169 | n == n' = Just (t, reverse acc ++ gs)
1170 find n (g : gs) acc = find n gs (g : acc)
1172-- replace non-linear occurrences with _
1173-- ASSUMPTION: This is called before adding 'alternatives' because otherwise
1174-- it is hard to get right!
1176stripLinear :: IState -> PTerm -> PTerm
1177stripLinear i tm = evalState (sl tm) [] where
1178 sl :: PTerm -> State [Name] PTerm
1179 sl (PRef fc f)
1180 | (_:_) <- lookupTy f (tt_ctxt i)
1181 = return $ PRef fc f
1182 | otherwise = do ns <- get
1183 if (f `elem` ns)
1184 then return Placeholder
1185 else do put (f : ns)
1186 return (PRef fc f)
1187 sl (PPatvar fc f)
1188 = do ns <- get
1189 if (f `elem` ns)
1190 then return Placeholder
1191 else do put (f : ns)
1192 return (PPatvar fc f)
1193 sl (PApp fc fn args) = do fn' <- sl fn
1194 args' <- mapM slA args
1195 return $ PApp fc fn' args'
1196 where slA (PImp p l n t d) = do t' <- sl t
1197 return $ PImp p l n t' d
1198 slA (PExp p l t d) = do t' <- sl t
1199 return $ PExp p l t' d
1200 slA (PConstraint p l t d)
1201 = do t' <- sl t
1202 return $ PConstraint p l t' d
1203 slA (PTacImplicit p l n sc t d)
1204 = do t' <- sl t
1205 return $ PTacImplicit p l n sc t' d
1206 sl x = return x
1208mkPApp fc a f [] = f
1209mkPApp fc a f as = let rest = drop a as in
1210 appRest fc (PApp fc f (take a as)) rest
1211 where
1212 appRest fc f [] = f
1213 appRest fc f (a : as) = appRest fc (PApp fc f [a]) as
1215-- Find 'static' argument positions
1216-- (the declared ones, plus any names in argument position in the declared
1217-- statics)
1218-- FIXME: It's possible that this really has to happen after elaboration
1220findStatics :: IState -> PTerm -> (PTerm, [Bool])
1221findStatics ist tm = trace (showImp Nothing True False tm) $
1222 let (ns, ss) = fs tm in
1223 runState (pos ns ss tm) []
1224 where fs (PPi p n t sc)
1225 | Static <- pstatic p
1226 = let (ns, ss) = fs sc in
1227 (namesIn [] ist t : ns, n : ss)
1228 | otherwise = let (ns, ss) = fs sc in
1229 (ns, ss)
1230 fs _ = ([], [])
1232 inOne n ns = length (filter id (map (elem n) ns)) == 1
1234 pos ns ss (PPi p n t sc)
1235 | elem n ss = do sc' <- pos ns ss sc
1236 spos <- get
1237 put (True : spos)
1238 return (PPi (p { pstatic = Static }) n t sc')
1239 | otherwise = do sc' <- pos ns ss sc
1240 spos <- get
1241 put (False : spos)
1242 return (PPi p n t sc')
1243 pos ns ss t = return t
1245-- Debugging/logging stuff
1247dumpDecls :: [PDecl] -> String
1248dumpDecls [] = ""
1249dumpDecls (d:ds) = dumpDecl d ++ "\n" ++ dumpDecls ds
1251dumpDecl (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
1252dumpDecl (PTy _ _ _ _ n t) = "tydecl " ++ show n ++ " : " ++ showImp Nothing True False t
1253dumpDecl (PClauses _ _ n cs) = "pat " ++ show n ++ "\t" ++ showSep "\n\t" (map (showCImp True) cs)
1254dumpDecl (PData _ _ _ _ d) = showDImp True d
1255dumpDecl (PParams _ ns ps) = "params {" ++ show ns ++ "\n" ++ dumpDecls ps ++ "}\n"
1256dumpDecl (PNamespace n ps) = "namespace {" ++ n ++ "\n" ++ dumpDecls ps ++ "}\n"
1257dumpDecl (PSyntax _ syn) = "syntax " ++ show syn
1258dumpDecl (PClass _ _ _ cs n ps ds)
1259 = "class " ++ show cs ++ " " ++ show n ++ " " ++ show ps ++ "\n" ++ dumpDecls ds
1260dumpDecl (PInstance _ _ cs n _ t _ ds)
1261 = "instance " ++ show cs ++ " " ++ show n ++ " " ++ show t ++ "\n" ++ dumpDecls ds
1262dumpDecl _ = "..."
1263-- dumpDecl (PImport i) = "import " ++ i
1265-- for 6.12/7 compatibility
1266data EitherErr a b = LeftErr a | RightOK b
1268instance Monad (EitherErr a) where
1269 return = RightOK
1271 (LeftErr e) >>= k = LeftErr e
1272 RightOK v >>= k = k v
1274toEither (LeftErr e) = Left e
1275toEither (RightOK ho) = Right ho
1277-- syntactic match of a against b, returning pair of variables in a
1278-- and what they match. Returns the pair that failed if not a match.
1280matchClause :: IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1281matchClause = matchClause' False
1283matchClause' :: Bool -> IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)]
1284matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
1285 matchArg x y = match (fullApp (getTm x)) (fullApp (getTm y))
1287 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1288 fullApp x = x
1290 match' x y = match (fullApp x) (fullApp y)
1291 match (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x]) x'
1292 | PConstant (I _) <- getTm x = match (getTm x) x'
1293 match x' (PApp _ (PRef _ (NS (UN "fromInteger") ["builtins"])) [_,_,x])
1294 | PConstant (I _) <- getTm x = match (getTm x) x'
1295 match (PApp _ (PRef _ (UN "lazy")) [_,x]) x' = match (getTm x) x'
1296 match x (PApp _ (PRef _ (UN "lazy")) [_,x']) = match x (getTm x')
1297 match (PApp _ f args) (PApp _ f' args')
1298 | length args == length args'
1299 = do mf <- match' f f'
1300 ms <- zipWithM matchArg args args'
1301 return (mf ++ concat ms)
1302-- match (PRef _ n) (PRef _ n') | n == n' = return []
1303-- | otherwise = Nothing
1304 match (PRef f n) (PApp _ x []) = match (PRef f n) x
1305 match (PPatvar f n) xr = match (PRef f n) xr
1306 match xr (PPatvar f n) = match xr (PRef f n)
1307 match (PApp _ x []) (PRef f n) = match x (PRef f n)
1308 match (PRef _ n) tm@(PRef _ n')
1309 | n == n' && not names &&
1310 (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1311 = return [(n, tm)]
1312 | n == n' = return []
1313 match (PRef _ n) tm
1314 | not names && (not (isConName n (tt_ctxt i)) || tm == Placeholder)
1315 = return [(n, tm)]
1316 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
1317 mr <- match' r r'
1318 return (ml ++ mr)
1319 match (PRewrite _ l r _) (PRewrite _ l' r' _)
1320 = do ml <- match' l l'
1321 mr <- match' r r'
1322 return (ml ++ mr)
1323 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
1324 mr <- match r r'
1325 return (ml ++ mr)
1326 match (PTyped l r) x = match l x
1327 match x (PTyped l r) = match x l
1328 match (PPair _ l r) (PPair _ l' r') = do ml <- match' l l'
1329 mr <- match' r r'
1330 return (ml ++ mr)
1331 match (PDPair _ l t r) (PDPair _ l' t' r') = do ml <- match' l l'
1332 mt <- match' t t'
1333 mr <- match' r r'
1334 return (ml ++ mt ++ mr)
1335 match (PAlternative a as) (PAlternative a' as')
1336 = do ms <- zipWithM match' as as'
1337 return (concat ms)
1338 match a@(PAlternative _ as) b
1339 = do let ms = zipWith match' as (repeat b)
1340 case (rights (map toEither ms)) of
1341 (x: _) -> return x
1342 _ -> LeftErr (a, b)
1343 match (PCase _ _ _) _ = return [] -- lifted out
1344 match (PMetavar _) _ = return [] -- modified
1345 match (PInferRef _ _) _ = return [] -- modified
1346 match (PQuote _) _ = return []
1347 match (PProof _) _ = return []
1348 match (PTactics _) _ = return []
1349 match (PRefl _ _) (PRefl _ _) = return []
1350 match (PResolveTC _) (PResolveTC _) = return []
1351 match (PTrue _) (PTrue _) = return []
1352 match (PFalse _) (PFalse _) = return []
1353 match (PReturn _) (PReturn _) = return []
1354 match (PPi _ _ t s) (PPi _ _ t' s') = do mt <- match' t t'
1355 ms <- match' s s'
1356 return (mt ++ ms)
1357 match (PLam _ t s) (PLam _ t' s') = do mt <- match' t t'
1358 ms <- match' s s'
1359 return (mt ++ ms)
1360 match (PLet _ t ty s) (PLet _ t' ty' s') = do mt <- match' t t'
1361 mty <- match' ty ty'
1362 ms <- match' s s'
1363 return (mt ++ mty ++ ms)
1364 match (PHidden x) (PHidden y) = match' x y
1365 match (PUnifyLog x) y = match' x y
1366 match x (PUnifyLog y) = match' x y
1367 match Placeholder _ = return []
1368 match _ Placeholder = return []
1369 match (PResolveTC _) _ = return []
1370 match a b | a == b = return []
1371 | otherwise = LeftErr (a, b)
1373 checkRpts (RightOK ms) = check ms where
1374 check ((n,t):xs)
1375 | Just t' <- lookup n xs = if t/=t' && t/=Placeholder && t'/=Placeholder
1376 then Left (t, t')
1377 else check xs
1378 check (_:xs) = check xs
1379 check [] = Right ms
1380 checkRpts (LeftErr x) = Left x
1382substMatches :: [(Name, PTerm)] -> PTerm -> PTerm
1383substMatches ms = substMatchesShadow ms []
1385substMatchesShadow :: [(Name, PTerm)] -> [Name] -> PTerm -> PTerm
1386substMatchesShadow [] shs t = t
1387substMatchesShadow ((n,tm):ns) shs t
1388 = substMatchShadow n shs tm (substMatchesShadow ns shs t)
1390substMatch :: Name -> PTerm -> PTerm -> PTerm
1391substMatch n = substMatchShadow n []
1393substMatchShadow :: Name -> [Name] -> PTerm -> PTerm -> PTerm
1394substMatchShadow n shs tm t = sm shs t where
1395 sm xs (PRef _ n') | n == n' = tm
1396 sm xs (PLam x t sc) = PLam x (sm xs t) (sm xs sc)
1397 sm xs (PPi p x t sc)
1398 | x `elem` xs
1399 = let x' = nextName x in
1400 PPi p x' (sm (x':xs) (substMatch x (PRef (FC "" 0) x') t))
1401 (sm (x':xs) (substMatch x (PRef (FC "" 0) x') sc))
1402 | otherwise = PPi p x (sm xs t) (sm (x : xs) sc)
1403 sm xs (PApp f x as) = fullApp $ PApp f (sm xs x) (map (fmap (sm xs)) as)
1404 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
1405 sm xs (PEq f x y) = PEq f (sm xs x) (sm xs y)
1406 sm xs (PRewrite f x y tm) = PRewrite f (sm xs x) (sm xs y)
1407 (fmap (sm xs) tm)
1408 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
1409 sm xs (PPair f x y) = PPair f (sm xs x) (sm xs y)
1410 sm xs (PDPair f x t y) = PDPair f (sm xs x) (sm xs t) (sm xs y)
1411 sm xs (PAlternative a as) = PAlternative a (map (sm xs) as)
1412 sm xs (PHidden x) = PHidden (sm xs x)
1413 sm xs (PUnifyLog x) = PUnifyLog (sm xs x)
1414 sm xs x = x
1416 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
1417 fullApp x = x
1419shadow :: Name -> Name -> PTerm -> PTerm
1420shadow n n' t = sm t where
1421 sm (PRef fc x) | n == x = PRef fc n'
1422 sm (PLam x t sc) = PLam x (sm t) (sm sc)
1423 sm (PPi p x t sc) = PPi p x (sm t) (sm sc)
1424 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
1425 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
1426 sm (PEq f x y) = PEq f (sm x) (sm y)
1427 sm (PRewrite f x y tm) = PRewrite f (sm x) (sm y) (fmap sm tm)
1428 sm (PTyped x y) = PTyped (sm x) (sm y)
1429 sm (PPair f x y) = PPair f (sm x) (sm y)
1430 sm (PDPair f x t y) = PDPair f (sm x) (sm t) (sm y)
1431 sm (PAlternative a as) = PAlternative a (map sm as)
1432 sm (PHidden x) = PHidden (sm x)
1433 sm (PUnifyLog x) = PUnifyLog (sm x)
1434 sm x = x