on master help sign in
Merge remote-tracking branch 'refs/remotes/origin/wip/tactical' into wip/tactical

Conflicts: libs/prelude/Language/Reflection/Tactical.idr src/Idris/ElabTerm.hs src/Idris/Reflection.hs

commit0ca171564568a2fd08d1efb114e23f14f7a4bdb2 authorDavid Raymond Christiansen <david@davidchristiansen.dk> dateMon 13 Apr 2015, 14:46 (12 years ago) parent7d2893e31f4c82
64 files changed+819−546
.gitignore+1 CHANGELOG+2 CONTRIBUTORS+1 Setup.hs+24−7 codegen/idris-c/Main.hs+4−1 docs/effects/introduction.rst+1−1 docs/faq/faq.rst+15 idris.cabal+5 libs/effects/Effect/Exception.idr+4−15 libs/effects/Effect/File.idr+16−16 libs/effects/Effect/Random.idr+12−13 libs/effects/Effect/Select.idr+2−2 libs/effects/Effect/State.idr+8−8 libs/effects/Effect/StdIO.idr+13−24 libs/effects/Effect/System.idr+8−8 libs/effects/Effects.idr+93−33 libs/prelude/IO.idr+3−1 libs/prelude/Language/Reflection/Elab.idr+149 libs/prelude/Language/Reflection/Tactical.idr−148 libs/prelude/Prelude.idr+1−1 libs/prelude/prelude.ipkg+1−1 main/Main.hs+2 src/IRTS/Compiler.hs+5−1 src/IRTS/Lang.hs+1−1 src/Idris/AbsSyntax.hs+4−4 src/Idris/AbsSyntaxTree.hs+43−28 src/Idris/Core/Elaborate.hs+1 src/Idris/Core/ProofTerm.hs+1−1 src/Idris/Core/TT.hs+1 src/Idris/DSL.hs+2−2 src/Idris/DeepSeq.hs+1−1 src/Idris/Elab/Class.hs+14−5 src/Idris/Elab/Value.hs+16−1 src/Idris/ElabQuasiquote.hs+2−2 src/Idris/ElabTerm.hs+38−16 src/Idris/Erasure.hs+3−16 src/Idris/Error.hs+1−1 src/Idris/IBC.hs+4−4 src/Idris/IdrisDoc.hs+3−3 src/Idris/ParseExpr.hs+67−50 src/Idris/Parser.hs+1−1 src/Idris/ProofSearch.hs+36−23 src/Idris/REPL.hs+9−11 src/Idris/REPLParser.hs+9−1 src/Idris/Reflection.hs+3−1 src/Idris/TypeSearch.hs+7−5 src/Util/System.hs+30−2 test/Makefile+1−1 test/basic010/Main.idr+1−1 test/basic010/run+31−25 test/effects001/test021.idr+1−2 test/effects001/test021a.idr+1−1 test/effects002/test025.idr+2−2 test/effects003/hangman.idr+28−26 test/effects004/effects004.idr+19 test/effects004/expected+11 test/effects004/input+10 test/effects004/run+4 test/ffi006/run+1−1 test/interactive007/expected.msys+1 test/reg039/run+27−24 test/runtest.pl+8 test/tactics001/Tactics.idr+4−4 win-release.sh+2
.gitignore+1
@@ -2,6 +2,7 @@ dist
22cabal-dev/
33.cabal-sandbox
44cabal.sandbox.config
5+cabal.config
56.hsenv
67*.ibc
78*.o
CHANGELOG+2
@@ -1,5 +1,6 @@
11New in 0.9.18:
22--------------
3+* Add support for bundled toolchains.
34* Strings are now UTF8 encoded in the default back end
45* Idris source files are now assumed to be in UTF8, regardless of locale
56 settings.
@@ -26,6 +27,7 @@ New in 0.9.18:
2627* The default Semigroup and Monoid instances for Maybe are now prioritised
2728 choice, keeping the first success as Alternative does. The version that
2829 collects successes is now a named instance.
30+* :exec REPL command now takes an optional expression to compile and run/show
2931
3032New in 0.9.17:
3133--------------
CONTRIBUTORS+1
@@ -32,6 +32,7 @@ Adam Sandberg Eriksson
3232Seo Sanghyeon
3333Benjamin Saunders
3434Alexander Shabalin
35+JP Smith
3536startling
3637Chetan T
3738Matúš Tejiščák
Setup.hs+24−7
@@ -62,7 +62,7 @@ execOnly flags =
6262 case lookup (FlagName "execonly") (S.configConfigurationsFlags flags) of
6363 Just True -> True
6464 Just False -> False
65− Nothing -> True
65+ Nothing -> False
6666
6767isRelease :: S.ConfigFlags -> Bool
6868isRelease flags =
@@ -137,17 +137,33 @@ generateTargetModule verbosity dir targetDir = do
137137 ++ " dir <- getDataDir\n"
138138 ++ " return (dir ++ \"/\" ++ name)"
139139
140+-- a module that has info about existence and location of a bundled toolchain
141+generateToolchainModule verbosity srcDir toolDir = do
142+ let commonContent = "module Tools_idris where\n\n"
143+ let toolContent = case toolDir of
144+ Just dir -> "hasBundledToolchain = True\n" ++
145+ "getToolchainDir = \"" ++ dir ++ "\"\n"
146+ Nothing -> "hasBundledToolchain = False\n" ++
147+ "getToolchainDir = \"\""
148+ let toolPath = srcDir </> "Tools_idris" Px.<.> "hs"
149+ createDirectoryIfMissingVerbose verbosity True srcDir
150+ rewriteFile toolPath (commonContent ++ toolContent)
140151
141152idrisConfigure _ flags _ local = do
142− configureRTS
143− generateVersionModule verbosity (autogenModulesDir local) (isRelease (configFlags local))
144− when (isFreestanding $ configFlags local) (do
145− targetDir <- lookupEnv "IDRIS_INSTALL_DIR"
153+ configureRTS
154+ generateVersionModule verbosity (autogenModulesDir local) (isRelease (configFlags local))
155+ if (isFreestanding $ configFlags local)
156+ then (do
157+ toolDir <- lookupEnv "IDRIS_TOOLCHAIN_DIR"
158+ generateToolchainModule verbosity (autogenModulesDir local) toolDir
159+ targetDir <- lookupEnv "IDRIS_LIB_DIR"
146160 case targetDir of
147161 Just d -> generateTargetModule verbosity (autogenModulesDir local) d
148162 Nothing -> error $ "Trying to build freestanding without a target directory."
149− ++ " Set it by defining IDRIS_INSTALL_DIR.")
150− where
163+ ++ " Set it by defining IDRIS_LIB_DIR.")
164+ else
165+ generateToolchainModule verbosity (autogenModulesDir local) Nothing
166+ where
151167 verbosity = S.fromFlag $ S.configVerbosity flags
152168 version = pkgVersion . package $ localPkgDescr local
153169
@@ -162,6 +178,7 @@ idrisPreSDist args flags = do
162178 let verb = S.fromFlag (S.sDistVerbosity flags)
163179 generateVersionModule verb ("src") True
164180 generateTargetModule verb "src" "./libs"
181+ generateToolchainModule verb "src" Nothing
165182 preSDist simpleUserHooks args flags
166183
167184idrisPostSDist args flags desc lbi = do
codegen/idris-c/Main.hs+4−1
@@ -14,6 +14,8 @@ import Control.Monad
1414
1515import Paths_idris
1616
17+import Util.System
18+
1719data Opts = Opts { inputs :: [FilePath],
1820 interface :: Bool,
1921 output :: FilePath }
@@ -31,7 +33,8 @@ getOpts = do xs <- getArgs
3133 process opts [] = opts
3234
3335c_main :: Opts -> Idris ()
34−c_main opts = do elabPrims
36+c_main opts = do runIO setupBundledCC
37+ elabPrims
3538 loadInputs (inputs opts) Nothing
3639 mainProg <- if interface opts
3740 then liftM Just elabMain
docs/effects/introduction.rst+1−1
@@ -66,7 +66,7 @@ library:
6666 import Effects
6767 import Effect.StdIO
6868
69− hello : [STDIO] Eff ()
69+ hello : {[STDIO]} Eff ()
7070 hello = putStrLn “Hello world!”
7171
7272 main : IO ()
docs/faq/faq.rst+15
@@ -131,6 +131,21 @@ choice by the developers of Idris, Idris uses the C style convention.
131131That is, the names ``Float`` and ``Double`` are used to describe
132132single and double precision numbers.
133133
134+What is -ffreestanding?
135+=======================
136+
137+The freestanding flag is used to build Idris binaries which have their
138+libs and compiler in a relative path. This is useful for building binaries
139+where the install directory is unknown at build time. When passing this
140+flag, the IDRIS_LIB_DIR environment variable needs to be set to the path
141+where the Idris libs reside relative to the idris executable. The
142+IDRIS_TOOLCHAIN_DIR environment variable is optional, if that is set,
143+Idris will use that path to find the C compiler.
144+
145+Example:
146+.. code-block::
147+ IDRIS_LIB_DIR="./libs" IDRIS_TOOLCHAIN_DIR="./mingw/bin" CABALFLAGS="-fffi -ffreestanding -frelease" make
148+
134149What does the name ‘Idris’ mean?
135150================================
136151
idris.cabal+5
@@ -373,6 +373,10 @@ Extra-source-files:
373373 test/effects003/*.idr
374374 test/effects003/expected
375375 test/effects003/input
376+ test/effects004/run
377+ test/effects004/*.idr
378+ test/effects004/expected
379+ test/effects004/input
376380
377381 test/error001/run
378382 test/error001/*.idr
@@ -806,6 +810,7 @@ Library
806810 -- Auto Generated
807811 , Paths_idris
808812 , Version_idris
813+ , Tools_idris
809814
810815 Build-depends: base >=4 && <5
811816 , annotated-wl-pprint >= 0.5.3 && < 0.6
libs/effects/Effect/Exception.idr+4−15
@@ -4,8 +4,8 @@ import Effects
44import System
55import Control.IOExcept
66
7−data Exception : Type -> Effect where
8− Raise : a -> { () } Exception a b
7+data Exception : Type -> Effect where
8+ Raise : a -> sig (Exception a) b
99
1010instance Handler (Exception a) Maybe where
1111 handle _ (Raise e) k = Nothing
@@ -14,7 +14,7 @@ instance Handler (Exception a) List where
1414 handle _ (Raise e) k = []
1515
1616instance Show a => Handler (Exception a) IO where
17− handle _ (Raise e) k = do printLn e
17+ handle _ (Raise e) k = do print e
1818 believe_me (exit 1)
1919
2020instance Handler (Exception a) (IOExcept a) where
@@ -26,16 +26,5 @@ instance Handler (Exception a) (Either a) where
2626EXCEPTION : Type -> EFFECT
2727EXCEPTION t = MkEff () (Exception t)
2828
29−raise : a -> { [EXCEPTION a ] } Eff b
29+raise : a -> Eff b [EXCEPTION a]
3030raise err = call $ Raise err
31−
32−
33−
34−
35−
36−
37−-- TODO: Catching exceptions mid program?
38−-- probably need to invoke a new interpreter
39−
40−-- possibly add a 'handle' to the Eff language so that an alternative
41−-- handler can be introduced mid interpretation?
libs/effects/Effect/File.idr+16−16
@@ -46,29 +46,29 @@ data FileIO : Effect where
4646 ||| @ m The file mode.
4747 Open : (fname: String)
4848 -> (m : Mode)
49− -> {() ==> {res} if res
50− then OpenFile m
51− else ()} FileIO Bool
49+ -> sig FileIO Bool () (\res => case res of
50+ True => OpenFile m
51+ False => ())
5252
5353 ||| Close a file.
5454 |||
5555 ||| Closing a file moves the state from Open to closed.
56− Close : {OpenFile m ==> ()} FileIO ()
56+ Close : sig FileIO () (OpenFile m) ()
5757
5858 ||| Read a line from the file.
5959 |||
6060 ||| Only files that are open for reading can be read.
61− ReadLine : {OpenFile Read} FileIO String
61+ ReadLine : sig FileIO String (OpenFile Read)
6262
6363 ||| Write a string to a file.
6464 |||
6565 ||| Only file that are open for writing can be written to.
66− WriteString : String -> {OpenFile Write} FileIO ()
66+ WriteString : String -> sig FileIO () (OpenFile Write)
6767
6868 ||| End of file?
6969 |||
7070 ||| Only files open for reading can be tested for EOF
71− EOF : {OpenFile Read} FileIO Bool
71+ EOF : sig FileIO Bool (OpenFile Read)
7272
7373-- ------------------------------------------------------------ [ The Handlers ]
7474
@@ -117,31 +117,31 @@ FILE_IO t = MkEff t FileIO
117117||| @ m The file mode.
118118open : (fname : String)
119119 -> (m : Mode)
120− -> { [FILE_IO ()] ==> {result}
121− [FILE_IO (if result
122− then OpenFile m
123− else ())] } Eff Bool
120+ -> Eff Bool [FILE_IO ()]
121+ (\res => [FILE_IO (case res of
122+ True => OpenFile m
123+ False => ())])
124124open f m = call $ Open f m
125125
126126
127127||| Close a file.
128−close : { [FILE_IO (OpenFile m)] ==> [FILE_IO ()] } Eff ()
128+close : Eff () [FILE_IO (OpenFile m)] [FILE_IO ()]
129129close = call $ Close
130130
131131||| Read a line from the file.
132−readLine : { [FILE_IO (OpenFile Read)] } Eff String
132+readLine : Eff String [FILE_IO (OpenFile Read)]
133133readLine = call $ ReadLine
134134
135135||| Write a string to a file.
136−writeString : String -> { [FILE_IO (OpenFile Write)] } Eff ()
136+writeString : String -> Eff () [FILE_IO (OpenFile Write)]
137137writeString str = call $ WriteString str
138138
139139||| Write a line to a file.
140−writeLine : String -> { [FILE_IO (OpenFile Write)] } Eff ()
140+writeLine : String -> Eff () [FILE_IO (OpenFile Write)]
141141writeLine str = call $ WriteString (str ++ "\n")
142142
143143||| End of file?
144−eof : { [FILE_IO (OpenFile Read)] } Eff Bool
144+eof : Eff Bool [FILE_IO (OpenFile Read)]
145145eof = call $ EOF
146146
147147-- --------------------------------------------------------------------- [ EOF ]
libs/effects/Effect/Random.idr+12−13
@@ -5,28 +5,27 @@ import Data.Vect
55import Data.Fin
66
77data Random : Effect where
8− getRandom : { Integer } Random Integer
9− setSeed : Integer -> { Integer } Random ()
8+ getRandom : sig Random Integer Integer
9+ setSeed : Integer -> sig Random () Integer
1010
11−using (m : Type -> Type)
12− instance Handler Random m where
13− handle seed getRandom k
14− = let seed' = assert_total ((1664525 * seed + 1013904223) `prim__sremBigInt` (pow 2 32)) in
15− k seed' seed'
16− handle seed (setSeed n) k = k () n
11+instance Handler Random m where
12+ handle seed getRandom k
13+ = let seed' = assert_total ((1664525 * seed + 1013904223) `prim__sremBigInt` (pow 2 32)) in
14+ k seed' seed'
15+ handle seed (setSeed n) k = k () n
1716
1817RND : EFFECT
1918RND = MkEff Integer Random
2019
2120||| Generates a random Integer in a given range
22−rndInt : Integer -> Integer -> { [RND] } Eff Integer
21+rndInt : Integer -> Integer -> Eff Integer [RND]
2322rndInt lower upper = do v <- call $ getRandom
2423 return ((v `prim__sremBigInt` (upper - lower)) + lower)
2524
2625||| Generate a random number in Fin (S `k`)
2726|||
2827||| Note that rndFin k takes values 0, 1, ..., k.
29−rndFin : (k : Nat) -> { [RND] } Eff (Fin (S k))
28+rndFin : (k : Nat) -> Eff (Fin (S k)) [RND]
3029rndFin k = do let v = assert_total $ !(call getRandom) `prim__sremBigInt` (cast (S k))
3130 return (toFin v)
3231 where toFin : Integer -> Fin (S k)
@@ -35,15 +34,15 @@ rndFin k = do let v = assert_total $ !(call getRandom) `prim__sremBigInt` (cast
3534 Nothing => toFin (assert_smaller x (x - cast (S k)))
3635
3736||| Select a random element from a vector
38−rndSelect' : Vect (S k) a -> { [RND] } Eff a
37+rndSelect' : Vect (S k) a -> Eff a [RND]
3938rndSelect' {k} xs = return (Vect.index !(rndFin k) xs)
4039
4140||| Select a random element from a list, or Nothing if the list is empty
42−rndSelect : List a -> { [RND] } Eff (Maybe a)
41+rndSelect : List a -> Eff (Maybe a) [RND]
4342rndSelect [] = return Nothing
4443rndSelect (x::xs) = return (Just !(rndSelect' (x::(fromList xs))))
4544
4645||| Sets the random seed
47−srand : Integer -> { [RND] } Eff ()
46+srand : Integer -> Eff () [RND]
4847srand n = call $ setSeed n
4948
libs/effects/Effect/Select.idr+2−2
@@ -3,7 +3,7 @@ module Effect.Select
33import Effects
44
55data Selection : Effect where
6− Select : List a -> { () } Selection a
6+ Select : List a -> sig Selection a ()
77
88instance Handler Selection Maybe where
99 handle _ (Select xs) k = tryAll xs where
@@ -18,6 +18,6 @@ instance Handler Selection List where
1818SELECT : EFFECT
1919SELECT = MkEff () Selection
2020
21−select : List a -> { [SELECT] } Eff a
21+select : List a -> Eff a [SELECT]
2222select xs = call $ Select xs
2323
libs/effects/Effect/State.idr+8−8
@@ -5,8 +5,8 @@ import Effects
55%access public
66
77data State : Effect where
8− Get : { a } State a
9− Put : b -> { a ==> b } State ()
8+ Get : sig State a a
9+ Put : b -> sig State () a b
1010
1111-- using (m : Type -> Type)
1212instance Handler State m where
@@ -16,22 +16,22 @@ instance Handler State m where
1616STATE : Type -> EFFECT
1717STATE t = MkEff t State
1818
19−get : { [STATE x] } Eff x
19+get : Eff x [STATE x]
2020get = call $ Get
2121
22−put : x -> { [STATE x] } Eff ()
22+put : x -> Eff () [STATE x]
2323put val = call $ Put val
2424
25−putM : y -> { [STATE x] ==> [STATE y] } Eff ()
25+putM : y -> Eff () [STATE x] [STATE y]
2626putM val = call $ Put val
2727
28−update : (x -> x) -> { [STATE x] } Eff ()
28+update : (x -> x) -> Eff () [STATE x]
2929update f = put (f !get)
3030
31−updateM : (x -> y) -> { [STATE x] ==> [STATE y] } Eff ()
31+updateM : (x -> y) -> Eff () [STATE x] [STATE y]
3232updateM f = putM (f !get)
3333
34−locally : x -> ({ [STATE x] } Eff t) -> { [STATE y] } Eff t
34+locally : x -> (Eff t [STATE x]) -> Eff t [STATE y]
3535locally newst prog = do st <- get
3636 putM newst
3737 val <- prog
libs/effects/Effect/StdIO.idr+13−24
@@ -9,10 +9,10 @@ import Control.IOExcept
99
1010||| The internal representation of StdIO effects
1111data StdIO : Effect where
12− PutStr : String -> { () } StdIO ()
13− GetStr : { () } StdIO String
14− PutCh : Char -> { () } StdIO ()
15− GetCh : { () } StdIO Char
12+ PutStr : String -> sig StdIO ()
13+ GetStr : sig StdIO String
14+ PutCh : Char -> sig StdIO ()
15+ GetCh : sig StdIO Char
1616
1717
1818-------------------------------------------------------------
@@ -22,13 +22,13 @@ data StdIO : Effect where
2222instance Handler StdIO IO where
2323 handle () (PutStr s) k = do putStr s; k () ()
2424 handle () GetStr k = do x <- getLine; k x ()
25− handle () (PutCh c) k = do putChar c; k () ()
25+ handle () (PutCh c) k = do putChar c; k () ()
2626 handle () GetCh k = do x <- getChar; k x ()
2727
2828instance Handler StdIO (IOExcept a) where
2929 handle () (PutStr s) k = do ioe_lift $ putStr s; k () ()
3030 handle () GetStr k = do x <- ioe_lift $ getLine; k x ()
31− handle () (PutCh c) k = do ioe_lift $ putChar c; k () ()
31+ handle () (PutCh c) k = do ioe_lift $ putChar c; k () ()
3232 handle () GetCh k = do x <- ioe_lift $ getChar; k x ()
3333
3434-------------------------------------------------------------
@@ -39,33 +39,22 @@ STDIO : EFFECT
3939STDIO = MkEff () StdIO
4040
4141||| Write a string to standard output.
42−putStr : String -> { [STDIO] } Eff ()
42+putStr : String -> Eff () [STDIO]
4343putStr s = call $ PutStr s
4444
45−||| Write a string to standard output, terminating with a newline.
46−putStrLn : String -> { [STDIO] } Eff ()
47−putStrLn s = putStr (s ++ "\n")
48−
4945||| Write a character to standard output.
50−putChar : Char -> { [STDIO] } Eff ()
46+putChar : Char -> Eff () [STDIO]
5147putChar c = call $ PutCh c
5248
53−||| Write a character to standard output, terminating with a newline.
54−putCharLn : Char -> { [STDIO] } Eff ()
55−putCharLn c = putStrLn (singleton c)
49+||| Write a string to standard output, terminating with a newline.
50+putStrLn : String -> Eff () [STDIO]
51+putStrLn s = putStr (s ++ "\n")
5652
5753||| Read a string from standard input.
58−getStr : { [STDIO] } Eff String
54+getStr : Eff String [STDIO]
5955getStr = call $ GetStr
6056
6157||| Read a character from standard input.
62−getChar : { [STDIO] } Eff Char
58+getChar : Eff Char [STDIO]
6359getChar = call $ GetCh
6460
65−||| Given a parameter `a` 'show' `a` to standard output.
66−print : Show a => a -> { [STDIO] } Eff ()
67−print a = putStr (show a)
68−
69−||| Given a parameter `a` 'show' `a` to a standard output, terminating with a newline
70−printLn : Show a => a -> { [STDIO] } Eff ()
71−printLn a = putStrLn (show a)
libs/effects/Effect/System.idr+8−8
@@ -8,10 +8,10 @@ import System
88import Control.IOExcept
99
1010data System : Effect where
11− Args : { () } System (List String)
12− Time : { () } System Int
13− GetEnv : String -> { () } System (Maybe String)
14− CSystem : String -> { () } System Int
11+ Args : sig System (List String)
12+ Time : sig System Int
13+ GetEnv : String -> sig System (Maybe String)
14+ CSystem : String -> sig System Int
1515
1616instance Handler System IO where
1717 handle () Args k = do x <- getArgs; k x ()
@@ -30,14 +30,14 @@ instance Handler System (IOExcept a) where
3030SYSTEM : EFFECT
3131SYSTEM = MkEff () System
3232
33−getArgs : { [SYSTEM] } Eff (List String)
33+getArgs : Eff (List String) [SYSTEM]
3434getArgs = call Args
3535
36−time : { [SYSTEM] } Eff Int
36+time : Eff Int [SYSTEM]
3737time = call Time
3838
39−getEnv : String -> { [SYSTEM] } Eff (Maybe String)
39+getEnv : String -> Eff (Maybe String) [SYSTEM]
4040getEnv s = call $ GetEnv s
4141
42−system : String -> { [SYSTEM] } Eff Int
42+system : String -> Eff Int [SYSTEM]
4343system s = call $ CSystem s
libs/effects/Effects.idr+93−33
@@ -24,6 +24,28 @@ Effect = (x : Type) -> Type -> (x -> Type) -> Type
2424data EFFECT : Type where
2525 MkEff : Type -> Effect -> EFFECT
2626
27+-- 'sig' gives the signature for an effect. There are four versions
28+-- depending on whether there is no resource needed,
29+-- no state change, a non-dependent change,
30+-- or a dependent change. These are easily disambiguated by type.
31+
32+namespace NoResourceEffect
33+ sig : Effect -> Type -> Type
34+ sig e r = e r () (\v => ())
35+
36+namespace NoUpdateEffect
37+ sig : Effect -> (ret : Type) -> (resource : Type) -> Type
38+ sig e r e_in = e r e_in (\v => e_in)
39+
40+namespace UpdateEffect
41+ sig : Effect -> (ret : Type) -> (res_in : Type) -> (res_out : Type) -> Type
42+ sig e r e_in e_out = e r e_in (\v => e_out)
43+
44+namespace DepUpdateEffect
45+ sig : Effect ->
46+ (ret : Type) -> (res_in : Type) -> (res_out : ret -> Type) -> Type
47+ sig e r e_in e_out = e r e_in e_out
48+
2749||| Handler classes describe how an effect `e` is translated to the
2850||| underlying computation context `m` for execution.
2951class Handler (e : Effect) (m : Type -> Type) where
@@ -60,6 +82,7 @@ data SubList : List a -> List a -> Type where
6082 Keep : SubList xs ys -> SubList (x :: xs) (x :: ys)
6183 Drop : SubList xs ys -> SubList xs (x :: ys)
6284
85+%hint
6386subListId : SubList xs xs
6487subListId {xs = Nil} = SubNil
6588subListId {xs = x :: xs} = Keep subListId
@@ -133,26 +156,61 @@ relabel {xs = (MkEff a e :: xs)} l (v :: vs) = (l := v) :: relabel l vs
133156||| @ x The return type of the result.
134157||| @ es The list of allowed side-effects.
135158||| @ ce Function to compute a new list of allowed side-effects.
136−data Eff : (x : Type)
137− -> (es : List EFFECT)
138− -> (ce : x -> List EFFECT) -> Type where
139− value : (val : a) -> Eff a (xs val) xs
140− ebind : Eff a xs xs' ->
141− ((val : a) -> Eff b (xs' val) xs'') -> Eff b xs xs''
159+data EffM : (m : Type -> Type) -> (x : Type)
160+ -> (es : List EFFECT)
161+ -> (ce : x -> List EFFECT) -> Type where
162+ value : (val : a) -> EffM m a (xs val) xs
163+ ebind : EffM m a xs xs' ->
164+ ((val : a) -> EffM m b (xs' val) xs'') -> EffM m b xs xs''
142165 callP : (prf : EffElem e a xs) ->
143166 (eff : e t a b) ->
144− Eff t xs (\v => updateResTy v xs prf eff)
167+ EffM m t xs (\v => updateResTy v xs prf eff)
145168
146169 liftP : (prf : SubList ys xs) ->
147− Eff t ys ys' -> Eff t xs (\v => updateWith (ys' v) xs prf)
170+ EffM m t ys ys' -> EffM m t xs (\v => updateWith (ys' v) xs prf)
171+
172+ new : Handler e' m => (e : EFFECT) -> resTy ->
173+ {auto prf : e = MkEff resTy e'} ->
174+ EffM m t (e :: es) (\v => e :: es) ->
175+ EffM m t es (\v => es)
148176
149177 (:-) : (l : ty) ->
150− Eff t [x] xs' -> -- [x] (\v => xs) ->
151− Eff t [l ::: x] (\v => map (l :::) (xs' v))
178+ EffM m t [x] xs' -> -- [x] (\v => xs) ->
179+ EffM m t [l ::: x] (\v => map (l :::) (xs' v))
180+
181+-- Some type synonyms, so we don't always have to write EffM in full
182+
183+namespace SimpleEff
184+ -- Simple effects, no updates
185+ Eff : (x : Type) -> (es : List EFFECT) -> Type
186+ Eff x es = {m : Type -> Type} -> EffM m x es (\v => es)
187+
188+ EffT : (m : Type -> Type) -> (x : Type) -> (es : List EFFECT) -> Type
189+ EffT m x es = EffM m x es (\v => es)
190+
191+namespace TransEff
192+ -- Dependent effects, updates not dependent on result
193+ Eff : (x : Type) -> (es : List EFFECT) -> (ce : List EFFECT) -> Type
194+ Eff x es ce = {m : Type -> Type} -> EffM m x es (\_ => ce)
195+
196+ EffT : (m : Type -> Type) ->
197+ (x : Type) -> (es : List EFFECT) -> (ce : List EFFECT) -> Type
198+ EffT m x es ce = EffM m x es (\_ => ce)
199+
200+namespace DepEff
201+ -- Dependent effects, updates dependent on result
202+ Eff : (x : Type) -> (es : List EFFECT)
203+ -> (ce : x -> List EFFECT) -> Type
204+ Eff x es ce = {m : Type -> Type} -> EffM m x es ce
205+
206+ EffT : (m : Type -> Type) -> (x : Type) -> (es : List EFFECT)
207+ -> (ce : x -> List EFFECT) -> Type
208+ EffT m x es ce = EffM m x es ce
209+
152210
153211%no_implicit
154−(>>=) : Eff a xs xs' ->
155− ((val : a) -> Eff b (xs' val) xs'') -> Eff b xs xs''
212+(>>=) : EffM m a xs xs' ->
213+ ((val : a) -> EffM m b (xs' val) xs'') -> EffM m b xs xs''
156214(>>=) = ebind
157215
158216-- namespace SimpleBind
@@ -161,29 +219,29 @@ data Eff : (x : Type)
161219-- (>>=) = ebind
162220
163221||| Run a subprogram which results in an effect state the same as the input.
164−staticEff : Eff a xs (\v => xs) -> Eff a xs (\v => xs)
222+staticEff : EffM m a xs (\v => xs) -> EffM m a xs (\v => xs)
165223staticEff = id
166224
167225||| Explicitly give the expected set of result effects for an effectful
168226||| operation.
169−toEff : .(xs' : List EFFECT) -> Eff a xs (\v => xs') -> Eff a xs (\v => xs')
227+toEff : .(xs' : List EFFECT) -> EffM m a xs (\v => xs') -> EffM m a xs (\v => xs')
170228toEff xs' = id
171229
172−return : a -> Eff a xs (\v => xs)
230+return : a -> EffM m a xs (\v => xs)
173231return x = value x
174232
175233-- ------------------------------------------------------ [ for idiom brackets ]
176234
177235infixl 2 <*>
178236
179−pure : a -> Eff a xs (\v => xs)
237+pure : a -> EffM m a xs (\v => xs)
180238pure = value
181239
182−pureM : (val : a) -> Eff a (xs val) xs
240+pureM : (val : a) -> EffM m a (xs val) xs
183241pureM = value
184242
185−(<*>) : Eff (a -> b) xs (\v => xs) ->
186− Eff a xs (\v => xs) -> Eff b xs (\v => xs)
243+(<*>) : EffM m (a -> b) xs (\v => xs) ->
244+ EffM m a xs (\v => xs) -> EffM m b xs (\v => xs)
187245(<*>) prog v = do fn <- prog
188246 arg <- v
189247 return (fn arg)
@@ -203,7 +261,7 @@ execEff {e} {a} {res} {resk} (val :: env) (There p) eff k
203261-- Q: Instead of m b, implement as StateT (Env m xs') m b, so that state
204262-- updates can be propagated even through failing computations?
205263
206−eff : Env m xs -> Eff a xs xs' -> ((x : a) -> Env m (xs' x) -> m b) -> m b
264+eff : Env m xs -> EffM m a xs xs' -> ((x : a) -> Env m (xs' x) -> m b) -> m b
207265eff env (value x) k = k x env
208266eff env (prog `ebind` c) k
209267 = eff env prog (\p', env' => eff env' (c p') k)
@@ -211,6 +269,8 @@ eff env (callP prf effP) k = execEff env prf effP k
211269eff env (liftP prf effP) k
212270 = let env' = dropEnv env prf in
213271 eff env' effP (\p', envk => k p' (rebuildEnv envk prf env))
272+eff env (new (MkEff resTy newEff) res {prf=Refl} effP) k
273+ = eff (res :: env) effP (\p', (val :: envk) => k p' envk)
214274-- FIXME:
215275-- xs is needed explicitly because otherwise the pattern binding for
216276-- 'l' appears too late. Solution seems to be to reorder patterns at the
@@ -235,14 +295,14 @@ call : {a, b: _} -> {e : Effect} ->
235295 (eff : e t a b) ->
236296 {default tactics { search 100; }
237297 prf : EffElem e a xs} ->
238− Eff t xs (\v => updateResTy v xs prf eff)
298+ EffM m t xs (\v => updateResTy v xs prf eff)
239299call e {prf} = callP prf e
240300
241301implicit
242−lift : Eff t ys ys' ->
302+lift : EffM m t ys ys' ->
243303 {default tactics { search 100; }
244304 prf : SubList ys xs} ->
245− Eff t xs (\v => updateWith (ys' v) xs prf)
305+ EffM m t xs (\v => updateWith (ys' v) xs prf)
246306lift e {prf} = liftP prf e
247307
248308
@@ -255,7 +315,7 @@ lift e {prf} = liftP prf e
255315|||
256316||| @prog The effectful program to run.
257317run : Applicative m => {default MkDefaultEnv env : Env m xs}
258− -> (prog : Eff a xs xs') -> m a
318+ -> (prog : EffM m a xs xs') -> m a
259319run {env} prog = eff env prog (\r, env => pure r)
260320
261321||| Run an effectful program in the identity context.
@@ -264,7 +324,7 @@ run {env} prog = eff env prog (\r, env => pure r)
264324||| The `env` argument is implicit and initialised automatically.
265325|||
266326||| @prog The effectful program to run.
267−runPure : {default MkDefaultEnv env : Env id xs} -> (prog : Eff a xs xs') -> a
327+runPure : {default MkDefaultEnv env : Env id xs} -> (prog : EffM id a xs xs') -> a
268328runPure {env} prog = eff env prog (\r, env => r)
269329
270330||| Run an effectful program in a given context `m` with a default value for the environment.
@@ -273,7 +333,7 @@ runPure {env} prog = eff env prog (\r, env => r)
273333|||
274334||| @env The environment to use.
275335||| @prog The effectful program to run.
276−runInit : Applicative m => (env : Env m xs) -> (prog : Eff a xs xs') -> m a
336+runInit : Applicative m => (env : Env m xs) -> (prog : EffM m a xs xs') -> m a
277337runInit env prog = eff env prog (\r, env => pure r)
278338
279339||| Run an effectful program with a given default value for the environment.
@@ -282,31 +342,31 @@ runInit env prog = eff env prog (\r, env => pure r)
282342|||
283343||| @env The environment to use.
284344||| @prog The effectful program to run.
285−runPureInit : (env : Env id xs) -> (prog : Eff a xs xs') -> a
345+runPureInit : (env : Env id xs) -> (prog : EffM id a xs xs') -> a
286346runPureInit env prog = eff env prog (\r, env => r)
287347
288−runWith : (a -> m a) -> Env m xs -> Eff a xs xs' -> m a
348+runWith : (a -> m a) -> Env m xs -> EffM m a xs xs' -> m a
289349runWith inj env prog = eff env prog (\r, env => inj r)
290350
291−runEnv : Applicative m => Env m xs -> Eff a xs xs' ->
351+runEnv : Applicative m => Env m xs -> EffM m a xs xs' ->
292352 m (x : a ** Env m (xs' x))
293353runEnv env prog = eff env prog (\r, env => pure (r ** env))
294354
295355-- ----------------------------------------------- [ some higher order things ]
296356
297−mapE : (a -> {xs} Eff b) -> List a -> {xs} Eff (List b)
357+mapE : (a -> {xs} EffM m b) -> List a -> {xs} EffM m (List b)
298358mapE f [] = pure []
299359mapE f (x :: xs) = [| f x :: mapE f xs |]
300360
301361
302−mapVE : (a -> {xs} Eff b) ->
362+mapVE : (a -> {xs} EffM m b) ->
303363 Vect n a ->
304− {xs} Eff (Vect n b)
364+ {xs} EffM m (Vect n b)
305365mapVE f [] = pure []
306366mapVE f (x :: xs) = [| f x :: mapVE f xs |]
307367
308368
309−when : Bool -> Lazy ({xs} Eff ()) -> {xs} Eff ()
369+when : Bool -> Lazy ({xs} EffM m ()) -> {xs} EffM m ()
310370when True e = Force e
311371when False e = pure ()
312372
libs/prelude/IO.idr+3−1
@@ -152,13 +152,15 @@ FFI_C = MkFFI C_Types String String
152152IO : Type -> Type
153153IO = IO' FFI_C
154154
155+-- Cannot be relaxed as is used by type providers and they expect IO a
156+-- in the first argument.
155157run__provider : IO a -> PrimIO a
156158run__provider (MkIO f) = f (TheWorld prim__TheWorld)
157159
158160prim_fork : PrimIO () -> PrimIO Ptr
159161prim_fork x = prim_io_return prim__vm -- compiled specially
160162
161−fork : IO () -> IO Ptr
163+fork : IO' l () -> IO' l Ptr
162164fork (MkIO f) = MkIO (\w => prim_io_bind
163165 (prim_fork (prim_io_bind (f w)
164166 (\ x => prim_io_return x)))
libs/prelude/Language/Reflection/Elab.idrnew file+149
@@ -0,0 +1,149 @@
1+module Language.Reflection.Elab
2+
3+import Builtins
4+import Prelude.Applicative
5+import Prelude.Functor
6+import Prelude.List
7+import Prelude.Maybe
8+import Prelude.Monad
9+import Language.Reflection
10+
11+data Arg : Type where
12+ Explicit : TTName -> Raw -> Arg
13+ Implicit : TTName -> Raw -> Arg
14+ Constraint : TTName -> Raw -> Arg
15+
16+data TyDecl : Type where
17+ Declare : TTName -> List Arg -> Raw -> TyDecl
18+
19+data FunClause : Type where
20+ MkFunClause : (lhs, rhs : Raw) -> FunClause
21+ MkImpossibleClause : (lhs : Raw) -> FunClause
22+
23+data FunDefn : Type where
24+ DefineFun : TTName -> List FunClause -> FunDefn
25+
26+abstract
27+data Elab : Type -> Type where
28+ -- obligatory control stuff
29+ prim__PureElab : a -> Elab a
30+ prim__BindElab : {a, b : Type} -> Elab a -> (a -> Elab b) -> Elab b
31+
32+ prim__Try : {a : Type} -> Elab a -> Elab a -> Elab a
33+ prim__Fail : {a : Type} -> List ErrorReportPart -> Elab a
34+
35+ prim__Env : Elab (List (TTName, Binder TT))
36+ prim__Goal : Elab (TTName, TT)
37+ prim__Holes : Elab (List TTName)
38+ prim__Guess : Elab (Maybe TT)
39+
40+ prim__SourceLocation : Elab SourceLocation
41+
42+ prim__Forget : TT -> Elab Raw
43+
44+ prim__Gensym : String -> Elab TTName
45+
46+ prim__Solve : Elab ()
47+ prim__Fill : Raw -> Elab ()
48+ prim__Focus : TTName -> Elab ()
49+ prim__Unfocus : TTName -> Elab ()
50+ prim__Attack : Elab ()
51+
52+ prim__Rewrite : Raw -> Elab ()
53+
54+ prim__Claim : TTName -> Raw -> Elab ()
55+ prim__Intro : Maybe TTName -> Elab ()
56+
57+ prim__DeclareType : TyDecl -> Elab ()
58+ prim__DefineFunction : FunDefn -> Elab ()
59+
60+ prim__Debug : {a : Type} -> Maybe String -> Elab a
61+
62+
63+-------------
64+-- Public API
65+-------------
66+%access public
67+
68+instance Functor Elab where
69+ map f t = prim__BindElab t (\x => prim__PureElab (f x))
70+
71+instance Applicative Elab where
72+ pure x = prim__PureElab x
73+ f <*> x = prim__BindElab f $ \g =>
74+ prim__BindElab x $ \y =>
75+ prim__PureElab $ g y
76+
77+instance Alternative Elab where
78+ empty = prim__Fail [TextPart "empty"]
79+ x <|> y = prim__Try x y
80+
81+instance Monad Elab where
82+ x >>= f = prim__BindElab x f
83+
84+fail : List ErrorReportPart -> Elab a
85+fail err = prim__Fail err
86+
87+getEnv : Elab (List (TTName, Binder TT))
88+getEnv = prim__Env
89+
90+getGoal : Elab (TTName, TT)
91+getGoal = prim__Goal
92+
93+getHoles : Elab (List TTName)
94+getHoles = prim__Holes
95+
96+getGuess : Elab (Maybe TT)
97+getGuess = prim__Guess
98+
99+forgetTypes : TT -> Elab Raw
100+forgetTypes tt = prim__Forget tt
101+
102+gensym : (hint : String) -> Elab TTName
103+gensym hint = prim__Gensym hint
104+
105+solve : Elab ()
106+solve = prim__Solve
107+
108+fill : Raw -> Elab ()
109+fill tm = prim__Fill tm
110+
111+focus : (hole : TTName) -> Elab ()
112+focus hole = prim__Focus hole
113+
114+unfocus : TTName -> Elab ()
115+unfocus hole = prim__Unfocus hole
116+
117+attack : Elab ()
118+attack = prim__Attack
119+
120+claim : TTName -> Raw -> Elab ()
121+claim n ty = prim__Claim n ty
122+
123+intro : Maybe TTName -> Elab ()
124+intro n = prim__Intro n
125+
126+||| Find out the present source context for the tactic script
127+getSourceLocation : Elab SourceLocation
128+getSourceLocation = prim__SourceLocation
129+
130+||| Attempt to solve the current goal with the source code location
131+sourceLocation : Elab ()
132+sourceLocation = do loc <- getSourceLocation
133+ fill (quote loc)
134+ solve
135+
136+rewriteWith : Raw -> Elab ()
137+rewriteWith rule = prim__Rewrite rule
138+
139+declareType : TyDecl -> Elab ()
140+declareType decl = prim__DeclareType decl
141+
142+defineFunction : FunDefn -> Elab ()
143+defineFunction defun = prim__DefineFunction defun
144+
145+debug : Elab a
146+debug = prim__Debug Nothing
147+
148+debugMessage : String -> Elab a
149+debugMessage msg = prim__Debug (Just msg)
libs/prelude/Language/Reflection/Tactical.idrdeleted−148
@@ -1,148 +0,0 @@
1−module Language.Reflection.Tactical
2−
3−import Builtins
4−import Prelude.Applicative
5−import Prelude.Functor
6−import Prelude.List
7−import Prelude.Maybe
8−import Prelude.Monad
9−import Language.Reflection
10−
11−data Arg : Type where
12− Explicit : TTName -> Raw -> Arg
13− Implicit : TTName -> Raw -> Arg
14− Constraint : TTName -> Raw -> Arg
15−
16−data TyDecl : Type where
17− Declare : TTName -> List Arg -> Raw -> TyDecl
18−
19−data FunClause : Type where
20− MkFunClause : (lhs, rhs : Raw) -> FunClause
21−
22−data FunDefn : Type where
23− DefineFun : TTName -> List FunClause -> FunDefn
24−
25−abstract
26−data Tactical : Type -> Type where
27− -- obligatory control stuff
28− prim__PureTactical : a -> Tactical a
29− prim__BindTactical : {a, b : Type} -> Tactical a -> (a -> Tactical b) -> Tactical b
30−
31− prim__Try : {a : Type} -> Tactical a -> Tactical a -> Tactical a
32− prim__Fail : {a : Type} -> List ErrorReportPart -> Tactical a
33−
34− prim__Env : Tactical (List (TTName, Binder TT))
35− prim__Goal : Tactical (TTName, TT)
36− prim__Holes : Tactical (List TTName)
37− prim__Guess : Tactical (Maybe TT)
38−
39− prim__SourceLocation : Tactical SourceLocation
40−
41− prim__Forget : TT -> Tactical Raw
42−
43− prim__Gensym : String -> Tactical TTName
44−
45− prim__Solve : Tactical ()
46− prim__Fill : Raw -> Tactical ()
47− prim__Focus : TTName -> Tactical ()
48− prim__Unfocus : TTName -> Tactical ()
49− prim__Attack : Tactical ()
50−
51− prim__Rewrite : Raw -> Tactical ()
52−
53− prim__Claim : TTName -> Raw -> Tactical ()
54− prim__Intro : Maybe TTName -> Tactical ()
55−
56− prim__DeclareType : TyDecl -> Tactical ()
57− prim__DefineFunction : FunDefn -> Tactical ()
58−
59− prim__Debug : {a : Type} -> Maybe String -> Tactical a
60−
61−
62−-------------
63−-- Public API
64−-------------
65−%access public
66−
67−instance Functor Tactical where
68− map f t = prim__BindTactical t (\x => prim__PureTactical (f x))
69−
70−instance Applicative Tactical where
71− pure x = prim__PureTactical x
72− f <*> x = prim__BindTactical f $ \g =>
73− prim__BindTactical x $ \y =>
74− prim__PureTactical $ g y
75−
76−instance Alternative Tactical where
77− empty = prim__Fail [TextPart "empty"]
78− x <|> y = prim__Try x y
79−
80−instance Monad Tactical where
81− x >>= f = prim__BindTactical x f
82−
83−fail : List ErrorReportPart -> Tactical a
84−fail err = prim__Fail err
85−
86−getEnv : Tactical (List (TTName, Binder TT))
87−getEnv = prim__Env
88−
89−getGoal : Tactical (TTName, TT)
90−getGoal = prim__Goal
91−
92−getHoles : Tactical (List TTName)
93−getHoles = prim__Holes
94−
95−getGuess : Tactical (Maybe TT)
96−getGuess = prim__Guess
97−
98−forgetTypes : TT -> Tactical Raw
99−forgetTypes tt = prim__Forget tt
100−
101−gensym : (hint : String) -> Tactical TTName
102−gensym hint = prim__Gensym hint
103−
104−solve : Tactical ()
105−solve = prim__Solve
106−
107−fill : Raw -> Tactical ()
108−fill tm = prim__Fill tm
109−
110−focus : (hole : TTName) -> Tactical ()
111−focus hole = prim__Focus hole
112−
113−unfocus : TTName -> Tactical ()
114−unfocus hole = prim__Unfocus hole
115−
116−attack : Tactical ()
117−attack = prim__Attack
118−
119−claim : TTName -> Raw -> Tactical ()
120−claim n ty = prim__Claim n ty
121−
122−intro : Maybe TTName -> Tactical ()
123−intro n = prim__Intro n
124−
125−||| Find out the present source context for the tactic script
126−getSourceLocation : Tactical SourceLocation
127−getSourceLocation = prim__SourceLocation
128−
129−||| Attempt to solve the current goal with the source code location
130−sourceLocation : Tactical ()
131−sourceLocation = do loc <- getSourceLocation
132− fill (quote loc)
133− solve
134−
135−rewriteWith : Raw -> Tactical ()
136−rewriteWith rule = prim__Rewrite rule
137−
138−declareType : TyDecl -> Tactical ()
139−declareType decl = prim__DeclareType decl
140−
141−defineFunction : FunDefn -> Tactical ()
142−defineFunction defun = prim__DefineFunction defun
143−
144−debug : Tactical a
145−debug = prim__Debug Nothing
146−
147−debugMessage : String -> Tactical a
148−debugMessage msg = prim__Debug (Just msg)
libs/prelude/Prelude.idr+1−1
@@ -526,7 +526,7 @@ validFile (FHandle h) = do x <- nullPtr h
526526||| @ test the condition of the loop
527527||| @ body the loop body
528528partial -- obviously
529−while : (test : IO Bool) -> (body : IO ()) -> IO ()
529+while : (test : IO' l Bool) -> (body : IO' l ()) -> IO' l ()
530530while t b = do v <- t
531531 if v then do b
532532 while t b
libs/prelude/prelude.ipkg+1−1
@@ -10,7 +10,7 @@ modules = Builtins, Prelude, IO,
1010 Prelude.Foldable, Prelude.Traversable, Prelude.Bits, Prelude.Stream,
1111 Prelude.Uninhabited, Prelude.Pairs, Prelude.Providers,
1212
13− Language.Reflection, Language.Reflection.Errors, Language.Reflection.Tactical,
13+ Language.Reflection, Language.Reflection.Errors, Language.Reflection.Elab,
1414
1515 Decidable.Equality
1616
main/Main.hs+2
@@ -29,6 +29,7 @@ import Idris.CmdOptions
2929import IRTS.System ( getLibFlags, getIdrisLibDir, getIncFlags )
3030
3131import Util.DynamicLinker
32+import Util.System
3233
3334import Pkg.Package
3435
@@ -43,6 +44,7 @@ main = do opts <- runArgParser
4344
4445runIdris :: [Opt] -> Idris ()
4546runIdris opts = do
47+ runIO setupBundledCC
4648 when (ShowIncs `elem` opts) $ runIO showIncs
4749 when (ShowLibs `elem` opts) $ runIO showLibs
4850 when (ShowLibdir `elem` opts) $ runIO showLibdir
src/IRTS/Compiler.hs+5−1
@@ -51,8 +51,12 @@ compile codegen f mtm
5151 = do checkMVs -- check for undefined metavariables
5252 checkTotality -- refuse to compile if there are totality problems
5353 exports <- findExports
54+ let rootNames = case mtm of
55+ Nothing -> []
56+ Just t -> freeNames t
5457
55− reachableNames <- performUsageAnalysis (getExpNames exports)
58+ reachableNames <- performUsageAnalysis
59+ (rootNames ++ getExpNames exports)
5660 maindef <- case mtm of
5761 Nothing -> return []
5862 Just tm -> do md <- irMain tm
src/IRTS/Lang.hs+1−1
@@ -132,7 +132,7 @@ data LiftState = LS Name Int [(Name, LDecl)]
132132
133133lname (NS n x) i = NS (lname n i) x
134134lname (UN n) i = MN i n
135−lname x i = sMN i (show x)
135+lname x i = sMN i (show x ++ "_lam")
136136
137137liftAll :: [(Name, LDecl)] -> [(Name, LDecl)]
138138liftAll xs = concatMap (\ (x, d) -> lambdaLift x d) xs
src/Idris/AbsSyntax.hs+4−4
@@ -1011,7 +1011,7 @@ expandParams dec ps ns infs tm = en tm
10111011 en (PApp fc f as) = PApp fc (en f) (map (fmap en) as)
10121012 en (PAppBind fc f as) = PAppBind fc (en f) (map (fmap en) as)
10131013 en (PCase fc c os) = PCase fc (en c) (map (pmap en) os)
1014− en (PRunTactics fc tm) = PRunTactics fc (en tm)
1014+ en (PRunElab fc tm) = PRunElab fc (en tm)
10151015 en t = t
10161016
10171017 nselem x [] = False
@@ -1485,7 +1485,7 @@ implicitise syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
14851485 imps top env (PHidden tm) = imps False env tm
14861486 imps top env (PUnifyLog tm) = imps False env tm
14871487 imps top env (PNoImplicits tm) = imps False env tm
1488− imps top env (PRunTactics fc tm) = imps False env tm
1488+ imps top env (PRunElab fc tm) = imps False env tm
14891489 imps top env _ = return ()
14901490
14911491 pibind using [] sc = sc
@@ -1612,7 +1612,7 @@ addImpl' inpat env infns imp_meths ist ptm
16121612 ai qq env ds (PQuasiquote tm g) = PQuasiquote (ai True env ds tm)
16131613 (fmap (ai True env ds) g)
16141614 ai qq env ds (PUnquote tm) = PUnquote (ai False env ds tm)
1615− ai qq env ds (PRunTactics fc tm) = PRunTactics fc (ai False env ds tm)
1615+ ai qq env ds (PRunElab fc tm) = PRunElab fc (ai False env ds tm)
16161616 ai qq env ds tm = tm
16171617
16181618 handleErr (Left err) = PElabError err
@@ -2149,5 +2149,5 @@ mkUniqueNames env tm = evalState (mkUniq tm) (S.fromList env) where
21492149 mkUniq (PNoImplicits t) = liftM PNoImplicits (mkUniq t)
21502150 mkUniq (PProof ts) = liftM PProof (mapM mkUniqT ts)
21512151 mkUniq (PTactics ts) = liftM PTactics (mapM mkUniqT ts)
2152− mkUniq (PRunTactics fc ts) = liftM (PRunTactics fc ) (mkUniq ts)
2152+ mkUniq (PRunElab fc ts) = liftM (PRunElab fc ) (mkUniq ts)
21532153 mkUniq t = return t
src/Idris/AbsSyntaxTree.hs+43−28
@@ -369,7 +369,7 @@ data Command = Quit
369369 | ModImport String
370370 | Edit
371371 | Compile Codegen String
372− | Execute
372+ | Execute PTerm
373373 | ExecVal PTerm
374374 | Metavars
375375 | Prove Name
@@ -648,6 +648,7 @@ deriving instance NFData PDecl'
648648-- | A set of instructions for things that need to happen in IState
649649-- after a term elaboration when there's been reflected elaboration.
650650data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
651+ | RClausesInstrs Name [([Name], Term, Term)]
651652
652653-- | For elaborator state
653654data EState = EState {
@@ -825,7 +826,7 @@ data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level langua
825826 | PNoImplicits PTerm -- ^ never run implicit converions on the term
826827 | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
827828 | PUnquote PTerm -- ^ ~Term
828− | PRunTactics FC PTerm -- ^ %runTactics tm - New-style proof script
829+ | PRunElab FC PTerm -- ^ %runElab tm - New-style proof script
829830 deriving (Eq, Data, Typeable)
830831
831832
@@ -1432,16 +1433,16 @@ pprintPTerm ppo bnd docArgs infixes = prettySe startPrec bnd
14321433 prettySe p bnd (PRef fc n) = prettyName True (ppopt_impl ppo) bnd n
14331434 prettySe p bnd (PLam fc n ty sc) =
14341435 bracket p startPrec . group . align . hang 2 $
1435− text "\\" <> bindingOf n False <+> text "=>" <$>
1436+ text "\\" <> prettyBindingOf n False <+> text "=>" <$>
14361437 prettySe startPrec ((n, False):bnd) sc
14371438 prettySe p bnd (PLet fc n ty v sc) =
14381439 bracket p startPrec . group . align $
1439− kwd "let" <+> (group . align . hang 2 $ bindingOf n False <+> text "=" <$> prettySe startPrec bnd v) </>
1440+ kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe startPrec bnd v) </>
14401441 kwd "in" <+> (group . align . hang 2 $ prettySe startPrec ((n, False):bnd) sc)
14411442 prettySe p bnd (PPi (Exp l s _) n ty sc)
14421443 | n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs =
14431444 bracket p startPrec . group $
1444− enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe startPrec bnd ty) <+>
1445+ enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe startPrec bnd ty) <+>
14451446 st <> text "->" <$> prettySe startPrec ((n, False):bnd) sc
14461447 | otherwise =
14471448 bracket p startPrec . group $
@@ -1454,7 +1455,7 @@ pprintPTerm ppo bnd docArgs infixes = prettySe startPrec bnd
14541455 prettySe p bnd (PPi (Imp l s _ fa) n ty sc)
14551456 | ppopt_impl ppo =
14561457 bracket p startPrec $
1457− lbrace <> bindingOf n True <+> colon <+> prettySe startPrec bnd ty <> rbrace <+>
1458+ lbrace <> prettyBindingOf n True <+> colon <+> prettySe startPrec bnd ty <> rbrace <+>
14581459 st <> text "->" </> prettySe startPrec ((n, True):bnd) sc
14591460 | otherwise = prettySe startPrec ((n, True):bnd) sc
14601461 where
@@ -1611,6 +1612,14 @@ pprintPTerm ppo bnd docArgs infixes = prettySe startPrec bnd
16111612
16121613 prettySe p bnd _ = text "missing pretty-printer for term"
16131614
1615+ prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
1616+ prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
1617+ where display (UN n) = T.unpack n
1618+ display (MN _ n) = T.unpack n
1619+ -- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
1620+ display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n
1621+ display n = show n
1622+
16141623 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
16151624 prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm
16161625 prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm
@@ -1632,6 +1641,8 @@ pprintPTerm ppo bnd docArgs infixes = prettySe startPrec bnd
16321641 basename (NS n _) = basename n
16331642 basename n = n
16341643
1644+ slist' _ _ e
1645+ | containsHole e = Nothing
16351646 slist' p bnd (PApp _ (PRef _ nil) _)
16361647 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
16371648 slist' p bnd (PRef _ nil)
@@ -1901,31 +1912,35 @@ allNamesIn tm = nub $ ni [] tm
19011912 niTacImp env (TacImp _ _ scr) = ni env scr
19021913 niTacImp _ _ = []
19031914
1915+
19041916-- Return all names defined in binders in the given term
19051917boundNamesIn :: PTerm -> [Name]
1906−boundNamesIn tm = nub $ ni tm
1918+boundNamesIn tm = S.toList (ni S.empty tm)
19071919 where -- TODO THINK Added niTacImp, but is it right?
1908− ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1909− ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1910− ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1911− ni (PLam fc n ty sc) = n : (ni ty ++ ni sc)
1912− ni (PLet fc n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1913− ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc))
1914− ni (PEq _ _ _ l r) = ni l ++ ni r
1915− ni (PRewrite _ l r _) = ni l ++ ni r
1916− ni (PTyped l r) = ni l ++ ni r
1917− ni (PPair _ _ l r) = ni l ++ ni r
1918− ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1919− ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1920− ni (PAlternative a as) = concatMap (ni) as
1921− ni (PHidden tm) = ni tm
1922− ni (PUnifyLog tm) = ni tm
1923− ni (PDisamb _ tm) = ni tm
1924− ni (PNoImplicits tm) = ni tm
1925− ni _ = []
1926−
1927− niTacImp (TacImp _ _ scr) = ni scr
1928− niTacImp _ = []
1920+ ni set (PApp _ f as) = niTms (ni set f) (map getTm as)
1921+ ni set (PAppBind _ f as) = niTms (ni set f) (map getTm as)
1922+ ni set (PCase _ c os) = niTms (ni set c) (map snd os)
1923+ ni set (PLam fc n ty sc) = S.insert n $ ni (ni set ty) sc
1924+ ni set (PLet fc n ty val sc) = S.insert n $ ni (ni (ni set ty) val) sc
1925+ ni set (PPi p n ty sc) = niTacImp (S.insert n $ ni (ni set ty) sc) p
1926+ ni set (PEq _ _ _ l r) = ni (ni set l) r
1927+ ni set (PRewrite _ l r _) = ni (ni set l) r
1928+ ni set (PTyped l r) = ni (ni set l) r
1929+ ni set (PPair _ _ l r) = ni (ni set l) r
1930+ ni set (PDPair _ _ (PRef _ n) t r) = ni (ni set t) r
1931+ ni set (PDPair _ _ l t r) = ni (ni (ni set l) t) r
1932+ ni set (PAlternative a as) = niTms set as
1933+ ni set (PHidden tm) = ni set tm
1934+ ni set (PUnifyLog tm) = ni set tm
1935+ ni set (PDisamb _ tm) = ni set tm
1936+ ni set (PNoImplicits tm) = ni set tm
1937+ ni set _ = set
1938+
1939+ niTms set [] = set
1940+ niTms set (x : xs) = niTms (ni set x) xs
1941+
1942+ niTacImp set (TacImp _ _ scr) = ni set scr
1943+ niTacImp set _ = set
19291944
19301945-- Return names which are valid implicits in the given term (type).
19311946implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
src/Idris/Core/Elaborate.hs+1
@@ -759,6 +759,7 @@ try' t1 t2 proofSearch
759759 = do s <- get
760760 ps <- get_probs
761761 ulog <- getUnifyLog
762+ ivs <- get_instances
762763 case prunStateT 999999 False ps t1 s of
763764 OK ((v, _, _), s') -> do put s'
764765 return $! v
src/Idris/Core/ProofTerm.hs+1−1
@@ -112,7 +112,7 @@ refocus' (Just n) pt@(PT path env tm ups)
112112 -- First look for the hole in the proof term as-is
113113 | Just (p', env', tm') <- findHole n env tm
114114 = PT (replaceTop p' path) env' tm' ups
115− -- Next apply the updates, and look for the hole in the resulting term
115+ -- If it's not there, rebuild and look from the top
116116 | Just (p', env', tm') <- findHole n [] (rebuildTerm tm (updateSolvedPath ups path))
117117 = PT p' env' tm' []
118118 | otherwise = pt
src/Idris/Core/TT.hs+1
@@ -426,6 +426,7 @@ showCG (SN s) = showCG' s
426426 showCG' (ParentN p c) = showCG p ++ "#" ++ show c
427427 showCG' (CaseN c) = showCG c ++ "_case"
428428 showCG' (ElimN sn) = showCG sn ++ "_elim"
429+ showCG' (InstanceCtorN n) = showCG n ++ "_ictor"
429430showCG NErased = "_"
430431
431432
src/Idris/DSL.hs+2−2
@@ -108,7 +108,7 @@ expandDo dsl (PDoBlock ds)
108108 block b _ = PElabError (Msg "Invalid statement in do block")
109109
110110expandDo dsl (PIdiom fc e) = expandDo dsl $ unIdiom (dsl_apply dsl) (dsl_pure dsl) fc e
111−expandDo dsl (PRunTactics fc tm) = PRunTactics fc $ expandDo dsl tm
111+expandDo dsl (PRunElab fc tm) = PRunElab fc $ expandDo dsl tm
112112expandDo dsl t = t
113113
114114-- | Replace DSL-bound variable in a term
@@ -195,7 +195,7 @@ debind b tm = let (tm', (bs, _)) = runState (db' tm) ([], 0) in
195195 db' (PDPair fc p l t r) = do l' <- db' l
196196 r' <- db' r
197197 return (PDPair fc p l' t r')
198− db' (PRunTactics fc t) = fmap (PRunTactics fc) (db' t)
198+ db' (PRunElab fc t) = fmap (PRunElab fc) (db' t)
199199 db' t = return t
200200
201201 dbArg a = do t' <- db' (getTm a)
src/Idris/DeepSeq.hs+1−1
@@ -243,7 +243,7 @@ instance NFData PTerm where
243243 rnf (PNoImplicits x1) = rnf x1 `seq` ()
244244 rnf (PQuasiquote x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
245245 rnf (PUnquote x1) = rnf x1 `seq` ()
246− rnf (PRunTactics x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
246+ rnf (PRunElab x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
247247
248248instance (NFData t) => NFData (PTactic' t) where
249249 rnf (Intro x1) = rnf x1 `seq` ()
src/Idris/Elab/Class.hs+14−5
@@ -175,8 +175,8 @@ elabClass info syn_in doc fc constraints tn ps pDocs fds ds
175175 let lhs = PApp fc (PRef fc cfn) [pconst capp]
176176 let rhs = PResolveTC (fileFC "HACK")
177177 let ty = PPi constraint cnm c con
178− iLOG (showTmImpls ty)
179− iLOG (showTmImpls lhs ++ " = " ++ showTmImpls rhs)
178+ logLvl 2 ("Dictionary constraint: " ++ showTmImpls ty)
179+ logLvl 2 (showTmImpls lhs ++ " = " ++ showTmImpls rhs)
180180 i <- getIState
181181 let conn = case con of
182182 PRef _ n -> n
@@ -193,16 +193,16 @@ elabClass info syn_in doc fc constraints tn ps pDocs fds ds
193193 -- Generate a top level function which looks up a method in a given
194194 -- dictionary (this is inlinable, always)
195195 tfun cn c syn all (m, (doc, o, ty))
196− = do let ty' = insertConstraint c ty
196+ = do let ty' = expandMethNS syn (insertConstraint c ty)
197197 let mnames = take (length all) $ map (\x -> sMN x "meth") [0..]
198198 let capp = PApp fc (PRef fc cn) (map (pexp . PRef fc) mnames)
199199 let margs = getMArgs ty
200200 let anames = map (\x -> sMN x "arg") [0..]
201201 let lhs = PApp fc (PRef fc m) (pconst capp : lhsArgs margs anames)
202202 let rhs = PApp fc (getMeth mnames all m) (rhsArgs margs anames)
203− iLOG (showTmImpls ty')
203+ logLvl 2 ("Top level type: " ++ showTmImpls ty')
204204 iLOG (show (m, ty', capp, margs))
205− iLOG (showTmImpls lhs ++ " = " ++ showTmImpls rhs)
205+ logLvl 2 ("Definition: " ++ showTmImpls lhs ++ " = " ++ showTmImpls rhs)
206206 return [PTy doc [] syn fc o m ty',
207207 PClauses fc [Inlinable] m [PClause fc m lhs [] rhs []]]
208208
@@ -236,6 +236,15 @@ elabClass info syn_in doc fc constraints tn ps pDocs fds ds
236236 toExp ns e (PPi p n ty sc) = PPi p n ty (toExp ns e sc)
237237 toExp ns e sc = sc
238238
239+-- In a top level type for a method, expand all the method names namespaces
240+-- so that we don't have to disambiguate later
241+expandMethNS :: SyntaxInfo
242+ -> PTerm -> PTerm
243+expandMethNS syn = mapPT expand
244+ where
245+ expand (PRef fc n) | n `elem` imp_methods syn = PRef fc $ expandNS syn n
246+ expand t = t
247+
239248findDets :: Name -> [Name] -> Idris [Int]
240249findDets n ns =
241250 do i <- getIState
src/Idris/Elab/Value.hs+16−1
@@ -1,6 +1,6 @@
11{-# LANGUAGE PatternGuards #-}
22{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
3−module Idris.Elab.Value(elabVal, elabValBind, elabDocTerms) where
3+module Idris.Elab.Value(elabVal, elabValBind, elabDocTerms, elabExec) where
44
55import Idris.AbsSyntax
66import Idris.ASTUtils
@@ -114,3 +114,18 @@ elabDocTerms info str = do typechecked <- Traversable.mapM decorate str
114114 then Example tm
115115 else Checked tm
116116 | otherwise = Unchecked
117+
118+-- Try running the term directly (as IO ()), then printing it as an Integer
119+-- (as a default numeric tye), then printing it as any Showable thing
120+elabExec :: FC -> PTerm -> PTerm
121+elabExec fc tm = runtm (PAlternative False
122+ [printtm (PApp fc (PRef fc (sUN "the"))
123+ [pexp (PConstant (AType (ATInt ITBig))), pexp tm]),
124+ tm,
125+ printtm tm
126+ ])
127+ where
128+ runtm t = PApp fc (PRef fc (sUN "run__IO")) [pexp t]
129+ printtm t = PApp fc (PRef fc (sUN "printLn"))
130+ [pimp (sUN "ffi") (PRef fc (sUN "FFI_C")) False, pexp t]
131+
src/Idris/ElabQuasiquote.hs+2−2
@@ -170,8 +170,8 @@ extractUnquotes n (PUnquote tm)
170170 return (PRef (fileFC "(unquote)") n, [(n, tm)])
171171 | otherwise = fmap (\(tm', ex) -> (PUnquote tm', ex)) $
172172 extractUnquotes (n-1) tm
173−extractUnquotes n (PRunTactics fc tm)
174− = fmap (\(tm', ex) -> (PRunTactics fc tm', ex)) $ extractUnquotes n tm
173+extractUnquotes n (PRunElab fc tm)
174+ = fmap (\(tm', ex) -> (PRunElab fc tm', ex)) $ extractUnquotes n tm
175175extractUnquotes n x = return (x, []) -- no subterms!
176176
177177
src/Idris/ElabTerm.hs+38−16
@@ -62,6 +62,11 @@ processTacticDecls info =
6262 addIBC (IBCDef n)
6363 let ds' = map (\(n, (i, top, t)) -> (n, (i, top, t, True))) ds
6464 addDeferred ds'
65+ RClausesInstrs n cs ->
66+ do logLvl 3 $ "Pattern-matching definition from tactics: " ++ show n
67+ solveDeferred n
68+ updateIState $ \i -> i { idris_patdefs = addDef n (cs, []) $ idris_patdefs i } -- TODO: missing clauses
69+ addIBC (IBCDef n)
6570
6671-- Using the elaborator, convert a term in raw syntax to a fully
6772-- elaborated, typechecked term.
@@ -215,7 +220,7 @@ goal_polymorphic =
215220
216221-- | Returns the set of declarations we need to add to complete the
217222-- definition (most likely case blocks to elaborate) as well as
218−-- declarations resulting from user tactic scripts (%runTactics)
223+-- declarations resulting from user tactic scripts (%runElab)
219224elab :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
220225 ElabD ()
221226elab ist info emode opts fn tm
@@ -1102,11 +1107,11 @@ elab ist info emode opts fn tm
11021107 delayElab $ do focus h
11031108 dotterm
11041109 elab' ina fc t
1105− elab' ina fc (PRunTactics fc' tm) =
1110+ elab' ina fc (PRunElab fc' tm) =
11061111 do attack
11071112 n <- getNameFrom (sMN 0 "tacticScript")
11081113 n' <- getNameFrom (sMN 0 "tacticExpr")
1109− let scriptTy = RApp (Var (sNS (sUN "Tactical") ["Tactical", "Reflection", "Language"])) (Var unitTy)
1114+ let scriptTy = RApp (Var (sNS (sUN "Elab") ["Elab", "Reflection", "Language"])) (Var unitTy)
11101115 claim n scriptTy
11111116 movelast n
11121117 letbind n' scriptTy (Var n)
@@ -1585,7 +1590,7 @@ case_ ind autoSolve ist fn tm = do
15851590 when autoSolve solveAll
15861591
15871592tacN :: String -> Name
1588−tacN str = sNS (sUN str) ["Tactical", "Reflection", "Language"]
1593+tacN str = sNS (sUN str) ["Elab", "Reflection", "Language"]
15891594
15901595runTactical :: FC -> Env -> Term -> ElabD ()
15911596runTactical fc env tm = do tm' <- eval tm
@@ -1597,28 +1602,43 @@ runTactical fc env tm = do tm' <- eval tm
15971602
15981603 returnUnit = fmap fst $ get_type_val (Var unitCon)
15991604
1605+ patvars :: [Name] -> Term -> ([Name], Term)
1606+ patvars ns (Bind n (PVar t) sc) = patvars (n : ns) (instantiate (P Bound n t) sc)
1607+ patvars ns tm = (ns, tm)
1608+
1609+ pullVars :: (Term, Term) -> ([Name], Term, Term)
1610+ pullVars (lhs, rhs) = (fst (patvars [] lhs), snd (patvars [] lhs), snd (patvars [] rhs)) -- TODO alpha-convert rhs
1611+
16001612 defineFunction :: RFunDefn -> ElabD ()
16011613 defineFunction (RDefineFun n clauses) =
16021614 do ctxt <- get_context
16031615 ty <- maybe (fail "no type decl") return $ lookupTyExact n ctxt
16041616 let info = CaseInfo True True False -- TODO document and figure out
1605− clauses' <- forM clauses (\(RMkFunClause lhs rhs) ->
1606− do lhs' <- lift $ check ctxt [] lhs
1607− rhs' <- lift $ check ctxt [] rhs
1608− return (fst lhs', fst rhs'))
1609− trace (show clauses') $ return ()
1617+ clauses' <- forM clauses (\case
1618+ RMkFunClause lhs rhs ->
1619+ do lhs' <- fmap fst . lift $ check ctxt [] lhs
1620+ rhs' <- fmap fst . lift $ check ctxt [] rhs
1621+ return $ Right (lhs', rhs')
1622+ RMkImpossibleClause lhs ->
1623+ do lhs' <- fmap fst . lift $ check ctxt [] lhs
1624+ return $ Left lhs')
1625+ let clauses'' = map (\case Right c -> pullVars c
1626+ Left lhs -> let (ns, lhs') = patvars [] lhs'
1627+ in (ns, lhs', Impossible))
1628+ clauses'
16101629 set_context $
16111630 addCasedef n (const [])
16121631 info False (STerm Erased)
16131632 True False -- TODO what are these?
16141633 [] [] -- TODO argument types, inaccessible types
1615− (map Right clauses')
1616− (map (\(l,r) -> ([], l, r)) clauses')
1617− (map (\(l,r) -> ([], l, r)) clauses')
1618− (map (\(l,r) -> ([], l, r)) clauses')
1619− (map (\(l,r) -> ([], l, r)) clauses')
1634+ clauses'
1635+ clauses''
1636+ clauses''
1637+ clauses''
1638+ clauses''
16201639 ty
16211640 ctxt
1641+ updateAux $ \e -> e { new_tyDecls = RClausesInstrs n clauses'' : new_tyDecls e}
16221642 return ()
16231643
16241644 -- | Do a step in the reflected elaborator monad. The input is the
@@ -1659,9 +1679,9 @@ runTactical fc env tm = do tm' <- eval tm
16591679 = do errs' <- eval errs
16601680 parts <- reifyReportParts errs'
16611681 lift . tfail $ ReflectionError [parts] (Msg "")
1662− | n == tacN "prim__PureTactical", [_a, tm] <- args
1682+ | n == tacN "prim__PureElab", [_a, tm] <- args
16631683 = return tm
1664− | n == tacN "prim__BindTactical", [_a, _b, first, andThen] <- args
1684+ | n == tacN "prim__BindElab", [_a, _b, first, andThen] <- args
16651685 = do first' <- eval first
16661686 res <- runTacTm first'
16671687 next <- eval (App andThen res)
@@ -2916,6 +2936,8 @@ reifyFunDefn (App (App (P _ n _) fnN) clauses)
29162936 | n == tacN "MkFunClause" = liftM2 RMkFunClause
29172937 (reifyRaw lhs)
29182938 (reifyRaw rhs)
2939+ reifyC (App (P (DCon _ _ _) n _) lhs)
2940+ | n == tacN "MkImpossibleClause" = fmap RMkImpossibleClause $ reifyRaw lhs
29192941 reifyC tm = fail $ "Couldn't reify " ++ show tm ++ " as a clause."
29202942reifyFunDefn tm = fail $ "Couldn't reify " ++ show tm ++ " as a function declaration."
29212943
src/Idris/Erasure.hs+3−16
@@ -66,13 +66,11 @@ type Vars = Map Name VarInfo
6666-- Perform usage analysis, write the relevant information in the internal
6767-- structures, returning the list of reachable names.
6868performUsageAnalysis :: [Name] -> Idris [Name]
69−performUsageAnalysis roots = do
69+performUsageAnalysis startNames = do
7070 ctx <- tt_ctxt <$> getIState
71− startNames <- getStartNames <$> getIState
72−
7371 case startNames of
74− Left reason -> return [] -- no main -> not compiling -> reachability irrelevant
75− Right main -> do
72+ [] -> return [] -- no main -> not compiling -> reachability irrelevant
73+ main -> do
7674 ci <- idris_classes <$> getIState
7775 cg <- idris_callgraph <$> getIState
7876 opt <- idris_optimisation <$> getIState
@@ -107,17 +105,6 @@ performUsageAnalysis roots = do
107105
108106 return $ S.toList reachableNames
109107 where
110− getStartNames :: IState -> Either Err [Name]
111− getStartNames ist
112− = case lookupCtxtName n (idris_implicits ist) of
113− [(n', _)] -> Right (n' : roots)
114− [] -> if null roots
115− then Left (NoSuchVariable n)
116− else Right roots
117− more -> Left (CantResolveAlts (map fst more))
118− where
119− n = sNS (sUN "main") ["Main"]
120−
121108 indent = (" " ++)
122109
123110 fmtItem :: (Cond, DepSet) -> String
src/Idris/Error.hs+1−1
@@ -148,4 +148,4 @@ warnDisamb ist (PQuasiquote tm goal) = warnDisamb ist tm >>
148148warnDisamb ist (PUnquote tm) = warnDisamb ist tm
149149warnDisamb ist (PAs _ _ tm) = warnDisamb ist tm
150150warnDisamb ist (PAppImpl tm _) = warnDisamb ist tm
151−warnDisamb ist (PRunTactics _ tm) = warnDisamb ist tm
151+warnDisamb ist (PRunElab _ tm) = warnDisamb ist tm
src/Idris/IBC.hs+4−4
@@ -1674,9 +1674,9 @@ instance Binary PTerm where
16741674 put x2
16751675 PUniverse x1 -> do putWord8 38
16761676 put x1
1677− PRunTactics x1 x2 -> do putWord8 39
1678− put x1
1679− put x2
1677+ PRunElab x1 x2 -> do putWord8 39
1678+ put x1
1679+ put x2
16801680 PAs x1 x2 x3 -> do putWord8 40
16811681 put x1
16821682 put x2
@@ -1809,7 +1809,7 @@ instance Binary PTerm where
18091809 return (PUniverse x1)
18101810 39 -> do x1 <- get
18111811 x2 <- get
1812− return (PRunTactics x1 x2)
1812+ return (PRunElab x1 x2)
18131813 40 -> do x1 <- get
18141814 x2 <- get
18151815 x3 <- get
src/Idris/IdrisDoc.hs+3−3
@@ -321,7 +321,7 @@ extractPTermNames (PCoerced p) = extract p
321321extractPTermNames (PDisamb _ p) = extract p
322322extractPTermNames (PUnifyLog p) = extract p
323323extractPTermNames (PNoImplicits p) = extract p
324−extractPTermNames (PRunTactics _ p) = extract p
324+extractPTermNames (PRunElab _ p) = extract p
325325extractPTermNames _ = []
326326
327327-- | Shorter name for extractPTermNames
@@ -420,7 +420,7 @@ createIndex nss out =
420420 BS2.hPut h $ renderHtml $ wrapper Nothing $ do
421421 H.h1 $ "Namespaces"
422422 H.ul ! class_ "names" $ do
423− let path ns = "docs" </> genRelNsPath ns "html"
423+ let path ns = "docs" ++ "/" ++ genRelNsPath ns "html"
424424 item ns = do let n = toHtml $ nsName2Str ns
425425 link = toValue $ path ns
426426 H.li $ H.a ! href link ! class_ "code" $ n
@@ -663,7 +663,7 @@ existingNamespaces :: FilePath -- ^ The base directory containing the
663663 -- namespace pages
664664 -> IO (S.Set NsName)
665665existingNamespaces out = do
666− let docs = out </> "docs"
666+ let docs = out ++ "/" ++ "docs"
667667 str2Ns s | s == rootNsStr = []
668668 str2Ns s = reverse $ T.splitOn (T.singleton '.') (txt s)
669669 toNs fp = do isFile <- doesFileExist $ docs </> fp
src/Idris/ParseExpr.hs+67−50
@@ -1,5 +1,4 @@
11{-# LANGUAGE GeneralizedNewtypeDeriving, ConstraintKinds, PatternGuards #-}
2−{-# OPTIONS_GHC -O0 #-}
32module Idris.ParseExpr where
43
54import Prelude hiding (pi)
@@ -221,7 +220,7 @@ InternalExpr ::=
221220internalExpr :: SyntaxInfo -> IdrisParser PTerm
222221internalExpr syn =
223222 unifyLog syn
224− <|> runTactics syn
223+ <|> runElab syn
225224 <|> disamb syn
226225 <|> noImplicits syn
227226 <|> recordType syn
@@ -498,16 +497,16 @@ unifyLog syn = do try (lchar '%' *> reserved "unifyLog")
498497
499498{- | Parses a new-style tactics expression
500499RunTactics ::=
501− '%' 'runTactics' SimpleExpr
500+ '%' 'runElab' SimpleExpr
502501 ;
503502-}
504−runTactics :: SyntaxInfo -> IdrisParser PTerm
505−runTactics syn = do try (lchar '%' *> reserved "runTactics")
506− fc <- getFC
507− tm <- simpleExpr syn
508− i <- get
509− return $ PRunTactics fc tm
510− <?> "new-style tactics expression"
503+runElab :: SyntaxInfo -> IdrisParser PTerm
504+runElab syn = do try (lchar '%' *> reserved "runElab")
505+ fc <- getFC
506+ tm <- simpleExpr syn
507+ i <- get
508+ return $ PRunElab fc tm
509+ <?> "new-style tactics expression"
511510
512511{- | Parses a disambiguation expression
513512Disamb ::=
@@ -869,49 +868,67 @@ bindsymbol opts st syn
869868 = do symbol "->"
870869 return (Exp opts st False)
871870
871+explicitPi opts st syn
872+ = do xt <- try (lchar '(' *> typeDeclList syn <* lchar ')')
873+ binder <- bindsymbol opts st syn
874+ sc <- expr syn
875+ return (bindList (PPi binder) xt sc)
876+
877+autoImplicit opts st syn
878+ = do reserved "auto"
879+ when (st == Static) $ fail "auto implicits can not be static"
880+ xt <- typeDeclList syn
881+ lchar '}'
882+ symbol "->"
883+ sc <- expr syn
884+ return (bindList (PPi
885+ (TacImp [] Dynamic (PTactics [ProofSearch True True 100 Nothing []]))) xt sc)
886+
887+defaultImplicit opts st syn = do
888+ reserved "default"
889+ when (st == Static) $ fail "default implicits can not be static"
890+ ist <- get
891+ script' <- simpleExpr syn
892+ let script = debindApp syn . desugar syn ist $ script'
893+ xt <- typeDeclList syn
894+ lchar '}'
895+ symbol "->"
896+ sc <- expr syn
897+ return (bindList (PPi (TacImp [] Dynamic script)) xt sc)
898+
899+normalImplicit opts st syn = do
900+ xt <- typeDeclList syn <* lchar '}'
901+ symbol "->"
902+ cs <- constraintList syn
903+ sc <- expr syn
904+ let (im,cl)
905+ = if implicitAllowed syn
906+ then (Imp opts st False Nothing,
907+ constraint)
908+ else (Imp opts st False (Just (Impl False)),
909+ Imp opts st False (Just (Impl True)))
910+ return (bindList (PPi im) xt
911+ (bindList (PPi cl) cs sc))
912+
913+implicitPi opts st syn =
914+ autoImplicit opts st syn
915+ <|> defaultImplicit opts st syn
916+ <|> normalImplicit opts st syn
917+
918+unboundPi opts st syn = do
919+ x <- opExpr syn
920+ (do binder <- bindsymbol opts st syn
921+ sc <- expr syn
922+ return (PPi binder (sUN "__pi_arg") x sc))
923+ <|> return x
924+
872925pi :: SyntaxInfo -> IdrisParser PTerm
873926pi syn =
874927 do opts <- piOpts syn
875928 st <- static
876− (do xt <- try (lchar '(' *> typeDeclList syn <* lchar ')')
877− binder <- bindsymbol opts st syn
878− sc <- expr syn
879− return (bindList (PPi binder) xt sc)) <|> (do
880− (do try (lchar '{' *> reserved "auto")
881− when (st == Static) $ fail "auto type constraints can not be static"
882− xt <- typeDeclList syn
883− lchar '}'
884− symbol "->"
885− sc <- expr syn
886− return (bindList (PPi
887− (TacImp [] Dynamic (PTactics [ProofSearch True True 100 Nothing []]))) xt sc)) <|> (do
888− try (lchar '{' *> reserved "default")
889− when (st == Static) $ fail "default tactic constraints can not be static"
890− ist <- get
891− script' <- simpleExpr syn
892− let script = debindApp syn . desugar syn ist $ script'
893− xt <- typeDeclList syn
894− lchar '}'
895− symbol "->"
896− sc <- expr syn
897− return (bindList (PPi (TacImp [] Dynamic script)) xt sc))
898− <|> (do xt <- try (lchar '{' *> typeDeclList syn <* lchar '}')
899− symbol "->"
900− cs <- constraintList syn
901− sc <- expr syn
902− let (im,cl)
903− = if implicitAllowed syn
904− then (Imp opts st False Nothing,
905− constraint)
906− else (Imp opts st False (Just (Impl False)),
907− Imp opts st False (Just (Impl True)))
908− return (bindList (PPi im) xt
909− (bindList (PPi cl) cs sc))))
910− <|> (do x <- opExpr syn
911− (do binder <- bindsymbol opts st syn
912− sc <- expr syn
913− return (PPi binder (sUN "__pi_arg") x sc))
914− <|> return x)
929+ explicitPi opts st syn
930+ <|> try (do lchar '{'; implicitPi opts st syn)
931+ <|> unboundPi opts st syn
915932 <?> "dependent type signature"
916933
917934{- | Parses Possible Options for Pi Expressions
@@ -944,7 +961,7 @@ constraintList1 syn = try (do lchar '('
944961 lchar ')'
945962 reservedOp "=>"
946963 return tys)
947− <|> try (do t <- expr (disallowImp syn)
964+ <|> try (do t <- opExpr (disallowImp syn)
948965 reservedOp "=>"
949966 return [(defname, t)])
950967 <?> "type constraint list"
src/Idris/Parser.hs+1−1
@@ -1365,7 +1365,7 @@ loadSource lidr f toline
13651365 -- process and check module aliases
13661366 let modAliases = M.fromList
13671367 [(prep alias, prep realName) | (reexport, realName, Just alias, fc) <- imports]
1368− prep = map T.pack . reverse . Spl.splitOn "/"
1368+ prep = map T.pack . reverse . Spl.splitOn [pathSeparator]
13691369 aliasNames = [(alias, fc) | (_, _, Just alias, fc) <- imports]
13701370 histogram = groupBy ((==) `on` fst) . sortBy (comparing fst) $ aliasNames
13711371 case map head . filter ((/= 1) . length) $ histogram of
src/Idris/ProofSearch.hs+36−23
@@ -15,6 +15,7 @@ import Idris.Error
1515import Control.Applicative ((<$>))
1616import Control.Monad
1717import Control.Monad.State.Strict
18+import qualified Data.Set as S
1819import Data.List
1920import Debug.Trace
2021
@@ -91,7 +92,7 @@ proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot hints ist
9192 if ambigok || argsok then
9293 case lookupCtxt nroot (idris_tyinfodata ist) of
9394 [TISolution ts] -> findInferredTy ts
94− _ -> psRec rec maxDepth []
95+ _ -> psRec rec maxDepth [] S.empty
9596 else autoArg (sUN "auto") -- not enough info in the type yet
9697 where
9798 findInferredTy (t : _) = elab (delab ist (toUN t))
@@ -134,13 +135,21 @@ proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot hints ist
134135 -- (so we don't try a pointless application of something to itself,
135136 -- which obviously won't work anyway but might lead us on a wild
136137 -- goose chase...)
137− psRec _ 0 locs | fromProver = cantSolveGoal
138− psRec rec 0 locs = do attack; defer [] nroot; solve --fail "Maximum depth reached"
139− psRec False d locs = tryCons d locs hints
140− psRec True d locs
138+ -- Also keep track of the types we've proved so far in this branch
139+ -- (if we get back to one we've been to before, we're just in a cycle and
140+ -- that's no use)
141+ psRec :: Bool -> Int -> [Name] -> S.Set Type -> ElabD ()
142+ psRec _ 0 locs tys | fromProver = cantSolveGoal
143+ psRec rec 0 locs tys = do attack; defer [] nroot; solve --fail "Maximum depth reached"
144+ psRec False d locs tys = tryCons d locs tys hints
145+ psRec True d locs tys
141146 = do compute
147+ ty <- goal
148+ when (S.member ty tys) $ fail "Been here before"
149+ let tys' = S.insert ty tys
142150 try' (trivial elab ist)
143− (try' (try' (resolveByCon (d - 1) locs) (resolveByLocals (d - 1) locs)
151+ (try' (try' (resolveByCon (d - 1) locs tys')
152+ (resolveByLocals (d - 1) locs tys')
144153 True)
145154 -- if all else fails, make a new metavariable
146155 (if fromProver
@@ -151,7 +160,7 @@ proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot hints ist
151160 getFn d (Just f) | d < maxDepth-1 = [f]
152161 | otherwise = []
153162
154− resolveByCon d locs
163+ resolveByCon d locs tys
155164 = do t <- goal
156165 let (f, _) = unApply t
157166 case f of
@@ -160,7 +169,8 @@ proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot hints ist
160169 Nothing -> []
161170 Just hs -> hs
162171 case lookupCtxtExact n (idris_datatypes ist) of
163− Just t -> tryCons d locs (hints ++
172+ Just t -> tryCons d locs tys
173+ (hints ++
164174 con_names t ++
165175 autohints ++
166176 getFn d fn)
@@ -169,28 +179,31 @@ proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot hints ist
169179
170180 -- if there are local variables which have a function type, try
171181 -- applying them too
172− resolveByLocals d locs
182+ resolveByLocals d locs tys
173183 = do env <- get_env
174− tryLocals d locs env
184+ tryLocals d locs tys env
175185
176− tryLocals d locs [] = fail "Locals failed"
177− tryLocals d locs ((x, t) : xs)
178− | x `elem` locs = tryLocals d locs xs
179− | otherwise = try' (tryLocal d (x : locs) x t) (tryLocals d locs xs) True
186+ tryLocals d locs tys [] = fail "Locals failed"
187+ tryLocals d locs tys ((x, t) : xs)
188+ | x `elem` locs = tryLocals d locs tys xs
189+ | otherwise = try' (tryLocal d (x : locs) tys x t)
190+ (tryLocals d locs tys xs) True
180191
181− tryCons d locs [] = fail "Constructors failed"
182− tryCons d locs (c : cs) = try' (tryCon d locs c) (tryCons d locs cs) True
192+ tryCons d locs tys [] = fail "Constructors failed"
193+ tryCons d locs tys (c : cs)
194+ = try' (tryCon d locs tys c) (tryCons d locs tys cs) True
183195
184− tryLocal d locs n t
196+ tryLocal d locs tys n t
185197 = do let a = getPArity (delab ist (binderTy t))
186− tryLocalArg d locs n a
198+ tryLocalArg d locs tys n a
187199
188− tryLocalArg d locs n 0 = elab (PRef (fileFC "prf") n)
189− tryLocalArg d locs n i = simple_app False (tryLocalArg d locs n (i - 1))
190− (psRec True d locs) "proof search local apply"
200+ tryLocalArg d locs tys n 0 = elab (PRef (fileFC "prf") n)
201+ tryLocalArg d locs tys n i
202+ = simple_app False (tryLocalArg d locs tys n (i - 1))
203+ (psRec True d locs tys) "proof search local apply"
191204
192205 -- Like type class resolution, but searching with constructors
193− tryCon d locs n =
206+ tryCon d locs tys n =
194207 do ty <- goal
195208 let imps = case lookupCtxtExact n (idris_implicits ist) of
196209 Nothing -> []
@@ -204,7 +217,7 @@ proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot hints ist
204217 when (length ps < length ps') $ fail "Can't apply constructor"
205218 mapM_ (\ (_, h) -> do focus h
206219 aty <- goal
207− psRec True d locs)
220+ psRec True d locs tys)
208221 (filter (\ (x, y) -> not x) (zip (map fst imps) args))
209222 solve
210223
src/Idris/REPL.hs+9−11
@@ -582,8 +582,8 @@ idemodeProcess fn (HNF t) = process fn (HNF t)
582582--idemodeProcess fn TTShell = process fn TTShell -- need some prove mode!
583583idemodeProcess fn (TestInline t) = process fn (TestInline t)
584584
585−idemodeProcess fn Execute = do process fn Execute
586− iPrintResult ""
585+idemodeProcess fn (Execute t) = do process fn (Execute t)
586+ iPrintResult ""
587587idemodeProcess fn (Compile codegen f) = do process fn (Compile codegen f)
588588 iPrintResult ""
589589idemodeProcess fn (LogLvl i) = do process fn (LogLvl i)
@@ -1115,13 +1115,10 @@ process fn (TestInline t)
11151115 let tm' = inlineTerm ist tm
11161116 c <- colourise
11171117 iPrintResult (showTm ist (delab ist tm'))
1118−process fn Execute
1118+process fn (Execute tm)
11191119 = idrisCatch
11201120 (do ist <- getIState
1121− (m, _) <- elabVal recinfo ERHS
1122− (PApp fc
1123− (PRef fc (sUN "run__IO"))
1124− [pexp $ PRef fc (sNS (sUN "main") ["Main"])])
1121+ (m, _) <- elabVal recinfo ERHS (elabExec fc tm)
11251122 (tmpn, tmph) <- runIO tempfile
11261123 runIO $ hClose tmph
11271124 t <- codegen
@@ -1232,10 +1229,11 @@ process fn (Apropos pkgs a) =
12321229 delabTy ist n,
12331230 fmap (overview . fst) (lookupCtxtExact n (idris_docstrings ist)))
12341231 | n <- sort names, isUN n ]
1235− iRenderResult $ vsep (map (\(m, d) -> text "Module" <+> text m <$>
1236− ppD ist d <> line) mods) <$>
1237− vsep (map (prettyDocumentedIst ist) aproposInfo)
1238− putIState orig
1232+ if (not (null mods)) || (not (null aproposInfo))
1233+ then iRenderResult $ vsep (map (\(m, d) -> text "Module" <+> text m <$>
1234+ ppD ist d <> line) mods) <$>
1235+ vsep (map (prettyDocumentedIst ist) aproposInfo)
1236+ else iRenderError $ text "No results found"
12391237 where isUN (UN _) = True
12401238 isUN (NS n _) = isUN n
12411239 isUN _ = False
src/Idris/REPLParser.hs+9−1
@@ -71,7 +71,7 @@ parserCommandsForHelp =
7171 , noArgCmd ["proofs"] Proofs "Show available proofs"
7272 , exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter"
7373 , (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile)
74− , noArgCmd ["exec", "execute"] Execute "Compile to an executable and run"
74+ , (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute)
7575 , (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic)
7676 , (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic)
7777 , noArgCmd ["?", "h", "help"] Help "Display this help text"
@@ -276,6 +276,14 @@ cmd_consolewidth name = do
276276 <|> do discard (P.symbol "infinite"); return InfinitelyWide
277277 <|> do n <- fmap fromInteger P.natural; return (ColsWide n)
278278
279+cmd_execute :: String -> P.IdrisParser (Either String Command)
280+cmd_execute name = do
281+ tm <- option maintm (P.fullExpr defaultSyntax)
282+ return (Right (Execute tm))
283+ where
284+ maintm = PRef (fileFC "(repl)") (sNS (sUN "main") ["Main"])
285+
286+
279287cmd_dynamic :: String -> P.IdrisParser (Either String Command)
280288cmd_dynamic name = do
281289 let emptyArgs = noArgs ListDynamic name
src/Idris/Reflection.hs+3−1
@@ -17,6 +17,8 @@ rArgToPArg (RExplicit n _) = PExp 0 [] n Placeholder
1717rArgToPArg (RImplicit n _) = PImp 0 False [] n Placeholder
1818rArgToPArg (RConstraint n _) = PConstraint 0 [] n Placeholder
1919
20−data RFunClause = RMkFunClause Raw Raw deriving Show
20+data RFunClause = RMkFunClause Raw Raw
21+ | RMkImpossibleClause Raw
22+ deriving Show
2123
2224data RFunDefn = RDefineFun Name [RFunClause] deriving Show
src/Idris/TypeSearch.hs+7−5
@@ -30,7 +30,7 @@ import Idris.Core.Unify (match_unify)
3030import Idris.Delaborate (delabTy)
3131import Idris.Docstrings (noDocs, overview)
3232import Idris.Elab.Type (elabType)
33−import Idris.Output (iputStrLn, iRenderOutput, iPrintResult, iRenderResult, prettyDocumentedIst)
33+import Idris.Output (iputStrLn, iRenderOutput, iPrintResult, iRenderError, iRenderResult, prettyDocumentedIst)
3434import Idris.IBC
3535
3636import Prelude hiding (pred)
@@ -54,10 +54,12 @@ searchByType pkgs pterm = do
5454 [ let docInfo = (n, delabTy i n, fmap (overview . fst) (lookupCtxtExact n (idris_docstrings i))) in
5555 displayScore theScore <> char ' ' <> prettyDocumentedIst i docInfo
5656 | (n, theScore) <- names']
57− case idris_outputmode i of
58− RawOutput _ -> do mapM_ iRenderOutput docs
59− iPrintResult ""
60− IdeMode _ _ -> iRenderResult (vsep docs)
57+ if (not (null docs))
58+ then case idris_outputmode i of
59+ RawOutput _ -> do mapM_ iRenderOutput docs
60+ iPrintResult ""
61+ IdeMode _ _ -> iRenderResult (vsep docs)
62+ else iRenderError $ text "No results found"
6163 putIState i -- don't actually make any changes
6264 where
6365 numLimit = 50
src/Util/System.hs+30−2
@@ -1,5 +1,6 @@
1+{-# LANGUAGE CPP #-}
12module Util.System(tempfile,withTempdir,rmFile,catchIO, isWindows,
2− readSource, writeSource) where
3+ writeSource, readSource, setupBundledCC) where
34
45-- System helper functions.
56import Control.Monad (when)
@@ -7,13 +8,19 @@ import System.Directory (getTemporaryDirectory
78 , removeFile
89 , removeDirectoryRecursive
910 , createDirectoryIfMissing
11+ , doesDirectoryExist
1012 )
11−import System.FilePath ((</>), normalise)
13+import System.FilePath ((</>), normalise, isAbsolute, dropFileName)
1214import System.IO
1315import System.Info
1416import System.IO.Error
1517import Control.Exception as CE
1618
19+#ifdef FREESTANDING
20+import Tools_idris
21+import System.Environment (getEnv, setEnv, getExecutablePath)
22+#endif
23+
1724catchIO :: IO a -> (IOError -> IO a) -> IO a
1825catchIO = CE.catch
1926
@@ -54,3 +61,24 @@ rmFile f = do putStrLn $ "Removing " ++ f
5461 catchIO (removeFile f)
5562 (\ioerr -> putStrLn $ "WARNING: Cannot remove file "
5663 ++ f ++ ", Error msg:" ++ show ioerr)
64+
65+setupBundledCC :: IO()
66+#ifdef FREESTANDING
67+setupBundledCC = when hasBundledToolchain
68+ $ do
69+ exePath <- getExecutablePath
70+ path <- getEnv "PATH"
71+ tcDir <- return getToolchainDir
72+ absolute <- return $ isAbsolute tcDir
73+ target <- return $
74+ if absolute
75+ then tcDir
76+ else dropFileName exePath ++ tcDir
77+ let pathSep = if isWindows then ";" else ":"
78+ present <- doesDirectoryExist target
79+ when present
80+ $ do newPath <- return $ target ++ pathSep ++ path
81+ setEnv "PATH" newPath
82+#else
83+setupBundledCC = return ()
84+#endif
test/Makefile+1−1
@@ -8,7 +8,7 @@ test: $(TESTS)
88 @perl ./runtest.pl $(patsubst %.test,%,$@)
99
1010test_js:
11− @perl ./runtest.pl without sugar004 reg029 reg052 io001 dsl002 io003 effects001 effects002 effects003 buffer001 basic007 basic011 primitives004 ffi006 --codegen node
11+ @perl ./runtest.pl without sugar004 reg029 reg052 io001 dsl002 io003 effects001 effects002 effects003 effects004 buffer001 basic007 basic011 primitives004 ffi006 --codegen node
1212
1313update:
1414 /usr/bin/env perl ./runtest.pl all -u
test/basic010/Main.idr+1−1
@@ -38,6 +38,6 @@ fmt (axiom n) = "axiom " ++ show n
3838
3939main : IO ()
4040main = do
41− n <- map (const 10000) (putStrLn "*oink*")
41+ n <- map (const (the Nat 10000)) (putStrLn "*oink*")
4242 putStrLn . show $ getWitness (f 4 n)
4343 putStrLn . fmt $ getProof (g 4 n)
test/basic010/run+31−25
@@ -1,28 +1,5 @@
11#!/usr/bin/env bash
22
3−# From http://unix.stackexchange.com/questions/43340/how-to-introduce-timeout-for-shell-scripting
4−# Here copied from reg039.
5−#
6−# Executes command with a timeout
7−# Params:
8−# $1 timeout in seconds
9−# $2 command
10−# Returns 1 if timed out 0 otherwise
11−timeout() {
12−
13− time=$1
14−
15− # start the command in a subshell to avoid problem with pipes
16− # (spawn accepts one command)
17− command="/bin/sh -c \"$2\""
18−
19− expect -c "set echo \"-noecho\"; set timeout $time; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"
20−
21− if [ $? = 1 ] ; then
22− echo "Timeout after ${time} seconds"
23− fi
24−
25−}
263
274declare -a extraargs
285for arg in "$@"
@@ -30,6 +7,35 @@ do
307 extraargs=("${extraargs[@]}" "'$arg'")
318done
329
33−timeout 10 "idris ${extraargs[*]} Main.idr --nocolour --check --warnreach -o basic010"
34−timeout 5 "./basic010"
10+if (which timeout&>/dev/null); then
11+ timeout 10 idris $@ Main.idr --nocolour --check --warnreach -o basic010
12+ timeout 5 ./basic010
13+else
14+ # From http://unix.stackexchange.com/questions/43340/how-to-introduce-timeout-for-shell-scripting
15+ # Here copied from reg039.
16+ #
17+ # Executes command with a timeout
18+ # Params:
19+ # $1 timeout in seconds
20+ # $2 command
21+ # Returns 1 if timed out 0 otherwise
22+ timeout() {
23+
24+ time=$1
25+
26+ # start the command in a subshell to avoid problem with pipes
27+ # (spawn accepts one command)
28+ command="/bin/sh -c \"$2\""
29+
30+ expect -c "set echo \"-noecho\"; set timeout $time; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"
31+
32+ if [ $? = 1 ] ; then
33+ echo "Timeout after ${time} seconds"
34+ fi
35+
36+ }
37+
38+ timeout 10 "idris ${extraargs[*]} Main.idr --nocolour --check --warnreach -o basic010"
39+ timeout 5 "./basic010"
40+fi
3541rm -f *.ibc basic010
test/effects001/test021.idr+1−2
@@ -9,8 +9,7 @@ import Control.IOExcept
99data Count : Type where
1010
1111FileIO : Type -> Type -> Type
12−FileIO st t
13− = { [FILE_IO st, STDIO, Count ::: STATE Int] } Eff t
12+FileIO st t = Eff t [FILE_IO st, STDIO, Count ::: STATE Int]
1413
1514readFile : FileIO (OpenFile Read) (List String)
1615readFile = readAcc [] where
test/effects001/test021a.idr+1−1
@@ -18,7 +18,7 @@ Env = List (String, Integer)
1818-- Evaluator t
1919-- = Eff m [EXCEPTION String, RND, STATE Env] t
2020
21−eval : Expr -> { [EXCEPTION String, STDIO, RND, STATE Env] } Eff Integer
21+eval : Expr -> Eff Integer [EXCEPTION String, STDIO, RND, STATE Env]
2222eval (Var x) = do vs <- get
2323 case lookup x vs of
2424 Nothing => raise ("No such variable " ++ x)
test/effects002/test025.idr+2−2
@@ -6,8 +6,8 @@ import Control.IOExcept
66import Data.Vect
77
88MemoryIO : Type -> Type -> Type -> Type
9−MemoryIO td ts r = { [ Dst ::: RAW_MEMORY td
10− , Src ::: RAW_MEMORY ts ] } Eff r
9+MemoryIO td ts r = Eff r [Dst ::: RAW_MEMORY td,
10+ Src ::: RAW_MEMORY ts]
1111
1212inpVect : Vect 5 Bits8
1313inpVect = map prim__truncInt_B8 [0, 1, 2, 3, 5]
test/effects003/hangman.idr+28−26
@@ -74,55 +74,59 @@ data HangmanRules : Effect where
7474-- the number of missing letters, if not, reduce the number of guesses left
7575
7676 Guess : (x : Char) ->
77− { Hangman (Running (S g) (S w)) ==>
78− {inword} (case inword of
77+ sig HangmanRules Bool
78+ (Hangman (Running (S g) (S w)))
79+ (\inword =>
80+ case inword of
7981 True => Hangman (Running (S g) w)
80− False => Hangman (Running g (S w))) }
81− HangmanRules Bool
82+ False => Hangman (Running g (S w)))
8283
8384-- The 'Won' operation requires that there are no missing letters
8485
85− Won : { Hangman (Running g 0) ==> Hangman NotRunning } HangmanRules ()
86+ Won : sig HangmanRules ()
87+ (Hangman (Running g 0))
88+ (Hangman NotRunning)
8689
8790-- The 'Lost' operation requires that there are no guesses left
8891
89− Lost : { Hangman (Running 0 g) ==> Hangman NotRunning } HangmanRules ()
92+ Lost : sig HangmanRules ()
93+ (Hangman (Running 0 g))
94+ (Hangman NotRunning)
9095
9196-- Set up a new game, initialised with 6 guesses and the missing letters in
9297-- the given word. Note that if there are no letters in the word, we won't
9398-- be able to run 'Guess'!
9499
95100 NewWord : (w : String) ->
96− { h ==> Hangman (Running 6 (length (letters w))) } HangmanRules ()
101+ sig HangmanRules () h (Hangman (Running 6 (length (letters w))))
97102
98103-- Finally, allow us to get the current game state
99104
100− Get : { h } HangmanRules h
105+ Get : sig HangmanRules h h
101106
102107HANGMAN : HState -> EFFECT
103108HANGMAN h = MkEff (Hangman h) HangmanRules
104109
105110-- Promote explicit effecst to Eff programs
106111
107−guess : Char ->
108− { [HANGMAN (Running (S g) (S w))] ==>
109− {inword} [HANGMAN (case inword of
110− True => Running (S g) w
111− False => Running g (S w))] } Eff Bool
112+guess : Char -> Eff Bool
113+ [HANGMAN (Running (S g) (S w))]
114+ (\inword => [HANGMAN (case inword of
115+ True => Running (S g) w
116+ False => Running g (S w))])
112117guess c = call (Main.Guess c)
113118
114−won : { [HANGMAN (Running g 0)] ==> [HANGMAN NotRunning]} Eff ()
119+won : Eff () [HANGMAN (Running g 0)] [HANGMAN NotRunning]
115120won = call Won
116121
117−lost : { [HANGMAN (Running 0 g)] ==> [HANGMAN NotRunning]} Eff ()
122+lost : Eff () [HANGMAN (Running 0 g)] [HANGMAN NotRunning]
118123lost = call Lost
119124
120−new_word : (w : String) ->
121− { [HANGMAN h] ==>
122− [HANGMAN (Running 6 (length (letters w)))]} Eff ()
125+new_word : (w : String) -> Eff () [HANGMAN h]
126+ [HANGMAN (Running 6 (length (letters w)))]
123127new_word w = call (NewWord w)
124128
125−get : { [HANGMAN h] } Eff (Hangman h)
129+get : Eff (Hangman h) [HANGMAN h]
126130get = call Get
127131
128132-----------------------------------------------------------------------
@@ -163,8 +167,8 @@ were valid letters in it!
163167soRefl : So x -> (x = True)
164168soRefl Oh = Refl
165169
166−game : { [HANGMAN (Running (S g) w), STDIO] ==>
167− [HANGMAN NotRunning, STDIO] } Eff ()
170+game : Eff () [HANGMAN (Running (S g) w), STDIO]
171+ [HANGMAN NotRunning, STDIO]
168172game {w=Z} = won
169173game {w=S _}
170174 = do putStrLn (show !get)
@@ -175,10 +179,8 @@ game {w=S _}
175179 (Right p) => do putStrLn "Invalid input!"
176180 game
177181 where
178− processGuess : -- {g,w:_} ->
179− Char -> { [HANGMAN (Running (S g) (S w)), STDIO] ==>
180− [HANGMAN NotRunning, STDIO] }
181− Eff ()
182+ processGuess : Char -> Eff () [HANGMAN (Running (S g) (S w)), STDIO]
183+ [HANGMAN NotRunning, STDIO]
182184 processGuess {g} c {w}
183185 = case !(guess c) of
184186 True => do putStrLn "Good guess!"
@@ -203,7 +205,7 @@ wlen = proof search
203205
204206{- It typechecks! Ship it! -}
205207
206−runGame : { [HANGMAN NotRunning, RND, STDIO] } Eff ()
208+runGame : Eff () [HANGMAN NotRunning, RND, STDIO]
207209runGame = do srand 1234567890
208210 let w = index !(rndFin _) words
209211 new_word w
test/effects004/effects004.idrnew file+19
@@ -0,0 +1,19 @@
1+import Effects
2+import Effect.StdIO
3+import Effect.State
4+
5+counter : Eff () [STATE Int, STDIO]
6+counter = do putStrLn $ "Counter at " ++ show !get
7+ x <- getStr
8+ if trim x /= "" then pure ()
9+ else do put (!get + 1)
10+ counter
11+
12+startCounter : Eff () [STDIO]
13+startCounter = do putStrLn "Off we go!"
14+ new (STATE Int) 0 counter
15+ putStrLn "Finished!"
16+
17+main : IO ()
18+main = run startCounter
19+
test/effects004/expectednew file+11
@@ -0,0 +1,11 @@
1+Off we go!
2+Counter at 0
3+Counter at 1
4+Counter at 2
5+Counter at 3
6+Counter at 4
7+Counter at 5
8+Counter at 6
9+Counter at 7
10+Counter at 8
11+Finished!
test/effects004/inputnew file+10
@@ -0,0 +1,10 @@
1+
2+
3+
4+
5+
6+
7+
8+
9+done
10+
test/effects004/runnew file+4
@@ -0,0 +1,4 @@
1+#!/usr/bin/env bash
2+idris $@ effects004.idr -o effects004 -p effects
3+./effects004 < input
4+rm -f effects004 *.ibc
test/ffi006/run+1−1
@@ -1,5 +1,5 @@
11#!/usr/bin/env bash
22idris $@ ffi006.idr --interface -o ffi006.o
3−cc ffi006.c ffi006.o `idris --include` `idris --link` -o ffi006
3+${CC:=cc} ffi006.c ffi006.o `idris --include` `idris --link` -o ffi006
44./ffi006
55rm -f ffi006 *.ibc *.o *.h
test/interactive007/expected.msysnew file+1
@@ -0,0 +1 @@
1+Idris> *Data\ZZ> *Data\ZZ> *Data\ZZ> *Data\ZZ> Bye bye
test/reg039/run+27−24
@@ -1,32 +1,35 @@
11#!/usr/bin/env bash
22
3−# From http://unix.stackexchange.com/questions/43340/how-to-introduce-timeout-for-shell-scripting
4−# Executes command with a timeout
5−# Params:
6−# $1 timeout in seconds
7−# $2 command
8−# Returns 1 if timed out 0 otherwise
9−timeout() {
10−
11− time=$1
12−
13− # start the command in a subshell to avoid problem with pipes
14− # (spawn accepts one command)
15− command="/bin/sh -c \"$2\""
16−
17− expect -c "set echo \"-noecho\"; set timeout $time; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"
18−
19− if [ $? = 1 ] ; then
20− echo "Timeout after ${time} seconds"
21− fi
22−
23−}
243
254declare -a extraargs
265for arg in "$@"
276do
287 extraargs=("${extraargs[@]}" "'$arg'")
298done
30−
31−timeout 60 "idris ${extraargs[*]} --nocolour reg039.idr --exec go"
32−rm -f reg039 *.ibc
9+if (which timeout&>/dev/null); then
10+ timeout 60 idris $@ --nocolour reg039.idr --exec go
11+else
12+ # From http://unix.stackexchange.com/questions/43340/how-to-introduce-timeout-for-shell-scripting
13+ # Executes command with a timeout
14+ # Params:
15+ # $1 timeout in seconds
16+ # $2 command
17+ # Returns 1 if timed out 0 otherwise
18+ timeout() {
19+
20+ time=$1
21+
22+ # start the command in a subshell to avoid problem with pipes
23+ # (spawn accepts one command)
24+ command="/bin/sh -c \"$2\""
25+
26+ expect -c "set echo \"-noecho\"; set timeout $time; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"
27+
28+ if [ $? = 1 ] ; then
29+ echo "Timeout after ${time} seconds"
30+ fi
31+
32+ }
33+ timeout 60 "idris ${extraargs[*]} --nocolour reg039.idr --exec go"
34+ fi
35+ rm -f reg039 *.ibc
test/runtest.pl+8
@@ -30,6 +30,14 @@ sub runtest {
3030 my $got = `$sandbox ./run @idrOpts`;
3131 my $exp = `cat expected`;
3232
33+ # Allow for variant expected output for tests by overriding expected
34+ # when there is an expected.<os> file in the test.
35+ # This should be the exception but there are sometimes valid reasons
36+ # for os-dependent output.
37+ # The endings are msys for windows, darwin for osx and linux for linux
38+ if ( -e "expected.$^O") {
39+ $exp = `cat expected.$^O`;
40+ }
3341 open my $out, '>', 'output';
3442 print $out $got;
3543 close $out;
test/tactics001/Tactics.idr+4−4
@@ -1,6 +1,6 @@
11module Tactics
22
3−import Language.Reflection.Tactical
3+import Language.Reflection.Elab
44
55import Data.Vect
66
@@ -18,21 +18,21 @@ refl t x = RApp (RApp (Var (UN "Refl")) t) x
1818plusZeroRightNeutralNew : (n : Nat) -> plus n 0 = n
1919plusZeroRightNeutralNew Z = Refl
2020plusZeroRightNeutralNew (S k) =
21− %runTactics (do rewriteWith `(sym $ plusZeroRightNeutralNew ~(Var "k"))
21+ %runElab (do rewriteWith `(sym $ plusZeroRightNeutralNew ~(Var "k"))
2222 fill $ refl `(Nat : Type) `(S ~(Var (UN "k")))
2323 solve)
2424
2525plusSuccRightSuccNew : (j, k : Nat) -> plus j (S k) = S (plus j k)
2626plusSuccRightSuccNew Z k = Refl
2727plusSuccRightSuccNew (S j) k =
28− %runTactics (do rewriteWith `(sym $ plusSuccRightSuccNew ~(Var "j") ~(Var (UN "k")))
28+ %runElab (do rewriteWith `(sym $ plusSuccRightSuccNew ~(Var "j") ~(Var (UN "k")))
2929 fill $ refl `(Nat : Type) `(S (S (plus ~(Var (UN "j")) ~(Var (UN "k")))))
3030 solve)
3131
3232-- Test that side effects in new tactics work
3333
3434mkDecl : ()
35−mkDecl = %runTactics (do declareType $ Declare (NS (UN "repUnit") ["Tactics"])
35+mkDecl = %runElab (do declareType $ Declare (NS (UN "repUnit") ["Tactics"])
3636 [Implicit (UN "z") `(Nat)]
3737 `(Vect ~(Var (UN "z")) ())
3838 fill `(() : ())
win-release.shnew file+2
@@ -0,0 +1,2 @@
1+
2+IDRIS_LIB_DIR="./libs" IDRIS_TOOLCHAIN_DIR="./mingw/bin" CABALFLAGS="-fffi -ffreestanding -frelease" make