on master help sign in
Merge branch 'master' of github.com:edwinb/Idris-dev into default-arg-subst
commitbfc3c3e1b47a9bc8c550509c3be9a00088dc540d authorTimo Petteri Sinnemäki <timo.sinnemaki@helsinki.fi> dateSat 5 Apr 2014, 15:51 (13 years ago) parent60ac04eaa39233
39 files changed+643−335
CHANGELOG+3−3 README+1−1 idris.cabal+2−1 libs/base/Data/HVect.idr+1 libs/effects/Effect/File.idr+85−14 libs/prelude/Prelude/Applicative.idr+2 libs/prelude/Prelude/Chars.idr+3 libs/prelude/Prelude/Fin.idr+11 libs/prelude/Prelude/List.idr+8 libs/prelude/Prelude/Nat.idr+4 libs/prelude/Prelude/Uninhabited.idr+2−7 libs/prelude/Prelude/Vect.idr+10 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+29−145 src/Idris/AbsSyntaxTree.hs+29−30 src/Idris/CaseSplit.hs+1 src/Idris/Core/TT.hs+8−6 src/Idris/Coverage.hs+38−11 src/Idris/Delaborate.hs+2−7 src/Idris/ElabDecls.hs+14−7 src/Idris/ElabTerm.hs+1 src/Idris/Error.hs+1 src/Idris/IBC.hs+12−5 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
CHANGELOG+3−3
@@ -5,7 +5,7 @@ New in 0.9.12:
55 type inference.
66* New 'Lazy' type, replacing laziness annotations.
77* JavaScript and Node codegen now understand the %include directive.
8−* Concept up 'null' is now understood in the JavaScript and Node codegen.
8+* Concept of 'null' is now understood in the JavaScript and Node codegen.
99* Lots of performance patches for generated JavaScript.
1010* New commands :eval (:e) and :type (:t) in the prover, which either normalise
1111 or show the type of expressions.
@@ -17,8 +17,8 @@ New in 0.9.12:
1717 ||| @ n the first number (examined by the function)
1818 ||| @ m the second number (not examined)
1919 plus (n, m : Nat) -> Nat
20−* Allow the auto-solve behavior in the prover to be disabled, for easier debugging
21− of proof automation. Use ":set autosolve" and ":unset autosolve".
20+* Allow the auto-solve behaviour in the prover to be disabled, for easier
21+ debugging of proof automation. Use ":set autosolve" and ":unset autosolve".
2222* Updated 'effects' library
2323* New :apropos command at REPL to search documentation, names, and types
2424* Unification errors are now slightly more informative
README+1−1
@@ -1,4 +1,4 @@
1−Idris (http://idris-lang.org/) is an experimental functional programming
1+Idris (http://idris-lang.org/) is a general-purpose functional programming
22language with dependent types.
33
44To configure, edit config.mk. The default values should work for most people.
idris.cabal+2−1
@@ -1,5 +1,5 @@
11Name: idris
2−Version: 0.9.11.2
2+Version: 0.9.12
33License: BSD3
44License-file: LICENSE
55Author: Edwin Brady
@@ -476,6 +476,7 @@ Library
476476 , Idris.IdeSlave
477477 , Idris.Imports
478478 , Idris.Inliner
479+ , Idris.Output
479480 , Idris.Parser
480481 , Idris.ParseHelpers
481482 , 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/effects/Effect/File.idr+85−14
@@ -1,24 +1,78 @@
1+-- -------------------------------------------------------- [ Effectful FileIO ]
12module Effect.File
23
34import Effects
45import Control.IOExcept
56
6−data OpenFile : Mode -> Type where
7+
8+||| A Dependent type to describe File Handles. File handles are
9+||| parameterised with the current state of the file: Closed; Open for
10+||| reading; and Open for writing.
11+|||
12+||| @ m The file mode.
13+data OpenFile : (m : Mode) -> Type where
714 FH : File -> OpenFile m
815
916openOK : Mode -> Bool -> Type
1017openOK m True = OpenFile m
1118openOK m False = ()
1219
20+-- ------------------------------------------------------------ [ The Protocol ]
21+
22+||| Here the protocol for resource access is defined as an effect.
23+||| The state transitions diagram for the protocol is as follows:
24+|||
25+||| digraph G {
26+|||
27+||| empty; read; write; // States
28+|||
29+||| empty -> read [label="Open R"];
30+||| read -> empty [label="Close"];
31+||| read -> read [label="ReadLine"];
32+||| read -> read [label="EOF"];
33+|||
34+||| empty -> write [label="Open W"];
35+||| write -> empty [label="Close"];
36+||| write -> write [label="WriteLine"];
37+|||
38+||| }
1339data FileIO : Effect where
14− Open : String -> (m : Mode) ->
15− {() ==> {res} if res then OpenFile m else ()} FileIO Bool
16− Close : {OpenFile m ==> ()} FileIO ()
17−
18− ReadLine : {OpenFile Read} FileIO String
19− WriteLine : String -> {OpenFile Write} FileIO ()
20− EOF : {OpenFile Read} FileIO Bool
21−
40+ ||| Open a file with the specified mode.
41+ |||
42+ ||| Opening a file successful moves the state from 'empty' to the
43+ ||| specified mode. If not successful the state is still 'empty'.
44+ |||
45+ ||| @ fname The file name to be opened.
46+ ||| @ m The file mode.
47+ Open : (fname: String)
48+ -> (m : Mode)
49+ -> {() ==> {res} if res
50+ then OpenFile m
51+ else ()} FileIO Bool
52+
53+ ||| Close a file.
54+ |||
55+ ||| Closing a file moves the state from Open to closed.
56+ Close : {OpenFile m ==> ()} FileIO ()
57+
58+ ||| Read a line from the file.
59+ |||
60+ ||| Only files that are open for reading can be read.
61+ ReadLine : {OpenFile Read} FileIO String
62+
63+ ||| Write a line to a file.
64+ |||
65+ ||| Only file that are open for writing can be written to.
66+ WriteLine : String -> {OpenFile Write} FileIO ()
67+
68+ ||| End of file?
69+ |||
70+ ||| Only files open for reading can be tested for EOF
71+ EOF : {OpenFile Read} FileIO Bool
72+
73+-- ------------------------------------------------------------ [ The Handlers ]
74+
75+--- An implementation of the resource access protocol for the IO Context.
2276instance Handler FileIO IO where
2377 handle () (Open fname m) k = do h <- openFile fname m
2478 valid <- validFile h
@@ -33,30 +87,47 @@ instance Handler FileIO IO where
3387 handle (FH h) EOF k = do e <- feof h
3488 k e (FH h)
3589
90+-- -------------------------------------------------------------- [ The Effect ]
3691FILE_IO : Type -> EFFECT
3792FILE_IO t = MkEff t FileIO
3893
94+-- ------------------------------------------------------------ [ The Bindings ]
95+--
96+-- Bind the IO context handlers to functions. These functions will run
97+-- in the IO context.
98+--
99+
100+||| Open a file with the specified mode.
101+|||
102+||| @ fname The file name to be opened.
103+||| @ m The file mode.
39104open : Handler FileIO e =>
40− String -> (m : Mode) ->
41− { [FILE_IO ()] ==> [FILE_IO (if result then OpenFile m else ())] } Eff e Bool
105+ (fname : String)
106+ -> (m : Mode)
107+ -> { [FILE_IO ()] ==> [FILE_IO (if result
108+ then OpenFile m
109+ else ())] } Eff e Bool
42110open f m = Open f m
43111
112+
113+||| Close a file.
44114close : Handler FileIO e =>
45115 { [FILE_IO (OpenFile m)] ==> [FILE_IO ()] } Eff e ()
46116close = Close
47117
118+||| Read a line from the file.
48119readLine : Handler FileIO e =>
49120 { [FILE_IO (OpenFile Read)] } Eff e String
50121readLine = ReadLine
51122
123+||| Write a line to a file.
52124writeLine : Handler FileIO e =>
53125 String -> { [FILE_IO (OpenFile Write)] } Eff e ()
54126writeLine str = WriteLine str
55127
128+||| End of file?
56129eof : Handler FileIO e =>
57130 { [FILE_IO (OpenFile Read)] } Eff e Bool
58131eof = EOF
59132
60−
61−
62−
133+-- --------------------------------------------------------------------- [ EOF ]
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+11
@@ -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
@@ -93,6 +98,12 @@ instance MaxBound (Fin (S n)) where
9398(+) {n=S n} {m=m} fZ f' = rewrite plusCommutative n m in weaken (weakenN n f')
9499(+) (fS f) f' = fS (f + f')
95100
101+||| Substract two Fins, keeping the bound of the minuend
102+(-) : Fin n -> Fin m -> Fin n
103+fZ - _ = fZ
104+f - fZ = f
105+(fS f) - (fS f') = weaken $ f - f'
106+
96107||| Multiply two Fins, extending the bound
97108(*) : Fin n -> Fin m -> Fin (n * m)
98109(*) {n=Z} f f' = FinZElim f
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+10
@@ -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
@@ -379,6 +381,14 @@ nub = nubBy (==)
379381-- Splitting and breaking lists
380382--------------------------------------------------------------------------------
381383
384+||| A tuple where the first element is a Vect of the n first elements and
385+||| the second element is a Vect of the remaining elements of the original Vect
386+||| It is equivalent to (take n xs, drop n xs)
387+||| @ m the index to split at
388+||| @ xs the Vect to split in two
389+splitAt : {n : Nat} -> (m : Fin (S n)) -> (xs : Vect n a) -> (Vect (cast m) a, Vect (n - cast m) a)
390+splitAt n xs = (take n xs, drop n xs)
391+
382392--------------------------------------------------------------------------------
383393-- Predicates
384394--------------------------------------------------------------------------------
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+29−145
@@ -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
@@ -1701,8 +1575,6 @@ matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
17011575 = do mf <- match' f f'
17021576 ms <- zipWithM matchArg args args'
17031577 return (mf ++ concat ms)
1704−-- match (PRef _ n) (PRef _ n') | n == n' = return []
1705−-- | otherwise = Nothing
17061578 match (PRef f n) (PApp _ x []) = match (PRef f n) x
17071579 match (PPatvar f n) xr = match (PRef f n) xr
17081580 match xr (PPatvar f n) = match xr (PRef f n)
@@ -1712,7 +1584,10 @@ matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
17121584 (not (isConName n (tt_ctxt i) || isFnName n (tt_ctxt i))
17131585 || tm == Placeholder)
17141586 = return [(n, tm)]
1715− | n == n' = return []
1587+ -- if one namespace is missing, drop the other
1588+ | n == n' || n == dropNS n' || dropNS n == n' = return []
1589+ where dropNS (NS n _) = n
1590+ dropNS n = n
17161591 match (PRef _ n) tm
17171592 | not names && (not (isConName n (tt_ctxt i) ||
17181593 isFnName n (tt_ctxt i)) || tm == Placeholder)
@@ -1855,6 +1730,12 @@ mkUniqueNames env tm = evalState (mkUniq tm) env where
18551730 mkUniqA arg = do t' <- mkUniq (getTm arg)
18561731 return (arg { getTm = t' })
18571732
1733+ -- Initialise the unique name with the environment length (so we're not
1734+ -- looking for too long...)
1735+ initN (UN n) l = UN $ txt (str n ++ show l)
1736+ initN (MN i s) l = MN (i+l) s
1737+ initN n l = n
1738+
18581739 -- FIXME: Probably ought to do this for completeness! It's fine as
18591740 -- long as there are no bindings inside tactics though.
18601741 mkUniqT tac = return tac
@@ -1864,7 +1745,8 @@ mkUniqueNames env tm = evalState (mkUniq tm) env where
18641745 = do env <- get
18651746 (n', sc') <-
18661747 if n `elem` env
1867− then do let n' = uniqueName n (env ++ inScope)
1748+ then do let n' = uniqueName (initN n (length env))
1749+ (env ++ inScope)
18681750 return (n', shadow n n' sc)
18691751 else return (n, sc)
18701752 put (n' : env)
@@ -1875,7 +1757,8 @@ mkUniqueNames env tm = evalState (mkUniq tm) env where
18751757 = do env <- get
18761758 (n', sc') <-
18771759 if n `elem` env
1878− then do let n' = uniqueName n (env ++ inScope)
1760+ then do let n' = uniqueName (initN n (length env))
1761+ (env ++ inScope)
18791762 return (n', shadow n n' sc)
18801763 else return (n, sc)
18811764 put (n' : env)
@@ -1886,7 +1769,8 @@ mkUniqueNames env tm = evalState (mkUniq tm) env where
18861769 = do env <- get
18871770 (n', sc') <-
18881771 if n `elem` env
1889− then do let n' = uniqueName n (env ++ inScope)
1772+ then do let n' = uniqueName (initN n (length env))
1773+ (env ++ inScope)
18901774 return (n', shadow n n' sc)
18911775 else return (n, sc)
18921776 put (n' : env)
src/Idris/AbsSyntaxTree.hs+29−30
@@ -104,11 +104,6 @@ data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines sh
104104 | ColsWide Int -- ^ Manually specified - must be positive
105105 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
106106
107−-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
108−-- without typechecking).
109−-- This will include all the functions and data declarations, plus fixity declarations
110−-- and syntax macros.
111−
112107-- | The global state used in the Idris monad
113108data IState = IState {
114109 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
@@ -147,6 +142,7 @@ data IState = IState {
147142 idris_libs :: [(Codegen, String)],
148143 idris_cgflags :: [(Codegen, String)],
149144 idris_hdrs :: [(Codegen, String)],
145+ idris_imported :: [FilePath], -- ^ Imported ibc file names
150146 proof_list :: [(Name, [String])],
151147 errSpan :: Maybe FC,
152148 parserWarnings :: [(FC, Err)],
@@ -238,7 +234,7 @@ idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
238234 emptyContext emptyContext emptyContext emptyContext
239235 emptyContext emptyContext
240236 [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
241− [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
237+ [] [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
242238 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
243239 AutomaticWidth
244240
@@ -1083,13 +1079,13 @@ consoleDecorate ist AnnConstType = let theme = idris_colourTheme ist
10831079consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
10841080consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
10851081consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1086−consoleDecorate ist (AnnName n _ _) = let ctxt = tt_ctxt ist
1087− theme = idris_colourTheme ist
1088− in case () of
1089− _ | isDConName n ctxt -> colouriseData theme
1090− _ | isFnName n ctxt -> colouriseFun theme
1091− _ | isTConName n ctxt -> colouriseType theme
1092− _ | otherwise -> id -- don't colourise unknown names
1082+consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1083+ theme = idris_colourTheme ist
1084+ in case () of
1085+ _ | isDConName n ctxt -> colouriseData theme
1086+ _ | isFnName n ctxt -> colouriseFun theme
1087+ _ | isTConName n ctxt -> colouriseType theme
1088+ _ | otherwise -> id -- don't colourise unknown names
10931089consoleDecorate ist (AnnFC _) = id
10941090consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
10951091 where colour BoldText = IdrisColour Nothing True False True False
@@ -1204,16 +1200,16 @@ pprintPTerm impl bnd docArgs = prettySe 10 bnd
12041200
12051201 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
12061202 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1207− prettySe p bnd (PRefl _ _) = annotate (AnnName eqCon Nothing Nothing) $ text "refl"
1203+ prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
12081204 prettySe p bnd (PResolveTC _) = text "resolvetc"
1209− prettySe p bnd (PTrue _ IsType) = annotate (AnnName unitTy Nothing Nothing) $ text "()"
1210− prettySe p bnd (PTrue _ IsTerm) = annotate (AnnName unitCon Nothing Nothing) $ text "()"
1205+ prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1206+ prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
12111207 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1212− prettySe p bnd (PFalse _) = annotate (AnnName falseTy Nothing Nothing) $ text "_|_"
1208+ prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
12131209 prettySe p bnd (PEq _ l r) =
12141210 bracket p 2 . align . group $
12151211 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1216− where eq = annotate (AnnName eqTy Nothing Nothing) (text "=")
1212+ where eq = annName eqTy (text "=")
12171213 prettySe p bnd (PRewrite _ l r _) =
12181214 bracket p 2 $
12191215 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
@@ -1225,28 +1221,28 @@ pprintPTerm impl bnd docArgs = prettySe 10 bnd
12251221 map (prettySe 10 bnd) elts
12261222 where ann = case pun of
12271223 TypeOrTerm -> id
1228− IsType -> annotate (AnnName pairTy Nothing Nothing)
1229− IsTerm -> annotate (AnnName pairCon Nothing Nothing)
1224+ IsType -> annName pairTy
1225+ IsTerm -> annName pairCon
12301226 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
12311227 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
12321228 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1233− annotate (AnnName sigmaTy Nothing Nothing) lparen <>
1229+ annName sigmaTy lparen <>
12341230 bindingOf n False <+>
1235− annotate (AnnName sigmaTy Nothing Nothing) (text "**") <+>
1231+ annName sigmaTy (text "**") <+>
12361232 prettySe 10 ((n, False):bnd) r <>
1237− annotate (AnnName sigmaTy Nothing Nothing) rparen
1233+ annName sigmaTy rparen
12381234 prettySe p bnd (PDPair _ IsType l t r) =
1239− annotate (AnnName sigmaTy Nothing Nothing) lparen <>
1235+ annName sigmaTy lparen <>
12401236 prettySe 10 bnd l <+>
1241− annotate (AnnName sigmaTy Nothing Nothing) (text "**") <+>
1237+ annName sigmaTy (text "**") <+>
12421238 prettySe 10 bnd r <>
1243− annotate (AnnName sigmaTy Nothing Nothing) rparen
1239+ annName sigmaTy rparen
12441240 prettySe p bnd (PDPair _ IsTerm l t r) =
1245− annotate (AnnName existsCon Nothing Nothing) lparen <>
1241+ annName existsCon lparen <>
12461242 prettySe 10 bnd l <+>
1247− annotate (AnnName existsCon Nothing Nothing) (text "**") <+>
1243+ annName existsCon (text "**") <+>
12481244 prettySe 10 bnd r <>
1249− annotate (AnnName existsCon Nothing Nothing) rparen
1245+ annName existsCon rparen
12501246 prettySe p bnd (PAlternative a as) =
12511247 lparen <> text "|" <> prettyAs <> text "|" <> rparen
12521248 where
@@ -1283,6 +1279,9 @@ pprintPTerm impl bnd docArgs = prettySe 10 bnd
12831279 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
12841280 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
12851281
1282+ annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1283+ annName n = annotate (AnnName n Nothing Nothing Nothing)
1284+
12861285 basename :: Name -> Name
12871286 basename (NS n _) = basename n
12881287 basename n = n
@@ -1348,7 +1347,7 @@ prettyName :: Bool -- ^^ whether to show namespaces
13481347 -> Name -- ^^ the name to pprint
13491348 -> Doc OutputAnnotation
13501349prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1351− | otherwise = annotate (AnnName n Nothing Nothing) (text (strName n))
1350+ | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
13521351 where strName (UN n) = T.unpack n
13531352 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
13541353 | 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+38−11
@@ -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.
@@ -40,19 +51,24 @@ mkPatTm t = do i <- getIState
4051-- This will only work after the given clauses have been typechecked and the
4152-- names are fully explicit!
4253
43−genClauses :: FC -> Name -> [Term] -> [PClause] -> Idris [PTerm]
54+genClauses :: FC -> Name -> [Term] -> [PTerm] -> Idris [PTerm]
4455genClauses fc n xs given
4556 = do i <- getIState
46− let lhss = map (getLHS i) xs
57+ let lhs_tms = map (\x -> delab' i x True True) xs
58+ -- if a placeholder was given, don't bother generating cases for it
59+ let lhs_tms' = zipWith mergePlaceholders lhs_tms given
60+ let lhss = map pUnApply lhs_tms'
61+
4762 let argss = transpose lhss
4863 let all_args = map (genAll i) argss
4964 logLvl 5 $ "COVERAGE of " ++ show n
65+ logLvl 5 $ show lhss
5066 logLvl 5 $ show (map length argss) ++ "\n" ++ show (map length all_args)
5167 logLvl 10 $ show argss ++ "\n" ++ show all_args
52− logLvl 10 $ "Original: \n" ++
68+ logLvl 1 $ "Original: \n" ++
5369 showSep "\n" (map (\t -> showTm i (delab' i t True True)) xs)
5470 -- add an infinite supply of explicit arguments to update the possible
55− -- cases for (the return type may be variadic, or function type, sp
71+ -- cases for (the return type may be variadic, or function type, so
5672 -- there may be more case splitting that the idris_implicits record
5773 -- suggests)
5874 let parg = case lookupCtxt n (idris_implicits i) of
@@ -61,10 +77,10 @@ genClauses fc n xs given
6177 _ -> repeat (pexp Placeholder)
6278 let tryclauses = mkClauses parg all_args
6379 logLvl 2 $ show (length tryclauses) ++ " initially to check"
64− logLvl 5 $ showSep "\n" (map (showTm i) tryclauses)
80+ logLvl 1 $ showSep "\n" (map (showTm i) tryclauses)
6581 let new = filter (noMatch i) (nub tryclauses)
6682 logLvl 1 $ show (length new) ++ " clauses to check for impossibility"
67− logLvl 5 $ "New clauses: \n" ++ showSep "\n" (map (showTm i) new)
83+ logLvl 3 $ "New clauses: \n" ++ showSep "\n" (map (showTm i) new)
6884-- ++ " from:\n" ++ showSep "\n" (map (showImp True) tryclauses)
6985 return new
7086-- return (map (\t -> PClause n t [] PImpossible []) new)
@@ -72,13 +88,23 @@ genClauses fc n xs given
7288 | (f, args) <- unApply term = map (\t -> delab' i t True True) args
7389 | otherwise = []
7490
75− lhsApp (PClause _ _ l _ _ _) = l
76− lhsApp (PWith _ _ l _ _ _) = l
91+ pUnApply (PApp _ _ args) = map getTm args
92+ pUnApply _ = []
7793
94+ -- Return whether the given clause matches none of the input clauses
95+ -- (xs)
7896 noMatch i tm = all (\x -> case matchClause i (delab' i x True True) tm of
79− Right _ -> False
80− Left miss -> True) xs
97+ Right ms -> False
98+ Left miss -> True) xs
99+
81100
101+ mergePlaceholders :: PTerm -> PTerm -> PTerm
102+ mergePlaceholders x Placeholder = Placeholder
103+ mergePlaceholders (PApp fc f args) (PApp fc' f' args')
104+ = PApp fc' f' (zipWith mergePArg args args')
105+ where mergePArg x y = let xtm = mergePlaceholders (getTm x) (getTm y) in
106+ x { getTm = xtm}
107+ mergePlaceholders x _ = x
82108
83109 mkClauses :: [PArg] -> [[PTerm]] -> [PTerm]
84110 mkClauses parg args
@@ -102,6 +128,7 @@ fnub' acc [] = acc
102128
103129-- quick check for constructor equality
104130quickEq :: PTerm -> PTerm -> Bool
131+quickEq (PConstant n) (PConstant n') = n == n'
105132quickEq (PRef _ n) (PRef _ n') = n == n'
106133quickEq (PApp _ t as) (PApp _ t' as')
107134 | length as == length as'
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+14−7
@@ -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
@@ -925,8 +927,10 @@ elabClauses info fc opts n_in cs = let n = liftname info n_in in
925927 tclift $ tfail $ At fc (NoTypeDecl n)
926928 [ty] -> return ty
927929 let atys = map snd (getArgTys fty)
928− pats_in <- mapM (elabClause info opts)
930+ cs_elab <- mapM (elabClause info opts)
929931 (zip [0..] cs)
932+ let (pats_in, cs_full) = unzip cs_elab
933+
930934 logLvl 3 $ "Elaborated patterns:\n" ++ show pats_in
931935
932936 -- if the return type of 'ty' is collapsible, the optimised version should
@@ -1011,7 +1015,7 @@ elabClauses info fc opts n_in cs = let n = liftname info n_in in
10111015 cov <- coverage
10121016 pmissing <-
10131017 if cov && not (hasDefault cs)
1014− then do missing <- genClauses fc n (map getLHS pdef) cs
1018+ then do missing <- genClauses fc n (map getLHS pdef) cs_full
10151019 -- missing <- genMissing n scargs sc
10161020 missing' <- filterM (checkPossible info fc True n) missing
10171021 let clhs = map getLHS pdef
@@ -1369,16 +1373,19 @@ propagateParams ps t (PRef fc n)
13691373 = PApp fc (PRef fc n) (map (\x -> pimp x (PRef fc x) True) ps)
13701374propagateParams ps t x = x
13711375
1376+-- Return the elaborated LHS/RHS, and the original LHS with implicits added
13721377elabClause :: ElabInfo -> FnOpts -> (Int, PClause) ->
1373− Idris (Either Term (Term, Term))
1378+ Idris (Either Term (Term, Term), PTerm)
13741379elabClause info opts (_, PClause fc fname lhs_in [] PImpossible [])
13751380 = do let tcgen = Dictionary `elem` opts
1381+ i <- get
1382+ let lhs = addImpl i lhs_in
13761383 b <- checkPossible info fc tcgen fname lhs_in
13771384 case b of
13781385 True -> tclift $ tfail (At fc
13791386 (Msg $ show lhs_in ++ " is a valid case"))
13801387 False -> do ptm <- mkPatTm lhs_in
1381− return (Left ptm)
1388+ return (Left ptm, lhs)
13821389elabClause info opts (cnum, PClause fc fname lhs_in withs rhs_in whereblock)
13831390 = do let tcgen = Dictionary `elem` opts
13841391 ctxt <- getContext
@@ -1519,7 +1526,7 @@ elabClause info opts (cnum, PClause fc fname lhs_in withs rhs_in whereblock)
15191526 when (rev || ErrorReverse `elem` opts) $ do
15201527 addIBC (IBCErrRev (crhs, clhs))
15211528 addErrRev (crhs, clhs)
1522− return $ Right (clhs, crhs)
1529+ return $ (Right (clhs, crhs), lhs)
15231530 where
15241531 pinfo :: ElabInfo -> [(Name, PTerm)] -> [Name] -> Int -> ElabInfo
15251532 pinfo info ns ds i
@@ -1686,7 +1693,7 @@ elabClause info opts (_, PWith fc fname lhs_in withs wval_in withblock)
16861693 mapM_ (elabCaseBlock info opts) is
16871694 logLvl 5 ("Checked RHS " ++ show rhs')
16881695 (crhs, crhsty) <- recheckC fc [] rhs'
1689− return $ Right (clhs, crhs)
1696+ return $ (Right (clhs, crhs), lhs)
16901697 where
16911698 getImps (Bind n (Pi _) t) = pexp Placeholder : getImps t
16921699 getImps _ = []
src/Idris/ElabTerm.hs+1
@@ -8,6 +8,7 @@ import Idris.DSL
88import Idris.Delaborate
99import Idris.Error
1010import Idris.ProofSearch
11+import Idris.Output (pshow)
1112
1213import Idris.Core.Elaborate hiding (Tactic(..))
1314import 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+12−5
@@ -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))
@@ -396,8 +400,11 @@ pPatdefs ds
396400pDefs :: [Name] -> [(Name, Def)] -> Idris ()
397401pDefs syms ds
398402 = mapM_ (\ (n, d) ->
399− do i <- getIState
400− let d' = updateDef d
403+ do let d' = updateDef d
404+ case d' of
405+ TyDecl _ _ -> return ()
406+ _ -> solveDeferred n
407+ i <- getIState
401408 logLvl 5 $ "Added " ++ show (n, d')
402409 putIState (i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds
403410 where
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
@@ -27,6 +27,7 @@ import Idris.Colours hiding (colourise)
2727import Idris.Inliner
2828import Idris.CaseSplit
2929import Idris.DeepSeq
30+import Idris.Output
3031
3132import Paths_idris
3233import Version_idris (gitHash)
@@ -319,8 +320,6 @@ ideslaveProcess fn (HNF t) = process stdout fn (HNF t)
319320--ideslaveProcess fn TTShell = process stdout fn TTShell -- need some prove mode!
320321ideslaveProcess fn (TestInline t) = process stdout fn (TestInline t)
321322
322−--that most likely does not work, since we need to wrap
323−--input/output of the executed binary...
324323ideslaveProcess fn Execute = do process stdout fn Execute
325324 iPrintResult ""
326325ideslaveProcess fn (Compile codegen f) = do process stdout fn (Compile codegen f)
@@ -532,7 +531,7 @@ process h fn (Check (PRef _ n))
532531 putTy imp ist _ bnd sc = putGoal imp ist ((n,False):bnd) sc
533532 putGoal imp ist bnd g
534533 = text "--------------------------------------" <$>
535− annotate (AnnName n Nothing Nothing) (text $ show n) <+> colon <+>
534+ annotate (AnnName n Nothing Nothing Nothing) (text $ show n) <+> colon <+>
536535 align (tPretty bnd ist g)
537536
538537 tPretty bnd ist t = pprintPTerm (opt_showimp (idris_options ist)) bnd [] t
@@ -891,17 +890,19 @@ process h fn (TestInline t)
891890 c <- colourise
892891 iPrintResult (showTm ist (delab ist tm'))
893892process h fn Execute
894− = do (m, _) <- elabVal toplevel False
893+ = do ist <- getIState
894+ (m, _) <- elabVal toplevel False
895895 (PApp fc
896896 (PRef fc (sUN "run__IO"))
897897 [pexp $ PRef fc (sNS (sUN "main") ["Main"])])
898−-- (PRef (FC "main" 0) (NS (UN "main") ["main"]))
899898 (tmpn, tmph) <- runIO tempfile
900899 runIO $ hClose tmph
901900 t <- codegen
902901 compile t tmpn m
903− runIO $ system tmpn
904− return ()
902+ case idris_outputmode ist of
903+ RawOutput -> do runIO $ system tmpn
904+ return ()
905+ IdeSlave n -> do runIO . hPutStrLn h $ IdeSlave.convSExp "run-program" tmpn n
905906 where fc = fileFC "main"
906907process h fn (Compile codegen f)
907908 = do (m, _) <- elabVal toplevel False
@@ -1146,30 +1147,32 @@ loadInputs h inputs
11461147 let ninputs = zip [1..] inputs
11471148 ifiles <- mapWhileOK (\(num, input) ->
11481149 do putIState ist
1149− v <- verbose
1150− -- when v $ iputStrLn $ "(" ++ show num ++ "/" ++
1151− -- show (length inputs) ++
1152− -- ") " ++ input
11531150 modTree <- buildTree
11541151 (map snd (take (num-1) ninputs))
11551152 input
11561153 let ifiles = getModuleFiles modTree
11571154 iLOG ("MODULE TREE : " ++ show modTree)
11581155 iLOG ("RELOAD: " ++ show ifiles)
1159− when (not (all ibc ifiles) || loadCode) $ tryLoad ifiles
1156+ when (not (all ibc ifiles) || loadCode) $
1157+ tryLoad False (filter (not . ibc) ifiles)
11601158 -- return the files that need rechecking
1161− return (if (all ibc ifiles) then ifiles else []))
1159+ return ifiles)
11621160 ninputs
11631161 inew <- getIState
1164− -- to check everything worked consistently (in particular, will catch
1165− -- if the ibc version is out of date) if we weren't loading per
1166− -- module
1162+ let tidata = idris_tyinfodata inew
1163+ let lineapps = idris_lineapps inew
1164+ let patdefs = idris_patdefs inew
1165+ -- If it worked, load the whole thing from all the ibcs together
11671166 case errSpan inew of
11681167 Nothing ->
1169− do putIState ist
1170− when (not loadCode) $ tryLoad $ nub (concat ifiles)
1168+ do putIState (ist { idris_tyinfodata = tidata })
1169+ ibcfiles <- mapM findNewIBC (nub (concat ifiles))
1170+ tryLoad True (mapMaybe id ibcfiles)
11711171 _ -> return ()
1172− putIState inew)
1172+ ist <- getIState
1173+ putIState (ist { idris_tyinfodata = tidata,
1174+ idris_lineapps = lineapps,
1175+ idris_patdefs = patdefs }))
11731176 (\e -> do i <- getIState
11741177 case e of
11751178 At f _ -> do setErrSpan f
@@ -1178,15 +1181,43 @@ loadInputs h inputs
11781181 _ -> do setErrSpan emptyFC -- FIXME! Propagate it
11791182 iputStrLn (pshow i e))
11801183 where -- load all files, stop if any fail
1181− tryLoad :: [IFileType] -> Idris ()
1182− tryLoad [] = return ()
1183− tryLoad (f : fs) = do loadFromIFile h f
1184− ok <- noErrors
1185− when ok $ tryLoad fs
1184+ tryLoad :: Bool -> [IFileType] -> Idris ()
1185+ tryLoad keepstate [] = return ()
1186+ tryLoad keepstate (f : fs)
1187+ = do ist <- getIState
1188+ loadFromIFile h f
1189+ inew <- getIState
1190+ -- FIXME: Save these in IBC to avoid this hack! Need to
1191+ -- preserve it all from source inputs
1192+ let tidata = idris_tyinfodata inew
1193+ let lineapps = idris_lineapps inew
1194+ let patdefs = idris_patdefs inew
1195+ ok <- noErrors
1196+ when ok $ do when (not keepstate) $ putIState ist
1197+ ist <- getIState
1198+ putIState (ist { idris_tyinfodata = tidata,
1199+ idris_lineapps = lineapps,
1200+ idris_patdefs = patdefs })
1201+ tryLoad keepstate fs
11861202
11871203 ibc (IBC _ _) = True
11881204 ibc _ = False
11891205
1206+ findNewIBC :: IFileType -> Idris (Maybe IFileType)
1207+ findNewIBC i@(IBC _ _) = return (Just i)
1208+ findNewIBC s@(IDR f) = do ist <- get
1209+ ibcsd <- valIBCSubDir ist
1210+ let ibc = ibcPathNoFallback ibcsd f
1211+ ok <- runIO $ doesFileExist ibc
1212+ if ok then return (Just (IBC ibc s))
1213+ else return Nothing
1214+ findNewIBC s@(LIDR f) = do ist <- get
1215+ ibcsd <- valIBCSubDir ist
1216+ let ibc = ibcPathNoFallback ibcsd f
1217+ ok <- runIO $ doesFileExist ibc
1218+ if ok then return (Just (IBC ibc s))
1219+ else return Nothing
1220+
11901221 -- Like mapM, but give up when there's an error
11911222 mapWhileOK f [] = return []
11921223 mapWhileOK f (x : xs) = do x' <- f x
src/Pkg/Package.hs+1
@@ -17,6 +17,7 @@ import Data.List.Split(splitOn)
1717import Idris.Core.TT
1818import Idris.REPL
1919import Idris.AbsSyntax
20+import Idris.Output
2021
2122import IRTS.System
2223
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