on master help sign in
Merged with master
commit20e0bf4d85d05dd1bc603577671f9db312f3215f authorPhilip Rasmussen <pjor@itu.dk> dateThu 3 Apr 2014, 09:12 (13 years ago) parent0939fb53820110
36 files changed+493−301
idris.cabal+1 libs/base/Data/HVect.idr+1 libs/prelude/Prelude/Applicative.idr+2 libs/prelude/Prelude/Chars.idr+3 libs/prelude/Prelude/Fin.idr+5 libs/prelude/Prelude/List.idr+8 libs/prelude/Prelude/Nat.idr+4 libs/prelude/Prelude/Uninhabited.idr+2−7 libs/prelude/Prelude/Vect.idr+2 rts/idris_rts.c+12−3 src/IRTS/CodegenC.hs+26−10 src/IRTS/CodegenCommon.hs+25 src/IRTS/CodegenJava.hs+13−8 src/IRTS/CodegenJavaScript.hs+11−3 src/IRTS/CodegenLLVM.hs+13−8 src/IRTS/Compiler.hs+14−23 src/Idris/AbsSyntax.hs+17−142 src/Idris/AbsSyntaxTree.hs+29−30 src/Idris/CaseSplit.hs+1 src/Idris/Core/TT.hs+8−6 src/Idris/Coverage.hs+20−7 src/Idris/Delaborate.hs+2−7 src/Idris/ElabDecls.hs+3−1 src/Idris/ElabTerm.hs+1 src/Idris/Error.hs+1 src/Idris/IBC.hs+7−3 src/Idris/IdeSlave.hs+13−8 src/Idris/Output.hs+173 src/Idris/ParseHelpers.hs+1 src/Idris/ParseOps.hs+6−1 src/Idris/Parser.hs+9 src/Idris/Prover.hs+1 src/Idris/REPL.hs+55−24 src/Pkg/Package.hs+1 src/Util/LLVMStubs.hs+2−9 test/error004/FunErrTest.idr+1−1
idris.cabal+1
@@ -477,6 +477,7 @@ Library
477477 , Idris.IdrisDoc
478478 , Idris.Imports
479479 , Idris.Inliner
480+ , Idris.Output
480481 , Idris.Parser
481482 , Idris.ParseHelpers
482483 , Idris.ParseOps
libs/base/Data/HVect.idr+1
@@ -19,6 +19,7 @@ using (k : Nat, ts : Vect k Type)
1919 deleteAt : {us : Vect (S l) Type} -> (i : Fin (S l)) -> HVect us -> HVect (deleteAt i us)
2020 deleteAt fZ (x::xs) = xs
2121 deleteAt {l = S m} (fS j) (x::xs) = x :: deleteAt j xs
22+ deleteAt {l = Z} (fS j) (x::xs) = absurd j
2223 deleteAt _ [] impossible
2324
2425 replaceAt : (i : Fin k) -> t -> HVect ts -> HVect (replaceAt i t ts)
libs/prelude/Prelude/Applicative.idr+2
@@ -1,6 +1,8 @@
11module Prelude.Applicative
22
33import Builtins
4+import Prelude.Basics
5+import Prelude.Classes
46import Prelude.Functor
57
68---- Applicative functors/Idioms
libs/prelude/Prelude/Chars.idr+3
@@ -1,6 +1,9 @@
11module Prelude.Char
22-- Functions operating over Chars
33
4+import Prelude.Bool
5+import Prelude.Classes
6+import Prelude.List
47import Builtins
58
69||| Return the ASCII representation of the character.
libs/prelude/Prelude/Fin.idr+5
@@ -2,6 +2,7 @@ module Prelude.Fin
22
33import Prelude.Nat
44import Prelude.Either
5+import Prelude.Uninhabited
56
67%default total
78
@@ -11,6 +12,10 @@ data Fin : (n : Nat) -> Type where
1112 fZ : Fin (S k)
1213 fS : Fin k -> Fin (S k)
1314
15+instance Uninhabited (Fin Z) where
16+ uninhabited fZ impossible
17+ uninhabited (fS f) impossible
18+
1419fSInjective : (m : Fin k) -> (n : Fin k) -> fS m = fS n -> m = n
1520fSInjective left _ refl = refl
1621
libs/prelude/Prelude/List.idr+8
@@ -422,6 +422,14 @@ split p xs =
422422 (chunk, []) => [chunk]
423423 (chunk, (c :: rest)) => chunk :: split p (assert_smaller xs rest)
424424
425+||| A tuple where the first element is a List of the n first elements and
426+||| the second element is a List of the remaining elements of the list
427+||| It is equivalent to (take n xs, drop n xs)
428+||| @ n the index to split at
429+||| @ xs the list to split in two
430+splitAt : (n : Nat) -> (xs : List a) -> (List a, List a)
431+splitAt n xs = (take n xs, drop n xs)
432+
425433partition : (a -> Bool) -> List a -> (List a, List a)
426434partition p [] = ([], [])
427435partition p (x::xs) =
libs/prelude/Prelude/Nat.idr+4
@@ -6,6 +6,7 @@ import Prelude.Algebra
66import Prelude.Bool
77import Prelude.Cast
88import Prelude.Classes
9+import Prelude.Uninhabited
910
1011%access public
1112%default total
@@ -20,6 +21,9 @@ import Prelude.Classes
2021-- name hints for interactive editing
2122%name Nat k,j,i,n,m
2223
24+instance Uninhabited (Z = S n) where
25+ uninhabited refl impossible
26+
2327--------------------------------------------------------------------------------
2428-- Syntactic tests
2529--------------------------------------------------------------------------------
libs/prelude/Prelude/Uninhabited.idr+2−7
@@ -1,18 +1,13 @@
11module Prelude.Uninhabited
22
3+import Builtins
4+
35||| A canonical proof that some type is empty
46class Uninhabited t where
57 ||| If I have a t, I've had a contradiction
68 ||| @ t the uninhabited type
79 total uninhabited : t -> _|_
810
9−instance Uninhabited (Fin Z) where
10− uninhabited fZ impossible
11− uninhabited (fS f) impossible
12−
13−instance Uninhabited (Z = S n) where
14− uninhabited refl impossible
15−
1611||| Use an absurd assumption to discharge a proof obligation
1712||| @ t some empty type
1813||| @ a the goal type
libs/prelude/Prelude/Vect.idr+2
@@ -7,6 +7,7 @@ import Prelude.List
77import Prelude.Classes
88import Prelude.Nat
99import Prelude.Bool
10+import Prelude.Uninhabited
1011
1112%access public
1213%default total
@@ -71,6 +72,7 @@ index fZ [] impossible
7172deleteAt : Fin (S n) -> Vect (S n) a -> Vect n a
7273deleteAt fZ (x::xs) = xs
7374deleteAt {n = S m} (fS k) (x::xs) = x :: deleteAt k xs
75+deleteAt {n = Z} (fS k) (x::xs) = absurd k
7476deleteAt _ [] impossible
7577
7678||| Replace an element at a particlar index with another
rts/idris_rts.c+12−3
@@ -37,9 +37,18 @@ VM* init_vm(int stack_size, size_t heap_size,
3737 vm->inbox_ptr = vm->inbox;
3838 vm->inbox_write = vm->inbox;
3939
40+ // The allocation lock must be reentrant. The lock exists to ensure that
41+ // no memory is allocated during the message sending process, but we also
42+ // check the lock in calls to allocate.
43+ // The problem comes when we use requireAlloc to guarantee a chunk of memory
44+ // first: this sets the lock, and since it is not reentrant, we get a deadlock.
45+ pthread_mutexattr_t rec_attr;
46+ pthread_mutexattr_init(&rec_attr);
47+ pthread_mutexattr_settype(&rec_attr, PTHREAD_MUTEX_RECURSIVE);
48+
4049 pthread_mutex_init(&(vm->inbox_lock), NULL);
4150 pthread_mutex_init(&(vm->inbox_block), NULL);
42− pthread_mutex_init(&(vm->alloc_lock), NULL);
51+ pthread_mutex_init(&(vm->alloc_lock), &rec_attr);
4352 pthread_cond_init(&(vm->inbox_waiting), NULL);
4453
4554 vm->max_threads = max_threads;
@@ -72,14 +81,14 @@ void idris_requireAlloc(VM* vm, size_t size) {
7281 }
7382
7483 int lock = vm->processes > 0;
75− if (lock) { // not message passing
84+ if (lock) { // We only need to lock if we're in concurrent mode
7685 pthread_mutex_lock(&vm->alloc_lock);
7786 }
7887}
7988
8089void idris_doneAlloc(VM* vm) {
8190 int lock = vm->processes > 0;
82− if (lock) { // not message passing
91+ if (lock) { // We only need to lock if we're in concurrent mode
8392 pthread_mutex_unlock(&vm->alloc_lock);
8493 }
8594}
src/IRTS/CodegenC.hs+26−10
@@ -20,16 +20,32 @@ import System.Directory
2020import System.FilePath ((</>), (<.>))
2121import Control.Monad
2222
23−codegenC :: [(Name, SDecl)] ->
24− String -> -- output file name
25− OutputType -> -- generate executable if True, only .o if False
26− [FilePath] -> -- include files
27− String -> -- extra object files
28− String -> -- extra compiler flags (libraries)
29− String -> -- extra compiler flags (anything)
30− DbgLevel ->
31− IO ()
32−codegenC defs out exec incs objs libs flags dbg
23+codegenC :: CodeGenerator
24+codegenC ci = codegenC' (simpleDecls ci)
25+ (outputFile ci)
26+ (outputType ci)
27+ (includes ci)
28+ (concatMap mkObj (compileObjs ci))
29+ (concatMap mkLib (compileLibs ci) ++
30+ concatMap incdir (importDirs ci))
31+ (concatMap mkFlag (compilerFlags ci))
32+ (debugLevel ci)
33+
34+ where mkObj f = f ++ " "
35+ mkLib l = "-l" ++ l ++ " "
36+ mkFlag l = l ++ " "
37+ incdir i = "-I" ++ i ++ " "
38+
39+codegenC' :: [(Name, SDecl)] ->
40+ String -> -- output file name
41+ OutputType -> -- generate executable if True, only .o if False
42+ [FilePath] -> -- include files
43+ String -> -- extra object files
44+ String -> -- extra compiler flags (libraries)
45+ String -> -- extra compiler flags (anything)
46+ DbgLevel ->
47+ IO ()
48+codegenC' defs out exec incs objs libs flags dbg
3349 = do -- print defs
3450 let bc = map toBC defs
3551 let h = concatMap toDecl (map fst bc)
src/IRTS/CodegenCommon.hs+25
@@ -2,8 +2,11 @@ module IRTS.CodegenCommon where
22
33import Idris.Core.TT
44import IRTS.Simplified
5+import IRTS.Defunctionalise
6+import IRTS.Lang
57
68import Control.Exception
9+import Data.Word
710import System.Environment
811
912data DbgLevel = NONE | DEBUG | TRACE deriving Eq
@@ -13,3 +16,25 @@ environment :: String -> IO (Maybe String)
1316environment x = Control.Exception.catch (do e <- getEnv x
1417 return (Just e))
1518 (\y-> do return (y::SomeException); return Nothing)
19+
20+-- Everything which might be needed in a code generator - a CG can choose which
21+-- level of Decls to generate code from (simplified, defunctionalised or merely
22+-- lambda lifted) and has access to the list of object files, libraries, etc.
23+
24+data CodegenInfo = CodegenInfo { outputFile :: String,
25+ outputType :: OutputType,
26+ targetTriple :: String,
27+ targetCPU :: String,
28+ optimisation :: Word,
29+ includes :: [FilePath],
30+ importDirs :: [FilePath],
31+ compileObjs :: [String],
32+ compileLibs :: [String],
33+ compilerFlags :: [String],
34+ debugLevel :: DbgLevel,
35+ simpleDecls :: [(Name, SDecl)],
36+ defunDecls :: [(Name, DDecl)],
37+ liftDecls :: [(Name, LDecl)]
38+ }
39+
40+type CodeGenerator = CodegenInfo -> IO ()
src/IRTS/CodegenJava.hs+13−8
@@ -34,14 +34,19 @@ import System.Process
3434
3535-----------------------------------------------------------------------
3636-- Main function
37−codegenJava :: [(Name, SExp)] -> -- initialization of globals
38− [(Name, SDecl)] -> -- decls
39− FilePath -> -- output file name
40− [String] -> -- headers
41− [String] -> -- libs
42− OutputType ->
43− IO ()
44−codegenJava globalInit defs out hdrs libs exec =
37+codegenJava :: CodeGenerator
38+codegenJava cg = codegenJava' [] (simpleDecls cg) (outputFile cg)
39+ (includes cg) (compileLibs cg)
40+ (outputType cg)
41+
42+codegenJava' :: [(Name, SExp)] -> -- initialization of globals
43+ [(Name, SDecl)] -> -- decls
44+ FilePath -> -- output file name
45+ [String] -> -- headers
46+ [String] -> -- libs
47+ OutputType ->
48+ IO ()
49+codegenJava' globalInit defs out hdrs libs exec =
4550 withTgtDir exec out (codegenJava' exec)
4651 where
4752 codegenJava' :: OutputType -> FilePath -> IO ()
src/IRTS/CodegenJavaScript.hs+11−3
@@ -1,6 +1,6 @@
11{-# LANGUAGE PatternGuards #-}
22
3−module IRTS.CodegenJavaScript (codegenJavaScript, JSTarget(..)) where
3+module IRTS.CodegenJavaScript (codegenJavaScript, codegenNode, JSTarget(..)) where
44
55import Idris.AbsSyntax hiding (TypeCase)
66import IRTS.Bytecode
@@ -1389,14 +1389,22 @@ getGlobalCons js = foldJS match (++) [] js
13891389getIncludes :: [FilePath] -> IO [String]
13901390getIncludes = mapM readFile
13911391
1392−codegenJavaScript
1392+codegenJavaScript :: CodeGenerator
1393+codegenJavaScript ci = codegenJS_all JavaScript (simpleDecls ci)
1394+ (includes ci) (outputFile ci) (outputType ci)
1395+
1396+codegenNode :: CodeGenerator
1397+codegenNode ci = codegenJS_all Node (simpleDecls ci)
1398+ (includes ci) (outputFile ci) (outputType ci)
1399+
1400+codegenJS_all
13931401 :: JSTarget
13941402 -> [(Name, SDecl)]
13951403 -> [FilePath]
13961404 -> FilePath
13971405 -> OutputType
13981406 -> IO ()
1399−codegenJavaScript target definitions includes filename outputType = do
1407+codegenJS_all target definitions includes filename outputType = do
14001408 let (header, rt) = case target of
14011409 Node ->
14021410 ("#!/usr/bin/env node\n", "-node")
src/IRTS/CodegenLLVM.hs+13−8
@@ -58,14 +58,19 @@ import Debug.Trace
5858
5959data Target = Target { triple :: String, dataLayout :: DataLayout }
6060
61−codegenLLVM :: [(TT.Name, SDecl)] ->
62− String -> -- target triple
63− String -> -- target CPU
64− Word -> -- Optimization degree
65− FilePath -> -- output file name
66− OutputType ->
67− IO ()
68−codegenLLVM defs triple cpu optimize file outty = withContext $ \context -> do
61+codegenLLVM :: CodeGenerator
62+codegenLLVM ci = codegenLLVM' (simpleDecls ci) (targetTriple ci)
63+ (targetCPU ci) (optimisation ci)
64+ (outputFile ci) (outputType ci)
65+
66+codegenLLVM' :: [(TT.Name, SDecl)] ->
67+ String -> -- target triple
68+ String -> -- target CPU
69+ Word -> -- Optimization degree
70+ FilePath -> -- output file name
71+ OutputType ->
72+ IO ()
73+codegenLLVM' defs triple cpu optimize file outty = withContext $ \context -> do
6974 initializeAllTargets
7075 (target, _) <- failInIO $ lookupTarget Nothing triple
7176 withTargetOptions $ \options ->
src/IRTS/Compiler.hs+14−23
@@ -71,25 +71,22 @@ compile codegen f tm
7171 case dumpDefun of
7272 Nothing -> return ()
7373 Just f -> runIO $ writeFile f (dumpDefuns defuns)
74− triple <- targetTriple
75− cpu <- targetCPU
76− optimize <- optLevel
74+ triple <- Idris.AbsSyntax.targetTriple
75+ cpu <- Idris.AbsSyntax.targetCPU
76+ optimise <- optLevel
7777 iLOG "Building output"
78+
7879 case checked of
79− OK c -> runIO $ case codegen of
80− ViaC ->
81− codegenC c f outty hdrs
82− (concatMap mkObj objs)
83− (concatMap mkLib libs)
84− (concatMap mkFlag flags ++
85− concatMap incdir impdirs) NONE
86− ViaJava ->
87− codegenJava [] c f hdrs libs outty
88− ViaJavaScript ->
89− codegenJavaScript JavaScript c hdrs f outty
90− ViaNode ->
91− codegenJavaScript Node c hdrs f outty
92− ViaLLVM -> codegenLLVM c triple cpu optimize f outty
80+ OK c -> do let cginfo = CodegenInfo f outty triple cpu optimise
81+ hdrs impdirs objs libs flags
82+ NONE c (toAlist defuns)
83+ tagged
84+ runIO $ case codegen of
85+ ViaC -> codegenC cginfo
86+ ViaJava -> codegenJava cginfo
87+ ViaJavaScript -> codegenJavaScript cginfo
88+ ViaNode -> codegenNode cginfo
89+ ViaLLVM -> codegenLLVM cginfo
9390 Bytecode -> dumpBC c f
9491 Error e -> ierror e
9592 where checkMVs = do i <- getIState
@@ -99,12 +96,6 @@ compile codegen f tm
9996 inDir d h = do let f = d </> h
10097 ex <- doesFileExist f
10198 if ex then return f else return h
102− mkObj f = f ++ " "
103− mkLib l = "-l" ++ l ++ " "
104− mkFlag l = l ++ " "
105−
106− incdir i = "-I" ++ i ++ " "
107−
10899
109100irMain :: TT Name -> Idris LDecl
110101irMain tm = do i <- ir tm
src/Idris/AbsSyntax.hs+17−142
@@ -88,6 +88,10 @@ addDyLib libs = do i <- getIState
8888addHdr :: Codegen -> String -> Idris ()
8989addHdr tgt f = do i <- getIState; putIState $ i { idris_hdrs = nub $ (tgt, f) : idris_hdrs i }
9090
91+addImported :: FilePath -> Idris ()
92+addImported f = do i <- getIState
93+ putIState $ i { idris_imported = nub $ f : idris_imported i }
94+
9195addLangExt :: LanguageExt -> Idris ()
9296addLangExt TypeProviders = do i <- getIState
9397 putIState $ i {
@@ -357,6 +361,9 @@ addNameIdx' i n
357361getHdrs :: Codegen -> Idris [String]
358362getHdrs tgt = do i <- getIState; return (forCodegen tgt $ idris_hdrs i)
359363
364+getImported :: Idris [FilePath]
365+getImported = do i <- getIState; return (idris_imported i)
366+
360367setErrSpan :: FC -> Idris ()
361368setErrSpan x = do i <- getIState;
362369 case (errSpan i) of
@@ -490,6 +497,12 @@ getUndefined :: Idris [Name]
490497getUndefined = do i <- getIState
491498 return (map fst (idris_metavars i) \\ primDefs)
492499
500+isMetavarName :: Name -> IState -> Bool
501+isMetavarName n ist
502+ = case lookupNames n (tt_ctxt ist) of
503+ (t:_) -> isJust $ lookup t (idris_metavars ist)
504+ _ -> False
505+
493506getWidth :: Idris ConsoleWidth
494507getWidth = fmap idris_consolewidth getIState
495508
@@ -505,155 +518,16 @@ renderWidth = do iw <- getWidth
505518 AutomaticWidth -> runIO getScreenWidth
506519
507520
508−iRender :: Doc a -> Idris (SimpleDoc a)
509−iRender d = do w <- getWidth
510− ist <- getIState
511− let ideSlave = case idris_outputmode ist of
512− IdeSlave _ -> True
513− _ -> False
514− case w of
515− InfinitelyWide -> return $ renderPretty 1.0 1000000000 d
516− ColsWide n -> return $
517− if n < 1
518− then renderPretty 1.0 1000000000 d
519− else renderPretty 0.8 n d
520− AutomaticWidth | ideSlave -> return $ renderPretty 1.0 1000000000 d
521− | otherwise -> do width <- runIO getScreenWidth
522− return $ renderPretty 0.8 width d
523−
524−ihPrintResult :: Handle -> String -> Idris ()
525−ihPrintResult h s = do i <- getIState
526− case idris_outputmode i of
527− RawOutput -> case s of
528− "" -> return ()
529− s -> runIO $ hPutStrLn h s
530− IdeSlave n ->
531− let good = SexpList [SymbolAtom "ok", toSExp s] in
532− runIO $ hPutStrLn h $ convSExp "return" good n
533−
534−-- | Write a pretty-printed term to the console with semantic coloring
535−consoleDisplayAnnotated :: Handle -> Doc OutputAnnotation -> Idris ()
536−consoleDisplayAnnotated h output = do ist <- getIState
537− rendered <- iRender $ output
538− runIO . hPutStrLn h .
539− displayDecorated (consoleDecorate ist) $
540− rendered
541−
542−
543−-- | Write pretty-printed output to IDESlave with semantic annotations
544−ideSlaveReturnAnnotated :: Integer -> Handle -> Doc OutputAnnotation -> Idris ()
545−ideSlaveReturnAnnotated n h out = do ist <- getIState
546− (str, spans) <- fmap displaySpans .
547− iRender .
548− fmap (fancifyAnnots ist) $
549− out
550− let good = [SymbolAtom "ok", toSExp str, toSExp spans]
551− runIO . hPutStrLn h $ convSExp "return" good n
552−
553−ihPrintTermWithType :: Handle -> Doc OutputAnnotation -> Doc OutputAnnotation -> Idris ()
554−ihPrintTermWithType h tm ty = do ist <- getIState
555− let output = tm <+> colon <+> ty
556− case idris_outputmode ist of
557− RawOutput -> consoleDisplayAnnotated h output
558− IdeSlave n -> ideSlaveReturnAnnotated n h output
559−
560−-- | Pretty-print a collection of overloadings to REPL or IDESlave - corresponds to :t name
561−ihPrintFunTypes :: Handle -> [(Name, Bool)] -> Name -> [(Name, PTerm)] -> Idris ()
562−ihPrintFunTypes h bnd n [] = ihPrintError h $ "No such variable " ++ show n
563−ihPrintFunTypes h bnd n overloads = do imp <- impShow
564− ist <- getIState
565− let output = vsep (map (uncurry (ppOverload imp)) overloads)
566− case idris_outputmode ist of
567− RawOutput -> consoleDisplayAnnotated h output
568− IdeSlave n -> ideSlaveReturnAnnotated n h output
569− where fullName n = prettyName True bnd n
570− ppOverload imp n tm = fullName n <+> colon <+> align (pprintPTerm imp bnd [] tm)
571−
572−ihRenderResult :: Handle -> Doc OutputAnnotation -> Idris ()
573−ihRenderResult h d = do ist <- getIState
574− case idris_outputmode ist of
575− RawOutput -> consoleDisplayAnnotated h d
576− IdeSlave n -> ideSlaveReturnAnnotated n h d
577−
578−fancifyAnnots :: IState -> OutputAnnotation -> OutputAnnotation
579−fancifyAnnots ist annot@(AnnName n _ _) =
580− do let ctxt = tt_ctxt ist
581− case () of
582− _ | isDConName n ctxt -> AnnName n (Just DataOutput) Nothing
583− _ | isFnName n ctxt -> AnnName n (Just FunOutput) Nothing
584− _ | isTConName n ctxt -> AnnName n (Just TypeOutput) Nothing
585− _ | otherwise -> annot
586−fancifyAnnots _ annot = annot
587521
588522type1Doc :: Doc OutputAnnotation
589523type1Doc = (annotate AnnConstType $ text "Type 1")
590524
591−-- | Show an error with semantic highlighting
592−ihRenderError :: Handle -> Doc OutputAnnotation -> Idris ()
593−ihRenderError h e = do ist <- getIState
594− case idris_outputmode ist of
595− RawOutput -> consoleDisplayAnnotated h e
596− IdeSlave n -> do
597− (str, spans) <- fmap displaySpans .
598− iRender .
599− fmap (fancifyAnnots ist) $
600− e
601− let good = [SymbolAtom "error", toSExp str, toSExp spans]
602− runIO . hPutStrLn h $ convSExp "return" good n
603−
604−ihPrintError :: Handle -> String -> Idris ()
605−ihPrintError h s = do i <- getIState
606− case idris_outputmode i of
607− RawOutput -> case s of
608− "" -> return ()
609− s -> runIO $ hPutStrLn h s
610− IdeSlave n ->
611− let good = SexpList [SymbolAtom "error", toSExp s] in
612− runIO . hPutStrLn h $ convSExp "return" good n
613−
614−ihputStrLn :: Handle -> String -> Idris ()
615−ihputStrLn h s = do i <- getIState
616− case idris_outputmode i of
617− RawOutput -> runIO $ hPutStrLn h s
618− IdeSlave n -> runIO . hPutStrLn h $ convSExp "write-string" s n
619−
620−iputStrLn = ihputStrLn stdout
621−iPrintError = ihPrintError stdout
622−iPrintResult = ihPrintResult stdout
623−iWarn = ihWarn stdout
624−
625−ideslavePutSExp :: SExpable a => String -> a -> Idris ()
626−ideslavePutSExp cmd info = do i <- getIState
627− case idris_outputmode i of
628− IdeSlave n -> runIO . putStrLn $ convSExp cmd info n
629− _ -> return ()
630−
631−-- this needs some typing magic and more structured output towards emacs
632−iputGoal :: SimpleDoc OutputAnnotation -> Idris ()
633−iputGoal g = do i <- getIState
634− case idris_outputmode i of
635− RawOutput -> runIO $ putStrLn (displayDecorated (consoleDecorate i) g)
636− IdeSlave n -> runIO . putStrLn $
637− convSExp "write-goal" (displayS (fmap (fancifyAnnots i) g) "") n
638525
639526isetPrompt :: String -> Idris ()
640527isetPrompt p = do i <- getIState
641528 case idris_outputmode i of
642529 IdeSlave n -> runIO . putStrLn $ convSExp "set-prompt" p n
643530
644−ihWarn :: Handle -> FC -> Doc OutputAnnotation -> Idris ()
645−ihWarn h fc err = do i <- getIState
646− case idris_outputmode i of
647− RawOutput ->
648− do err' <- iRender . fmap (fancifyAnnots i) $
649− text (show fc) <> colon <//> err
650− runIO . hPutStrLn h $ displayDecorated (consoleDecorate i) err'
651− IdeSlave n ->
652− do err' <- iRender . fmap (fancifyAnnots i) $ err
653− let (str, spans) = displaySpans err'
654− runIO . hPutStrLn h $
655− convSExp "warning" (fc_fname fc, fc_start fc, fc_end fc, str, spans) n
656−
657531setLogLevel :: Int -> Idris ()
658532setLogLevel l = do i <- getIState
659533 let opts = idris_options i
@@ -1666,8 +1540,6 @@ matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
16661540 = do mf <- match' f f'
16671541 ms <- zipWithM matchArg args args'
16681542 return (mf ++ concat ms)
1669−-- match (PRef _ n) (PRef _ n') | n == n' = return []
1670−-- | otherwise = Nothing
16711543 match (PRef f n) (PApp _ x []) = match (PRef f n) x
16721544 match (PPatvar f n) xr = match (PRef f n) xr
16731545 match xr (PPatvar f n) = match xr (PRef f n)
@@ -1677,7 +1549,10 @@ matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
16771549 (not (isConName n (tt_ctxt i) || isFnName n (tt_ctxt i))
16781550 || tm == Placeholder)
16791551 = return [(n, tm)]
1680− | n == n' = return []
1552+ -- if one namespace is missing, drop the other
1553+ | n == n' || n == dropNS n' || dropNS n == n' = return []
1554+ where dropNS (NS n _) = n
1555+ dropNS n = n
16811556 match (PRef _ n) tm
16821557 | not names && (not (isConName n (tt_ctxt i) ||
16831558 isFnName n (tt_ctxt i)) || tm == Placeholder)
src/Idris/AbsSyntaxTree.hs+29−30
@@ -91,11 +91,6 @@ data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines sh
9191 | ColsWide Int -- ^ Manually specified - must be positive
9292 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
9393
94−-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
95−-- without typechecking).
96−-- This will include all the functions and data declarations, plus fixity declarations
97−-- and syntax macros.
98−
9994-- | The global state used in the Idris monad
10095data IState = IState {
10196 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
@@ -134,6 +129,7 @@ data IState = IState {
134129 idris_libs :: [(Codegen, String)],
135130 idris_cgflags :: [(Codegen, String)],
136131 idris_hdrs :: [(Codegen, String)],
132+ idris_imported :: [FilePath], -- ^ Imported ibc file names
137133 proof_list :: [(Name, [String])],
138134 errSpan :: Maybe FC,
139135 parserWarnings :: [(FC, Err)],
@@ -225,7 +221,7 @@ idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
225221 emptyContext emptyContext emptyContext emptyContext
226222 emptyContext emptyContext
227223 [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
228− [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
224+ [] [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
229225 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
230226 AutomaticWidth
231227
@@ -1070,13 +1066,13 @@ consoleDecorate ist AnnConstType = let theme = idris_colourTheme ist
10701066consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
10711067consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
10721068consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1073−consoleDecorate ist (AnnName n _ _) = let ctxt = tt_ctxt ist
1074− theme = idris_colourTheme ist
1075− in case () of
1076− _ | isDConName n ctxt -> colouriseData theme
1077− _ | isFnName n ctxt -> colouriseFun theme
1078− _ | isTConName n ctxt -> colouriseType theme
1079− _ | otherwise -> id -- don't colourise unknown names
1069+consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1070+ theme = idris_colourTheme ist
1071+ in case () of
1072+ _ | isDConName n ctxt -> colouriseData theme
1073+ _ | isFnName n ctxt -> colouriseFun theme
1074+ _ | isTConName n ctxt -> colouriseType theme
1075+ _ | otherwise -> id -- don't colourise unknown names
10801076consoleDecorate ist (AnnFC _) = id
10811077consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
10821078 where colour BoldText = IdrisColour Nothing True False True False
@@ -1191,16 +1187,16 @@ pprintPTerm impl bnd docArgs = prettySe 10 bnd
11911187
11921188 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
11931189 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1194− prettySe p bnd (PRefl _ _) = annotate (AnnName eqCon Nothing Nothing) $ text "refl"
1190+ prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
11951191 prettySe p bnd (PResolveTC _) = text "resolvetc"
1196− prettySe p bnd (PTrue _ IsType) = annotate (AnnName unitTy Nothing Nothing) $ text "()"
1197− prettySe p bnd (PTrue _ IsTerm) = annotate (AnnName unitCon Nothing Nothing) $ text "()"
1192+ prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1193+ prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
11981194 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1199− prettySe p bnd (PFalse _) = annotate (AnnName falseTy Nothing Nothing) $ text "_|_"
1195+ prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
12001196 prettySe p bnd (PEq _ l r) =
12011197 bracket p 2 . align . group $
12021198 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1203− where eq = annotate (AnnName eqTy Nothing Nothing) (text "=")
1199+ where eq = annName eqTy (text "=")
12041200 prettySe p bnd (PRewrite _ l r _) =
12051201 bracket p 2 $
12061202 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
@@ -1212,28 +1208,28 @@ pprintPTerm impl bnd docArgs = prettySe 10 bnd
12121208 map (prettySe 10 bnd) elts
12131209 where ann = case pun of
12141210 TypeOrTerm -> id
1215− IsType -> annotate (AnnName pairTy Nothing Nothing)
1216− IsTerm -> annotate (AnnName pairCon Nothing Nothing)
1211+ IsType -> annName pairTy
1212+ IsTerm -> annName pairCon
12171213 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
12181214 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
12191215 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1220− annotate (AnnName sigmaTy Nothing Nothing) lparen <>
1216+ annName sigmaTy lparen <>
12211217 bindingOf n False <+>
1222− annotate (AnnName sigmaTy Nothing Nothing) (text "**") <+>
1218+ annName sigmaTy (text "**") <+>
12231219 prettySe 10 ((n, False):bnd) r <>
1224− annotate (AnnName sigmaTy Nothing Nothing) rparen
1220+ annName sigmaTy rparen
12251221 prettySe p bnd (PDPair _ IsType l t r) =
1226− annotate (AnnName sigmaTy Nothing Nothing) lparen <>
1222+ annName sigmaTy lparen <>
12271223 prettySe 10 bnd l <+>
1228− annotate (AnnName sigmaTy Nothing Nothing) (text "**") <+>
1224+ annName sigmaTy (text "**") <+>
12291225 prettySe 10 bnd r <>
1230− annotate (AnnName sigmaTy Nothing Nothing) rparen
1226+ annName sigmaTy rparen
12311227 prettySe p bnd (PDPair _ IsTerm l t r) =
1232− annotate (AnnName existsCon Nothing Nothing) lparen <>
1228+ annName existsCon lparen <>
12331229 prettySe 10 bnd l <+>
1234− annotate (AnnName existsCon Nothing Nothing) (text "**") <+>
1230+ annName existsCon (text "**") <+>
12351231 prettySe 10 bnd r <>
1236− annotate (AnnName existsCon Nothing Nothing) rparen
1232+ annName existsCon rparen
12371233 prettySe p bnd (PAlternative a as) =
12381234 lparen <> text "|" <> prettyAs <> text "|" <> rparen
12391235 where
@@ -1270,6 +1266,9 @@ pprintPTerm impl bnd docArgs = prettySe 10 bnd
12701266 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
12711267 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
12721268
1269+ annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1270+ annName n = annotate (AnnName n Nothing Nothing Nothing)
1271+
12731272 basename :: Name -> Name
12741273 basename (NS n _) = basename n
12751274 basename n = n
@@ -1335,7 +1334,7 @@ prettyName :: Bool -- ^^ whether to show namespaces
13351334 -> Name -- ^^ the name to pprint
13361335 -> Doc OutputAnnotation
13371336prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1338− | otherwise = annotate (AnnName n Nothing Nothing) (text (strName n))
1337+ | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
13391338 where strName (UN n) = T.unpack n
13401339 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
13411340 | otherwise = strName n
src/Idris/CaseSplit.hs+1
@@ -14,6 +14,7 @@ import Idris.ElabTerm
1414import Idris.Delaborate
1515import Idris.Parser
1616import Idris.Error
17+import Idris.Output
1718
1819import Idris.Core.TT
1920import Idris.Core.Typecheck
src/Idris/Core/TT.hs+8−6
@@ -82,14 +82,16 @@ instance Show FC where
8282 | otherwise = show sl ++ ":" ++ show sc ++ "-" ++ show el ++ ":" ++ show ec
8383
8484-- | Output annotation for pretty-printed name - decides colour
85−data NameOutput = TypeOutput | FunOutput | DataOutput
85+data NameOutput = TypeOutput | FunOutput | DataOutput | MetavarOutput
8686
8787-- | Text formatting output
8888data TextFormatting = BoldText | ItalicText | UnderlineText
8989
9090-- | Output annotations for pretty-printing
91−data OutputAnnotation = AnnName Name (Maybe NameOutput) (Maybe Type)
91+data OutputAnnotation = AnnName Name (Maybe NameOutput) (Maybe String) (Maybe String)
92+ -- ^^ The name, classification, docs overview, and pretty-printed type
9293 | AnnBoundName Name Bool
94+ -- ^^ The name and whether it is implicit
9395 | AnnConstData
9496 | AnnConstType
9597 | AnnKeyword
@@ -312,11 +314,11 @@ instance Sized Name where
312314 size _ = 1
313315
314316instance Pretty Name OutputAnnotation where
315− pretty n@(UN n') = annotate (AnnName n Nothing Nothing) $ text (T.unpack n')
316− pretty n@(NS un s) = annotate (AnnName n Nothing Nothing) . noAnnotate $ pretty un
317− pretty n@(MN i s) = annotate (AnnName n Nothing Nothing) $
317+ pretty n@(UN n') = annotate (AnnName n Nothing Nothing Nothing) $ text (T.unpack n')
318+ pretty n@(NS un s) = annotate (AnnName n Nothing Nothing Nothing) . noAnnotate $ pretty un
319+ pretty n@(MN i s) = annotate (AnnName n Nothing Nothing Nothing) $
318320 lbrace <+> text (T.unpack s) <+> (text . show $ i) <+> rbrace
319− pretty n@(SN s) = annotate (AnnName n Nothing Nothing) $ text (show s)
321+ pretty n@(SN s) = annotate (AnnName n Nothing Nothing Nothing) $ text (show s)
320322
321323instance Pretty [Name] OutputAnnotation where
322324 pretty = encloseSep empty empty comma . map pretty
src/Idris/Coverage.hs+20−7
@@ -9,6 +9,7 @@ import Idris.Core.CaseTree
99import Idris.AbsSyntax
1010import Idris.Delaborate
1111import Idris.Error
12+import Idris.Output (iputStrLn)
1213
1314import Data.List
1415import Data.Either
@@ -17,10 +18,14 @@ import Debug.Trace
1718
1819import Control.Monad.State.Strict
1920
21+-- Generate a pattern from an 'impossible' LHS. (Need this to eliminate the
22+-- pattern clauses which have been provided explicitly from new clause
23+-- generation.)
24+
2025mkPatTm :: PTerm -> Idris Term
2126mkPatTm t = do i <- getIState
2227 let timp = addImpl' True [] [] i t
23− evalStateT (toTT timp) 0
28+ evalStateT (toTT (mapPT deNS timp)) 0
2429 where
2530 toTT (PRef _ n) = do i <- lift getIState
2631 case lookupDef n (tt_ctxt i) of
@@ -29,10 +34,16 @@ mkPatTm t = do i <- getIState
2934 toTT (PApp _ t args) = do t' <- toTT t
3035 args' <- mapM (toTT . getTm) args
3136 return $ mkApp t' args'
37+ -- For alternatives, pick the first and drop the namespaces. It doesn't
38+ -- really matter which is taken since matching will ignore the namespace.
39+ toTT (PAlternative _ (a : as)) = toTT a
3240 toTT _ = do v <- get
3341 put (v + 1)
3442 return (P Bound (sMN v "imp") Erased)
3543
44+ deNS (PRef f (NS n _)) = PRef f n
45+ deNS t = t
46+
3647-- Given a list of LHSs, generate a extra clauses which cover the remaining
3748-- cases. The ones which haven't been provided are marked 'absurd' so that the
3849-- checker will make sure they can't happen.
@@ -49,10 +60,10 @@ genClauses fc n xs given
4960 logLvl 5 $ "COVERAGE of " ++ show n
5061 logLvl 5 $ show (map length argss) ++ "\n" ++ show (map length all_args)
5162 logLvl 10 $ show argss ++ "\n" ++ show all_args
52− logLvl 10 $ "Original: \n" ++
63+ logLvl 1 $ "Original: \n" ++
5364 showSep "\n" (map (\t -> showTm i (delab' i t True True)) xs)
5465 -- add an infinite supply of explicit arguments to update the possible
55− -- cases for (the return type may be variadic, or function type, sp
66+ -- cases for (the return type may be variadic, or function type, so
5667 -- there may be more case splitting that the idris_implicits record
5768 -- suggests)
5869 let parg = case lookupCtxt n (idris_implicits i) of
@@ -60,10 +71,10 @@ genClauses fc n xs given
6071 _ -> repeat (pexp Placeholder)
6172 let tryclauses = mkClauses parg all_args
6273 logLvl 2 $ show (length tryclauses) ++ " initially to check"
63− logLvl 5 $ showSep "\n" (map (showTm i) tryclauses)
74+ logLvl 1 $ showSep "\n" (map (showTm i) tryclauses)
6475 let new = filter (noMatch i) (nub tryclauses)
6576 logLvl 1 $ show (length new) ++ " clauses to check for impossibility"
66− logLvl 5 $ "New clauses: \n" ++ showSep "\n" (map (showTm i) new)
77+ logLvl 3 $ "New clauses: \n" ++ showSep "\n" (map (showTm i) new)
6778-- ++ " from:\n" ++ showSep "\n" (map (showImp True) tryclauses)
6879 return new
6980-- return (map (\t -> PClause n t [] PImpossible []) new)
@@ -74,9 +85,11 @@ genClauses fc n xs given
7485 lhsApp (PClause _ _ l _ _ _) = l
7586 lhsApp (PWith _ _ l _ _ _) = l
7687
88+ -- Return whether the given clause matches none of the input clauses
89+ -- (xs)
7790 noMatch i tm = all (\x -> case matchClause i (delab' i x True True) tm of
78− Right _ -> False
79− Left miss -> True) xs
91+ Right ms -> False
92+ Left miss -> True) xs
8093
8194
8295 mkClauses :: [PArg] -> [[PTerm]] -> [PTerm]
src/Idris/Delaborate.hs+2−7
@@ -1,5 +1,5 @@
11{-# LANGUAGE PatternGuards #-}
2−module Idris.Delaborate (bugaddr, delab, delab', delabMV, delabTy, delabTy', pshow, pprintErr) where
2+module Idris.Delaborate (bugaddr, delab, delab', delabMV, delabTy, delabTy', pprintErr) where
33
44-- Convert core TT back into high level syntax, primarily for display
55-- purposes.
@@ -140,11 +140,6 @@ pprintTerm ist = pprintTerm' ist []
140140pprintTerm' :: IState -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
141141pprintTerm' ist bnd tm = pprintPTerm (opt_showimp (idris_options ist)) bnd [] tm
142142
143−pshow :: IState -> Err -> String
144−pshow ist err = displayDecorated (consoleDecorate ist) .
145− renderPretty 1.0 80 .
146− fmap (fancifyAnnots ist) $ pprintErr ist err
147−
148143pprintErr :: IState -> Err -> Doc OutputAnnotation
149144pprintErr i err = pprintErr' i (fmap (errReverse i) err)
150145
@@ -261,7 +256,7 @@ annName :: Name -> Doc OutputAnnotation
261256annName n = annName' n (showbasic n)
262257
263258annName' :: Name -> String -> Doc OutputAnnotation
264−annName' n str = annotate (AnnName n Nothing Nothing) (text str)
259+annName' n str = annotate (AnnName n Nothing Nothing Nothing) (text str)
265260
266261showSc :: IState -> [(Name, Term)] -> Doc OutputAnnotation
267262showSc i [] = empty
src/Idris/ElabDecls.hs+3−1
@@ -16,6 +16,7 @@ import Idris.Primitives
1616import Idris.Inliner
1717import Idris.PartialEval
1818import Idris.DeepSeq
19+import Idris.Output (iputStrLn, pshow, iWarn)
1920import IRTS.Lang
2021import Paths_idris
2122
@@ -58,7 +59,8 @@ checkAddDef add toplvl fc [] = return []
5859checkAddDef add toplvl fc ((n, (i, top, t)) : ns)
5960 = do ctxt <- getContext
6061 (t', _) <- recheckC fc [] t
61− when add $ addDeferred [(n, (i, top, t, toplvl))]
62+ when add $ do addDeferred [(n, (i, top, t, toplvl))]
63+ addIBC (IBCDef n)
6264 ns' <- checkAddDef add toplvl fc ns
6365 return ((n, (i, top, t')) : ns')
6466-- mapM (\(n, (i, top, t)) -> do (t', _) <- recheckC fc [] t
src/Idris/ElabTerm.hs+1
@@ -7,6 +7,7 @@ import Idris.DSL
77import Idris.Delaborate
88import Idris.Error
99import Idris.ProofSearch
10+import Idris.Output (pshow)
1011
1112import Idris.Core.Elaborate hiding (Tactic(..))
1213import Idris.Core.TT
src/Idris/Error.hs+1
@@ -5,6 +5,7 @@ module Idris.Error where
55import Prelude hiding (catch)
66import Idris.AbsSyntax
77import Idris.Delaborate
8+import Idris.Output
89
910import Idris.Core.TT
1011import Idris.Core.Typecheck
src/Idris/IBC.hs+7−3
@@ -10,6 +10,7 @@ import Idris.Imports
1010import Idris.Error
1111import Idris.Delaborate
1212import Idris.Docstrings
13+import Idris.Output
1314
1415import qualified Cheapskate.Types as CT
1516
@@ -75,9 +76,12 @@ initIBC :: IBCFile
7576initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] []
7677
7778loadIBC :: FilePath -> Idris ()
78−loadIBC fp = do iLOG $ "Loading ibc " ++ fp
79− ibcf <- runIO $ (bdecode fp :: IO IBCFile)
80− process ibcf fp
79+loadIBC fp = do imps <- getImported
80+ when (not (fp `elem` imps)) $
81+ do iLOG $ "Loading ibc " ++ fp
82+ ibcf <- runIO $ (bdecode fp :: IO IBCFile)
83+ process ibcf fp
84+ addImported fp
8185
8286bencode :: Binary a => FilePath -> a -> IO ()
8387bencode f d = B.writeFile f (compress (encode d))
src/Idris/IdeSlave.hs+13−8
@@ -74,16 +74,21 @@ instance (SExpable a, SExpable b, SExpable c, SExpable d, SExpable e) =>
7474 toSExp (l, m, n, o, p) = SexpList [toSExp l, toSExp m, toSExp n, toSExp o, toSExp p]
7575
7676instance SExpable NameOutput where
77− toSExp TypeOutput = SymbolAtom "type"
78− toSExp FunOutput = SymbolAtom "function"
79− toSExp DataOutput = SymbolAtom "data"
77+ toSExp TypeOutput = SymbolAtom "type"
78+ toSExp FunOutput = SymbolAtom "function"
79+ toSExp DataOutput = SymbolAtom "data"
80+ toSExp MetavarOutput = SymbolAtom "metavar"
81+
82+maybeProps :: SExpable a => [(String, Maybe a)] -> [(SExp, SExp)]
83+maybeProps [] = []
84+maybeProps ((n, Just p):ps) = (SymbolAtom n, toSExp p) : maybeProps ps
85+maybeProps ((n, Nothing):ps) = maybeProps ps
8086
8187instance SExpable OutputAnnotation where
82− toSExp (AnnName n Nothing _) = toSExp [(SymbolAtom "name", StringAtom (show n)),
83− (SymbolAtom "implicit", BoolAtom False)]
84− toSExp (AnnName n (Just ty) _) = toSExp [(SymbolAtom "name", StringAtom (show n)),
85− (SymbolAtom "decor", toSExp ty),
86− (SymbolAtom "implicit", BoolAtom False)]
88+ toSExp (AnnName n ty d t) = toSExp $ [(SymbolAtom "name", StringAtom (show n)),
89+ (SymbolAtom "implicit", BoolAtom False)] ++
90+ maybeProps [("decor", ty)] ++
91+ maybeProps [("doc-overview", d), ("type", t)]
8792 toSExp (AnnBoundName n imp) = toSExp [(SymbolAtom "name", StringAtom (show n)),
8893 (SymbolAtom "decor", SymbolAtom "bound"),
8994 (SymbolAtom "implicit", BoolAtom imp)]
src/Idris/Output.hsnew file+173
@@ -0,0 +1,173 @@
1+module Idris.Output where
2+
3+import Idris.Core.TT
4+import Idris.Core.Evaluate (isDConName, isTConName, isFnName)
5+
6+import Idris.AbsSyntax
7+import Idris.Delaborate
8+import Idris.Docstrings
9+import Idris.IdeSlave
10+
11+import Util.Pretty
12+import Util.ScreenSize (getScreenWidth)
13+
14+import System.IO (stdout, Handle, hPutStrLn)
15+
16+pshow :: IState -> Err -> String
17+pshow ist err = displayDecorated (consoleDecorate ist) .
18+ renderPretty 1.0 80 .
19+ fmap (fancifyAnnots ist) $ pprintErr ist err
20+
21+ihWarn :: Handle -> FC -> Doc OutputAnnotation -> Idris ()
22+ihWarn h fc err = do i <- getIState
23+ case idris_outputmode i of
24+ RawOutput ->
25+ do err' <- iRender . fmap (fancifyAnnots i) $
26+ text (show fc) <> colon <//> err
27+ runIO . hPutStrLn h $ displayDecorated (consoleDecorate i) err'
28+ IdeSlave n ->
29+ do err' <- iRender . fmap (fancifyAnnots i) $ err
30+ let (str, spans) = displaySpans err'
31+ runIO . hPutStrLn h $
32+ convSExp "warning" (fc_fname fc, fc_start fc, fc_end fc, str, spans) n
33+
34+iRender :: Doc a -> Idris (SimpleDoc a)
35+iRender d = do w <- getWidth
36+ ist <- getIState
37+ let ideSlave = case idris_outputmode ist of
38+ IdeSlave _ -> True
39+ _ -> False
40+ case w of
41+ InfinitelyWide -> return $ renderPretty 1.0 1000000000 d
42+ ColsWide n -> return $
43+ if n < 1
44+ then renderPretty 1.0 1000000000 d
45+ else renderPretty 0.8 n d
46+ AutomaticWidth | ideSlave -> return $ renderPretty 1.0 1000000000 d
47+ | otherwise -> do width <- runIO getScreenWidth
48+ return $ renderPretty 0.8 width d
49+
50+ihPrintResult :: Handle -> String -> Idris ()
51+ihPrintResult h s = do i <- getIState
52+ case idris_outputmode i of
53+ RawOutput -> case s of
54+ "" -> return ()
55+ s -> runIO $ hPutStrLn h s
56+ IdeSlave n ->
57+ let good = SexpList [SymbolAtom "ok", toSExp s] in
58+ runIO $ hPutStrLn h $ convSExp "return" good n
59+
60+-- | Write a pretty-printed term to the console with semantic coloring
61+consoleDisplayAnnotated :: Handle -> Doc OutputAnnotation -> Idris ()
62+consoleDisplayAnnotated h output = do ist <- getIState
63+ rendered <- iRender $ output
64+ runIO . hPutStrLn h .
65+ displayDecorated (consoleDecorate ist) $
66+ rendered
67+
68+
69+-- | Write pretty-printed output to IDESlave with semantic annotations
70+ideSlaveReturnAnnotated :: Integer -> Handle -> Doc OutputAnnotation -> Idris ()
71+ideSlaveReturnAnnotated n h out = do ist <- getIState
72+ (str, spans) <- fmap displaySpans .
73+ iRender .
74+ fmap (fancifyAnnots ist) $
75+ out
76+ let good = [SymbolAtom "ok", toSExp str, toSExp spans]
77+ runIO . hPutStrLn h $ convSExp "return" good n
78+
79+ihPrintTermWithType :: Handle -> Doc OutputAnnotation -> Doc OutputAnnotation -> Idris ()
80+ihPrintTermWithType h tm ty = do ist <- getIState
81+ let output = tm <+> colon <+> ty
82+ case idris_outputmode ist of
83+ RawOutput -> consoleDisplayAnnotated h output
84+ IdeSlave n -> ideSlaveReturnAnnotated n h output
85+
86+-- | Pretty-print a collection of overloadings to REPL or IDESlave - corresponds to :t name
87+ihPrintFunTypes :: Handle -> [(Name, Bool)] -> Name -> [(Name, PTerm)] -> Idris ()
88+ihPrintFunTypes h bnd n [] = ihPrintError h $ "No such variable " ++ show n
89+ihPrintFunTypes h bnd n overloads = do imp <- impShow
90+ ist <- getIState
91+ let output = vsep (map (uncurry (ppOverload imp)) overloads)
92+ case idris_outputmode ist of
93+ RawOutput -> consoleDisplayAnnotated h output
94+ IdeSlave n -> ideSlaveReturnAnnotated n h output
95+ where fullName n = prettyName True bnd n
96+ ppOverload imp n tm = fullName n <+> colon <+> align (pprintPTerm imp bnd [] tm)
97+
98+ihRenderResult :: Handle -> Doc OutputAnnotation -> Idris ()
99+ihRenderResult h d = do ist <- getIState
100+ case idris_outputmode ist of
101+ RawOutput -> consoleDisplayAnnotated h d
102+ IdeSlave n -> ideSlaveReturnAnnotated n h d
103+
104+fancifyAnnots :: IState -> OutputAnnotation -> OutputAnnotation
105+fancifyAnnots ist annot@(AnnName n _ _ _) =
106+ do let ctxt = tt_ctxt ist
107+ docs = docOverview ist n
108+ ty = Just (getTy ist n)
109+ case () of
110+ _ | isDConName n ctxt -> AnnName n (Just DataOutput) docs ty
111+ _ | isFnName n ctxt -> AnnName n (Just FunOutput) docs ty
112+ _ | isTConName n ctxt -> AnnName n (Just TypeOutput) docs ty
113+ _ | isMetavarName n ist -> AnnName n (Just MetavarOutput) docs ty
114+ _ | otherwise -> annot
115+ where docOverview :: IState -> Name -> Maybe String -- pretty-print first paragraph of docs
116+ docOverview ist n = do docs <- lookupCtxtExact n (idris_docstrings ist)
117+ let o = overview (fst docs)
118+ -- TODO make width configurable
119+ out = displayS . renderPretty 1.0 50 $ renderDocstring o
120+ return (out "")
121+ getTy :: IState -> Name -> String -- fails if name not already extant!
122+ getTy ist n = let theTy = pprintPTerm (opt_showimp (idris_options ist)) [] [] $
123+ delabTy ist n
124+ in (displayS . renderPretty 1.0 50 $ theTy) ""
125+fancifyAnnots _ annot = annot
126+
127+-- | Show an error with semantic highlighting
128+ihRenderError :: Handle -> Doc OutputAnnotation -> Idris ()
129+ihRenderError h e = do ist <- getIState
130+ case idris_outputmode ist of
131+ RawOutput -> consoleDisplayAnnotated h e
132+ IdeSlave n -> do
133+ (str, spans) <- fmap displaySpans .
134+ iRender .
135+ fmap (fancifyAnnots ist) $
136+ e
137+ let good = [SymbolAtom "error", toSExp str, toSExp spans]
138+ runIO . hPutStrLn h $ convSExp "return" good n
139+
140+ihPrintError :: Handle -> String -> Idris ()
141+ihPrintError h s = do i <- getIState
142+ case idris_outputmode i of
143+ RawOutput -> case s of
144+ "" -> return ()
145+ s -> runIO $ hPutStrLn h s
146+ IdeSlave n ->
147+ let good = SexpList [SymbolAtom "error", toSExp s] in
148+ runIO . hPutStrLn h $ convSExp "return" good n
149+
150+ihputStrLn :: Handle -> String -> Idris ()
151+ihputStrLn h s = do i <- getIState
152+ case idris_outputmode i of
153+ RawOutput -> runIO $ hPutStrLn h s
154+ IdeSlave n -> runIO . hPutStrLn h $ convSExp "write-string" s n
155+
156+iputStrLn = ihputStrLn stdout
157+iPrintError = ihPrintError stdout
158+iPrintResult = ihPrintResult stdout
159+iWarn = ihWarn stdout
160+
161+ideslavePutSExp :: SExpable a => String -> a -> Idris ()
162+ideslavePutSExp cmd info = do i <- getIState
163+ case idris_outputmode i of
164+ IdeSlave n -> runIO . putStrLn $ convSExp cmd info n
165+ _ -> return ()
166+
167+-- this needs some typing magic and more structured output towards emacs
168+iputGoal :: SimpleDoc OutputAnnotation -> Idris ()
169+iputGoal g = do i <- getIState
170+ case idris_outputmode i of
171+ RawOutput -> runIO $ putStrLn (displayDecorated (consoleDecorate i) g)
172+ IdeSlave n -> runIO . putStrLn $
173+ convSExp "write-goal" (displayS (fmap (fancifyAnnots i) g) "") n
src/Idris/ParseHelpers.hs+1
@@ -17,6 +17,7 @@ import Idris.Core.TT
1717import Idris.Core.Evaluate
1818import Idris.Delaborate (pprintErr)
1919import Idris.Docstrings
20+import Idris.Output (ihWarn)
2021
2122import qualified Util.Pretty as Pretty (text)
2223
src/Idris/ParseOps.hs+6−1
@@ -37,9 +37,14 @@ table fixes
3737 [pexp (PApp fc (PRef fc (sUN "fromInteger")) [pexp (PConstant (BI 0))]), pexp x])]]
3838 ++ toTable (reverse fixes) ++
3939 [[backtick],
40− [binary "$" (\fc x y -> PApp fc x [pexp y]) AssocRight],
40+ [binary "$" (\fc x y -> flatten $ PApp fc x [pexp y]) AssocRight],
4141 [binary "=" PEq AssocLeft],
4242 [binary "->" (\fc x y -> PPi expl (sUN "__pi_arg") x y) AssocRight]]
43+ where
44+ flatten :: PTerm -> PTerm -- flatten application
45+ flatten (PApp fc (PApp _ f as) bs) = flatten (PApp fc f (as ++ bs))
46+ flatten t = t
47+
4348
4449-- | Calculates table for fixtiy declarations
4550toTable :: [FixDecl] -> OperatorTable IdrisParser PTerm
src/Idris/Parser.hs+9
@@ -29,6 +29,7 @@ import Idris.Coverage
2929import Idris.IBC
3030import Idris.Unlit
3131import Idris.Providers
32+import Idris.Output
3233
3334import Idris.ParseHelpers
3435import Idris.ParseOps
@@ -1212,6 +1213,14 @@ loadSource h lidr f
12121213 file_in <- runIO $ readFile f
12131214 file <- if lidr then tclift $ unlit f file_in else return file_in
12141215 (mname, imports, pos) <- parseImports f file
1216+ ids <- allImportDirs
1217+ ibcsd <- valIBCSubDir i
1218+ mapM_ (\f -> do fp <- runIO $ findImport ids ibcsd f
1219+ case fp of
1220+ LIDR fn -> ifail $ "No ibc for " ++ f
1221+ IDR fn -> ifail $ "No ibc for " ++ f
1222+ IBC fn src -> loadIBC fn)
1223+ [fn | (fn, _, _) <- imports]
12151224 reportParserWarnings
12161225
12171226 -- process and check module aliases
src/Idris/Prover.hs+1
@@ -15,6 +15,7 @@ import Idris.Error
1515import Idris.DataOpts
1616import Idris.Completion
1717import Idris.IdeSlave
18+import Idris.Output
1819
1920import Text.Trifecta.Result(Result(..))
2021
src/Idris/REPL.hs+55−24
@@ -28,6 +28,7 @@ import Idris.Colours hiding (colourise)
2828import Idris.Inliner
2929import Idris.CaseSplit
3030import Idris.DeepSeq
31+import Idris.Output
3132
3233import Paths_idris
3334import Version_idris (gitHash)
@@ -321,8 +322,6 @@ ideslaveProcess fn (HNF t) = process stdout fn (HNF t)
321322--ideslaveProcess fn TTShell = process stdout fn TTShell -- need some prove mode!
322323ideslaveProcess fn (TestInline t) = process stdout fn (TestInline t)
323324
324−--that most likely does not work, since we need to wrap
325−--input/output of the executed binary...
326325ideslaveProcess fn Execute = do process stdout fn Execute
327326 iPrintResult ""
328327ideslaveProcess fn (Compile codegen f) = do process stdout fn (Compile codegen f)
@@ -534,7 +533,7 @@ process h fn (Check (PRef _ n))
534533 putTy imp ist _ bnd sc = putGoal imp ist ((n,False):bnd) sc
535534 putGoal imp ist bnd g
536535 = text "--------------------------------------" <$>
537− annotate (AnnName n Nothing Nothing) (text $ show n) <+> colon <+>
536+ annotate (AnnName n Nothing Nothing Nothing) (text $ show n) <+> colon <+>
538537 align (tPretty bnd ist g)
539538
540539 tPretty bnd ist t = pprintPTerm (opt_showimp (idris_options ist)) bnd [] t
@@ -893,17 +892,19 @@ process h fn (TestInline t)
893892 c <- colourise
894893 iPrintResult (showTm ist (delab ist tm'))
895894process h fn Execute
896− = do (m, _) <- elabVal toplevel False
895+ = do ist <- getIState
896+ (m, _) <- elabVal toplevel False
897897 (PApp fc
898898 (PRef fc (sUN "run__IO"))
899899 [pexp $ PRef fc (sNS (sUN "main") ["Main"])])
900−-- (PRef (FC "main" 0) (NS (UN "main") ["main"]))
901900 (tmpn, tmph) <- runIO tempfile
902901 runIO $ hClose tmph
903902 t <- codegen
904903 compile t tmpn m
905− runIO $ system tmpn
906− return ()
904+ case idris_outputmode ist of
905+ RawOutput -> do runIO $ system tmpn
906+ return ()
907+ IdeSlave n -> do runIO . hPutStrLn h $ IdeSlave.convSExp "run-program" tmpn n
907908 where fc = fileFC "main"
908909process h fn (Compile codegen f)
909910 = do (m, _) <- elabVal toplevel False
@@ -1163,30 +1164,32 @@ loadInputs h inputs
11631164 let ninputs = zip [1..] inputs
11641165 ifiles <- mapWhileOK (\(num, input) ->
11651166 do putIState ist
1166− v <- verbose
1167− -- when v $ iputStrLn $ "(" ++ show num ++ "/" ++
1168− -- show (length inputs) ++
1169− -- ") " ++ input
11701167 modTree <- buildTree
11711168 (map snd (take (num-1) ninputs))
11721169 input
11731170 let ifiles = getModuleFiles modTree
11741171 iLOG ("MODULE TREE : " ++ show modTree)
11751172 iLOG ("RELOAD: " ++ show ifiles)
1176− when (not (all ibc ifiles) || loadCode) $ tryLoad ifiles
1173+ when (not (all ibc ifiles) || loadCode) $
1174+ tryLoad False (filter (not . ibc) ifiles)
11771175 -- return the files that need rechecking
1178− return (if (all ibc ifiles) then ifiles else []))
1176+ return ifiles)
11791177 ninputs
11801178 inew <- getIState
1181− -- to check everything worked consistently (in particular, will catch
1182− -- if the ibc version is out of date) if we weren't loading per
1183− -- module
1179+ let tidata = idris_tyinfodata inew
1180+ let lineapps = idris_lineapps inew
1181+ let patdefs = idris_patdefs inew
1182+ -- If it worked, load the whole thing from all the ibcs together
11841183 case errSpan inew of
11851184 Nothing ->
1186− do putIState ist
1187− when (not loadCode) $ tryLoad $ nub (concat ifiles)
1185+ do putIState (ist { idris_tyinfodata = tidata })
1186+ ibcfiles <- mapM findNewIBC (nub (concat ifiles))
1187+ tryLoad True (mapMaybe id ibcfiles)
11881188 _ -> return ()
1189− putIState inew)
1189+ ist <- getIState
1190+ putIState (ist { idris_tyinfodata = tidata,
1191+ idris_lineapps = lineapps,
1192+ idris_patdefs = patdefs }))
11901193 (\e -> do i <- getIState
11911194 case e of
11921195 At f _ -> do setErrSpan f
@@ -1195,15 +1198,43 @@ loadInputs h inputs
11951198 _ -> do setErrSpan emptyFC -- FIXME! Propagate it
11961199 iputStrLn (pshow i e))
11971200 where -- load all files, stop if any fail
1198− tryLoad :: [IFileType] -> Idris ()
1199− tryLoad [] = return ()
1200− tryLoad (f : fs) = do loadFromIFile h f
1201− ok <- noErrors
1202− when ok $ tryLoad fs
1201+ tryLoad :: Bool -> [IFileType] -> Idris ()
1202+ tryLoad keepstate [] = return ()
1203+ tryLoad keepstate (f : fs)
1204+ = do ist <- getIState
1205+ loadFromIFile h f
1206+ inew <- getIState
1207+ -- FIXME: Save these in IBC to avoid this hack! Need to
1208+ -- preserve it all from source inputs
1209+ let tidata = idris_tyinfodata inew
1210+ let lineapps = idris_lineapps inew
1211+ let patdefs = idris_patdefs inew
1212+ ok <- noErrors
1213+ when ok $ do when (not keepstate) $ putIState ist
1214+ ist <- getIState
1215+ putIState (ist { idris_tyinfodata = tidata,
1216+ idris_lineapps = lineapps,
1217+ idris_patdefs = patdefs })
1218+ tryLoad keepstate fs
12031219
12041220 ibc (IBC _ _) = True
12051221 ibc _ = False
12061222
1223+ findNewIBC :: IFileType -> Idris (Maybe IFileType)
1224+ findNewIBC i@(IBC _ _) = return (Just i)
1225+ findNewIBC s@(IDR f) = do ist <- get
1226+ ibcsd <- valIBCSubDir ist
1227+ let ibc = ibcPathNoFallback ibcsd f
1228+ ok <- runIO $ doesFileExist ibc
1229+ if ok then return (Just (IBC ibc s))
1230+ else return Nothing
1231+ findNewIBC s@(LIDR f) = do ist <- get
1232+ ibcsd <- valIBCSubDir ist
1233+ let ibc = ibcPathNoFallback ibcsd f
1234+ ok <- runIO $ doesFileExist ibc
1235+ if ok then return (Just (IBC ibc s))
1236+ else return Nothing
1237+
12071238 -- Like mapM, but give up when there's an error
12081239 mapWhileOK f [] = return []
12091240 mapWhileOK f (x : xs) = do x' <- f x
src/Pkg/Package.hs+1
@@ -23,6 +23,7 @@ import Idris.Parser (loadModule)
2323import Idris.Delaborate (pshow)
2424import Idris.AbsSyntax
2525import Idris.IdrisDoc
26+import Idris.Output
2627
2728import IRTS.System
2829
src/Util/LLVMStubs.hs+2−9
@@ -20,12 +20,5 @@ getHostCPUName :: IO String
2020getHostCPUName = return ""
2121
2222
23−codegenLLVM :: [(TT.Name, SDecl)] ->
24− String -> -- target triple
25− String -> -- target CPU
26− Word -> -- Optimization degree
27− FilePath -> -- output file name
28− OutputType ->
29− IO ()
30−
31−codegenLLVM _ _ _ _ _ _ = fail "This Idris was compiled without the LLVM backend."
23+codegenLLVM :: CodeGenerator
24+codegenLLVM _ = fail "This Idris was compiled without the LLVM backend."
test/error004/FunErrTest.idr+1−1
@@ -6,7 +6,6 @@ import Language.Reflection.Utils
66
77%language ErrorReflection
88
9−
109total
1110cadr : (xs : List a)
1211 -> {auto cons1 : isCons xs = True}
@@ -14,6 +13,7 @@ cadr : (xs : List a)
1413 -> a
1514cadr (x :: (y :: _)) {cons1=refl} {cons2=refl} = y
1615cadr (x :: []) {cons1=refl} {cons2=refl} impossible
16+cadr [] {cons1=refl} {cons2=refl} impossible
1717
1818extractList : TT -> Maybe TT
1919extractList (App (App reflCon (App isCons lst)) _) = Just lst