on master help sign in
Merge branch 'master' into boolean-op-fixity
dcf65d8Ahmad Salim Al-Sibahi
CHANGELOG.md+10
@@ -8,13 +8,17 @@
8+ The `LinearTypes` language extension has been revised. It implements the
8+ The `LinearTypes` language extension has been revised. It implements the
9 rules from Bob Atkey's draft "The Syntax and Semantics of Quantitative
9 rules from Bob Atkey's draft "The Syntax and Semantics of Quantitative
10 Type Theory" and now works with holes and case expressions.
10 Type Theory" and now works with holes and case expressions.
11++ Backticked operators can appear in sections, e.g. `(\`LTE\` 42)` or
12+ `(1 \`plus\`)`.
11
13
12## Library Updates
14## Library Updates
13
15
16++ Removed `oldeffects` library from `libs` folder, use `effects` or `Control.ST` instead.
14+ Added `Text.Literate`, a module for working with literate source files.
17+ Added `Text.Literate`, a module for working with literate source files.
15+ Added `Data.IORef`, for working with mutable references in `IO` and `JS_IO`.
18+ Added `Data.IORef`, for working with mutable references in `IO` and `JS_IO`.
16+ Added `discriminate` and `construct` tactics to Pruviloj.
19+ Added `discriminate` and `construct` tactics to Pruviloj.
17+ Added `IsSucc` type to `Prelude`, which proves that a `Nat` is a successor.
20+ Added `IsSucc` type to `Prelude`, which proves that a `Nat` is a successor.
21++ Added `Data.IOArray`, containing primitives for mutable arrays.
18+ Reworked operator fixity for `&&` and `||`, as well as the comparison operators: `==`, `/=`, `<`, `<=`, `>`, and `>=`.
22+ Reworked operator fixity for `&&` and `||`, as well as the comparison operators: `==`, `/=`, `<`, `<=`, `>`, and `>=`.
19
23
20## Tool Updates
24## Tool Updates
@@ -23,6 +27,12 @@
23+ The --interface option now creates CommonJS modules on the node backend.
27+ The --interface option now creates CommonJS modules on the node backend.
24+ The C backend now pass arguments to the C compiler in the same order
28+ The C backend now pass arguments to the C compiler in the same order
25 as they were given in the source files.
29 as they were given in the source files.
30++ Backslash, braces and percent symbols are now correctly pretty printed
31+ in LaTeX.
32+
33+## Packaging Updates
34++ Package names now only accept a restrictive charset of letters, numbers and the `-_` characters.
35+ Package names are also case insensitive
26
36
27# New in 1.1.1
37# New in 1.1.1
28
38
CONTRIBUTORS+3
@@ -34,6 +34,7 @@ Brent Yorgey
34Brian Koropoff
34Brian Koropoff
35Brian McKenna
35Brian McKenna
36Bryn Keller
36Bryn Keller
37+Caleb Case
37Calvin Beck
38Calvin Beck
38Carsten König
39Carsten König
39Carter Charbonneau
40Carter Charbonneau
@@ -107,6 +108,7 @@ Jan de Muijnck-Hughes
107Jan Doms
108Jan Doms
108Jan Stolarek
109Jan Stolarek
109Jason Dagit
110Jason Dagit
111+Jason Felice
110Jason Gross
112Jason Gross
111Jean-Remi Desjardins
113Jean-Remi Desjardins
112Jeff Hemphill
114Jeff Hemphill
@@ -202,6 +204,7 @@ Stuart Gale
202suhorng
204suhorng
203Sune Alkærsig
205Sune Alkærsig
204Sven Koschnicke
206Sven Koschnicke
207+Taran Lynn
205tdidriksen
208tdidriksen
206Tenor Biel
209Tenor Biel
207Thomas Cooper
210Thomas Cooper
docs/tutorial/miscellany.rst+1−1
@@ -86,7 +86,7 @@ number as 0), we could write:
86
86
87 fibonacci : {default 0 lag : Nat} -> {default 1 lead : Nat} -> (n : Nat) -> Nat
87 fibonacci : {default 0 lag : Nat} -> {default 1 lead : Nat} -> (n : Nat) -> Nat
88 fibonacci {lag} Z = lag
88 fibonacci {lag} Z = lag
89− fibonacci {lag} {lead} (S Z) = fibonacci {lag=lead} {lead=lag+lead} n
89+ fibonacci {lag} {lead} (S n) = fibonacci {lag=lead} {lead=lag+lead} n
90
90
91After this definition, ``fibonacci 5`` is equivalent to ``fibonacci {lag=0} {lead=1} 5``,
91After this definition, ``fibonacci 5`` is equivalent to ``fibonacci {lag=0} {lead=1} 5``,
92and will return the 5th fibonacci number. Note that while this works, this is not the
92and will return the 5th fibonacci number. Note that while this works, this is not the
idris.cabal+1−1
@@ -314,7 +314,7 @@ Library
314
314
315 if os(windows)
315 if os(windows)
316 build-depends: mintty >= 0.1 && < 0.2
316 build-depends: mintty >= 0.1 && < 0.2
317− , Win32 < 2.4
317+ , Win32 < 2.7
318 else
318 else
319 build-depends: unix < 2.8
319 build-depends: unix < 2.8
320 if flag(FFI)
320 if flag(FFI)
libs/base/Control/Monad/State.idr+4
@@ -42,6 +42,10 @@ implementation MonadTrans (StateT stateType) where
42 lift x = ST (\st => do r <- x
42 lift x = ST (\st => do r <- x
43 pure (r, st))
43 pure (r, st))
44
44
45+implementation (Monad f, Alternative f) => Alternative (StateT st f) where
46+ empty = lift empty
47+ (ST f) <|> (ST g) = ST (\st => f st <|> g st)
48+
45||| Apply a function to modify the context of this computation
49||| Apply a function to modify the context of this computation
46modify : MonadState stateType m => (stateType -> stateType) -> m ()
50modify : MonadState stateType m => (stateType -> stateType) -> m ()
47modify f = do s <- get
51modify f = do s <- get
libs/base/Data/Primitives/Views.idr+19−15
@@ -12,9 +12,9 @@ namespace Integer
12 DivByZero : Divides x 0
12 DivByZero : Divides x 0
13 DivBy : (prf : rem >= 0 && rem < d = True) ->
13 DivBy : (prf : rem >= 0 && rem < d = True) ->
14 Divides ((d * div) + rem) d
14 Divides ((d * div) + rem) d
15−
15+
16 ||| Covering function for the `Divides` view
16 ||| Covering function for the `Divides` view
17− export
17+ public export
18 divides : (val : Integer) -> (d : Integer) -> Divides val d
18 divides : (val : Integer) -> (d : Integer) -> Divides val d
19 divides val 0 = DivByZero
19 divides val 0 = DivByZero
20 divides val d
20 divides val d
@@ -22,21 +22,23 @@ namespace Integer
22 let dividend = if d < 0 then -(val `div` abs d)
22 let dividend = if d < 0 then -(val `div` abs d)
23 else val `div` d
23 else val `div` d
24 remainder = abs (val - dividend * d) in
24 remainder = abs (val - dividend * d) in
25− believe_me (DivBy {d} {div = dividend} {rem = remainder}
25+ really_believe_me (DivBy {d} {div = dividend} {rem = remainder}
26− (believe_me (Refl {x = True})))
26+ (really_believe_me (Refl {x = True})))
27
27
28 ||| View for recursion over Integers
28 ||| View for recursion over Integers
29+ public export
29 data IntegerRec : Integer -> Type where
30 data IntegerRec : Integer -> Type where
30 IntegerZ : IntegerRec 0
31 IntegerZ : IntegerRec 0
31 IntegerSucc : IntegerRec (n - 1) -> IntegerRec n
32 IntegerSucc : IntegerRec (n - 1) -> IntegerRec n
32 IntegerPred : IntegerRec ((-n) + 1) -> IntegerRec (-n)
33 IntegerPred : IntegerRec ((-n) + 1) -> IntegerRec (-n)
33−
34+
34 ||| Covering function for `IntegerRec`
35 ||| Covering function for `IntegerRec`
36+ public export
35 integerRec : (x : Integer) -> IntegerRec x
37 integerRec : (x : Integer) -> IntegerRec x
36 integerRec 0 = IntegerZ
38 integerRec 0 = IntegerZ
37 integerRec x = if x > 0 then IntegerSucc (assert_total (integerRec (x - 1)))
39 integerRec x = if x > 0 then IntegerSucc (assert_total (integerRec (x - 1)))
38− else believe_me (IntegerPred {n=-x}
40+ else really_believe_me (IntegerPred {n=-x}
39− (assert_total (believe_me (integerRec (x + 1)))))
41+ (assert_total (really_believe_me (integerRec (x + 1)))))
40
42
41namespace Int
43namespace Int
42 ||| View for expressing a number as a multiplication + a remainder
44 ||| View for expressing a number as a multiplication + a remainder
@@ -45,13 +47,13 @@ namespace Int
45 DivByZero : Int.Divides x 0
47 DivByZero : Int.Divides x 0
46 DivBy : (prf : rem >= 0 && rem < d = True) ->
48 DivBy : (prf : rem >= 0 && rem < d = True) ->
47 Int.Divides ((d * div) + rem) d
49 Int.Divides ((d * div) + rem) d
48−
50+
49 -- I have assumed, but not actually verified, that this will still
51 -- I have assumed, but not actually verified, that this will still
50 -- give a right result (i.e. still adding up) when the Ints overflow.
52 -- give a right result (i.e. still adding up) when the Ints overflow.
51 -- TODO: Someone please check this and fix if necessary...
53 -- TODO: Someone please check this and fix if necessary...
52
54
53 ||| Covering function for the `Divides` view
55 ||| Covering function for the `Divides` view
54− export
56+ public export
55 divides : (val : Int) -> (d : Int) -> Divides val d
57 divides : (val : Int) -> (d : Int) -> Divides val d
56 divides val 0 = DivByZero
58 divides val 0 = DivByZero
57 divides val d
59 divides val d
@@ -59,19 +61,21 @@ namespace Int
59 let dividend = if d < 0 then -(val `div` abs d)
61 let dividend = if d < 0 then -(val `div` abs d)
60 else val `div` d
62 else val `div` d
61 remainder = abs (val - dividend * d) in
63 remainder = abs (val - dividend * d) in
62− believe_me (DivBy {d} {div = dividend} {rem = remainder}
64+ really_believe_me (DivBy {d} {div = dividend} {rem = remainder}
63− (believe_me (Refl {x = True})))
65+ (really_believe_me (Refl {x = True})))
64
66
65 ||| View for recursion over Ints
67 ||| View for recursion over Ints
68+ public export
66 data IntRec : Int -> Type where
69 data IntRec : Int -> Type where
67 IntZ : IntRec 0
70 IntZ : IntRec 0
68 IntSucc : IntRec (n - 1) -> IntRec n
71 IntSucc : IntRec (n - 1) -> IntRec n
69 IntPred : IntRec ((-n) + 1) -> IntRec (-n)
72 IntPred : IntRec ((-n) + 1) -> IntRec (-n)
70−
73+
71 ||| Covering function for `IntRec`
74 ||| Covering function for `IntRec`
75+ public export
72 intRec : (x : Int) -> IntRec x
76 intRec : (x : Int) -> IntRec x
73 intRec 0 = IntZ
77 intRec 0 = IntZ
74 intRec x = if x > 0 then IntSucc (assert_total (intRec (x - 1)))
78 intRec x = if x > 0 then IntSucc (assert_total (intRec (x - 1)))
75− else believe_me (IntPred {n=-x}
79+ else really_believe_me (IntPred {n=-x}
76− (assert_total (believe_me (intRec (x + 1)))))
80+ (assert_total (really_believe_me (intRec (x + 1)))))
77−
81+
libs/base/Data/Vect.idr+8
@@ -634,6 +634,14 @@ mapElem : {xs : Vect k t} -> {f : t -> u} -> Elem x xs -> Elem (f x) (map f xs)
634mapElem Here = Here
634mapElem Here = Here
635mapElem (There e) = There (mapElem e)
635mapElem (There e) = There (mapElem e)
636
636
637+||| Remove the element at the given position.
638+|||
639+||| @xs The vector to be removed from
640+||| @p A proof that the element to be removed is in the vector
641+dropElem : (xs : Vect (S k) t) -> (p : Elem x xs) -> Vect k t
642+dropElem (x :: ys) Here = ys
643+dropElem {k = (S k)} (x :: ys) (There later) = x :: dropElem ys later
644+
637-- Some convenience functions for testing lengths
645-- Some convenience functions for testing lengths
638
646
639||| If the given Vect is the required length, return a Vect with that
647||| If the given Vect is the required length, return a Vect with that
libs/base/base.ipkg+39−44
@@ -1,48 +1,43 @@
1package base
1package base
2
2
3opts = "--nobasepkgs --total --no-elim-deprecation-warnings --partial-eval -i ../prelude"
3opts = "--nobasepkgs --total --no-elim-deprecation-warnings --partial-eval -i ../prelude"
4−modules = System,
5
4
6− Debug.Error, Debug.Trace,
5+modules = Control.Arrow
7−
6+ , Control.Catchable
8− System.Info,
7+ , Control.Category
9−
8+ , Control.IOExcept
10− Language.Reflection.Utils,
9+ , Control.Isomorphism
11−
10+ , Control.Monad.Identity
12− Syntax.PreorderReasoning,
11+ , Control.Monad.Reader
13−
12+ , Control.Monad.RWS
14− Data.Morphisms,
13+ , Control.Monad.State
14+ , Control.Monad.Trans
15+ , Control.Monad.Writer
15− Data.Bits,
16+ , Data.Bits
16− Data.Mod2,
17− Data.Fin,
17+ , Data.Buffer
18− Data.Vect,
19− Data.Vect.Views,
20− Data.Vect.Quantifiers,
21− Data.HVect,
22− Data.Complex,
18+ , Data.Complex
23− Data.Erased,
19+ , Data.Erased
20+ , Data.Fin
21+ , Data.HVect
24− Data.IORef,
22+ , Data.IORef
23+ , Data.List
25− Data.List,
24+ , Data.List.Quantifiers
26− Data.List.Views,
25+ , Data.List.Views
27− Data.List.Quantifiers,
26+ , Data.Mod2
27+ , Data.Morphisms
28− Data.Nat.Views,
28+ , Data.Nat.Views
29− Data.Primitives.Views,
29+ , Data.Primitives.Views
30− Data.String.Views,
31− Data.So,
30+ , Data.So
32− Data.String,
31+ , Data.String
33− Data.Buffer,
32+ , Data.String.Views
34−
33+ , Data.Vect
35− Control.Isomorphism,
34+ , Data.Vect.Quantifiers
36− Control.Monad.Identity,
35+ , Data.Vect.Views
37− Control.Monad.RWS,
36+ , Debug.Error
38− Control.Monad.Trans,
37+ , Debug.Trace
39− Control.Monad.State,
38+ , Language.Reflection.Utils
40− Control.Monad.Writer,
39+ , Syntax.PreorderReasoning
41− Control.Monad.Reader,
40+ , System
42− Control.Category,
41+ , System.Concurrency.Channels
43− Control.Arrow,
44− Control.Catchable,
45− Control.IOExcept,
46−
47− System.Concurrency.Raw,
42+ , System.Concurrency.Raw
48− System.Concurrency.Channels
43+ , System.Info
libs/contrib/Control/ST/Random.idrnew file+16
@@ -0,0 +1,16 @@
1+module Control.ST.Random
2+
3+import Control.ST
4+
5+public export
6+Random : Type
7+Random = State Integer
8+
9+export
10+getRandom : (rnd : Var) -> ST m Integer [rnd ::: Random]
11+getRandom rnd =
12+ do
13+ st <- read rnd
14+ let st' = assert_total ((1664525 * st + 1013904223) `prim__sremBigInt` (pow 2 32))
15+ write rnd st'
16+ pure st'
libs/contrib/Data/Combinators.idrnew file+39
@@ -0,0 +1,39 @@
1+||| Combinators that are thought to be at least situationally useful, mostly for
2+||| tacit (or point-free) programming. "To Mock a Mockingbird" refers to the book
3+||| "To Mock a Mockingbird and Other Logic Puzzles: Including an Amazing Adventure
4+||| in Combinatory Logic", by Raymond Smullyan (which the author of this module
5+||| hasn't actually read). See
6+||| http://www.angelfire.com/tx4/cus/combinator/birds.html and
7+||| https://hackage.haskell.org/package/data-aviary-0.4.0/docs/Data-Aviary-Birds.html
8+||| an (incomplete?) list of birds introduced. Also includes some operations defined
9+||| over Arrows.
10+
11+module Data.Combinators
12+
13+%default total
14+%access public export
15+
16+||| Psi combinator - psi bird (?) - Haskell on.
17+on : (b -> b -> c) -> (a -> b) -> (a -> a -> c)
18+on f g x y = g x `f` g y
19+
20+
21+infixl 9 ...
22+||| Blackbird, as named in "To Mock a Mockingbird". This is like
23+||| function composition, but second function takes two arguments. See the talk
24+||| "Point-Free or Die: Tacit Programming in Haskell and Beyond" by Amar Shah
25+||| (https://youtu.be/seVSlKazsNk).
26+(...) : (c -> d) -> (a -> b -> c) -> (a -> b -> d)
27+(...) = (.) . (.)
28+
29+||| Warbler, as named in "To Mock a Mockingbird".
30+||| See http://code.jsoftware.com/wiki/Vocabulary/tilde
31+||| Equivalent to `join` on the Reader monad (`(->) e` in Haskell)
32+reflex : (a -> a -> b) -> (a -> b)
33+reflex f x = f x x
34+
35+||| Phoenix, according to Data.Aviary.
36+||| See http://code.jsoftware.com/wiki/Vocabulary/fork.
37+||| Equivalent to `liftA2` on the Reader monad (`(->) e` in Haskell)
38+fork2 : (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)
39+fork2 f g h x = f (g x) (h x)
libs/contrib/Data/Combinators/Applicative.idrnew file+27
@@ -0,0 +1,27 @@
1+||| Enable applicative-style syntax (Mostly f <$> g <*> h and idiom brackets)
2+||| for function composition:
3+module Data.Combinators.Applicative
4+
5+import Data.Combinators
6+
7+%default total
8+%access public export
9+
10+||| Pure is just const, also known as the K combinator
11+pure : a -> b -> a
12+pure = const
13+
14+||| `map` is (.), but isn't here to discourage that use of the syntax.
15+||| `foo <$> bar <*> baz` applies `foo` to the results of `bar` and `baz`,
16+||| and generalizes to multiple arguments.
17+(<$>) : (b -> c) -> (a -> b) -> (a -> c)
18+(<$>) f g x = f (g x)
19+
20+||| Starling, as named in "To Mock a Mockingbird". This is the S combinator.
21+||| Equivalent to `<*>` on the Reader monad (`(->) e` in Haskell).
22+||| See http://code.jsoftware.com/wiki/Vocabulary/hook.
23+(<*>) : (a -> b -> c) -> (a -> b)-> (a -> c)
24+(<*>) f g x = f x (g x)
25+
26+liftA2 : (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)
27+liftA2 = fork2
libs/contrib/Data/Combinators/Arrow.idrnew file+15
@@ -0,0 +1,15 @@
1+||| Combinators from Control.Arrow
2+
3+first : (a -> b) -> (a, c) -> (b, c)
4+first f (a, c) = (f a, c)
5+
6+second : (a -> b) -> ((c, a) -> (c, b))
7+second f (c, a) = (c, f a)
8+
9+infixr 3 ***
10+(***) : (a -> b) -> (a' -> b') -> ((a, a') -> (b, b'))
11+(***) f g (a, a') = (f a, g a')
12+
13+infixr 3 &&&
14+(&&&) : (a -> b) -> (a -> b') -> (a -> (b, b'))
15+(&&&) f g x = (f x, g x)
libs/contrib/Data/IOArray.idrnew file+47
@@ -0,0 +1,47 @@
1+module Data.IOArray
2+
3+-- Raw access to IOArrays. This interface is unsafe because there's no
4+-- bounds checking, and is merely intended to provide primitive access via
5+-- the RTS. Safe interfaces (either with run time or compile time
6+-- bounds checking) can be implemented on top of this
7+
8+-- Implemented entirely by the array primitives in the RTS
9+data ArrayData : Type -> Type where
10+
11+export
12+data IOArray elem = MkIOArray (ArrayData elem)
13+
14+||| Create a new array of the given size, with all entries set to the
15+||| given default element.
16+export
17+newArray : Int -> elem -> IO (IOArray elem)
18+newArray size default
19+ = do vm <- getMyVM
20+ MkRaw p <- foreign FFI_C "idris_newArray"
21+ (Ptr -> Int -> Raw elem -> IO (Raw (ArrayData elem)))
22+ vm size (MkRaw default)
23+ pure (MkIOArray p)
24+
25+||| Write an element at a location in an array.
26+||| There is *no* bounds checking, hence this is unsafe. Safe interfaces can
27+||| be implemented on top of this, either with a run time or compile time
28+||| check.
29+export
30+unsafeWriteArray : IOArray elem -> Int -> elem -> IO ()
31+unsafeWriteArray (MkIOArray p) i val
32+ = foreign FFI_C "idris_arraySet"
33+ (Raw (ArrayData elem) -> Int -> Raw elem -> IO ())
34+ (MkRaw p) i (MkRaw val)
35+
36+||| Read the element at a location in an array.
37+||| There is *no* bounds checking, hence this is unsafe. Safe interfaces can
38+||| be implemented on top of this, either with a run time or compile time
39+||| check.
40+export
41+unsafeReadArray : IOArray elem -> Int -> IO elem
42+unsafeReadArray (MkIOArray p) i
43+ = do MkRaw val <- foreign FFI_C "idris_arrayGet"
44+ (Raw (ArrayData elem) -> Int -> IO (Raw elem))
45+ (MkRaw p) i
46+ pure val
47+
libs/contrib/Data/String.idr → libs/contrib/Data/String/Extra.idrrenamed+1−1
@@ -1,4 +1,4 @@
1−module Data.String
1+module Data.String.Extra
2
2
3infixl 5 +>
3infixl 5 +>
4infixr 5 <+
4infixr 5 <+
libs/contrib/contrib.ipkg+55−41
@@ -1,45 +1,59 @@
1package contrib
1package contrib
2
2
3opts = "--nobasepkgs --partial-eval --total -i ../prelude -i ../base"
3opts = "--nobasepkgs --partial-eval --total -i ../prelude -i ../base"
4−modules = CFFI, CFFI.Types, CFFI.Memory,
5
4
5+modules = CFFI
6+ , CFFI.Memory
7+ , CFFI.Types
6− Control.Algebra,
8+ , Control.Algebra
7− Control.Algebra.Lattice, Control.Algebra.VectorSpace,
9+ , Control.Algebra.Lattice
8− Control.Algebra.NumericImplementations,
10+ , Control.Algebra.NumericImplementations
11+ , Control.Algebra.VectorSpace
9− Control.Isomorphism.Primitives,
12+ , Control.Isomorphism.Primitives
10− Control.Partial,
13+ , Control.Partial
11− Control.Pipeline,
14+ , Control.Pipeline
15+ , Control.ST
16+ , Control.ST.Exception
12− Control.ST, Control.ST.ImplicitCall, Control.ST.Exception,
17+ , Control.ST.ImplicitCall
13−
18+ , Control.ST.Random
14− Interfaces.Correlative,
19+ , Data.BoundedList
15− Interfaces.Verified,
20+ , Data.CoList
16−
21+ , Data.Combinators
22+ , Data.Combinators.Applicative
23+ , Data.Combinators.Arrow
24+ , Data.Fin.Extra
17− Data.Fun, Data.Rel,
25+ , Data.Fun
18− Data.Hash,
26+ , Data.Hash
27+ , Data.Heap
28+ , Data.IOArray
29+ , Data.List.Zipper
30+ , Data.Matrix
19− Data.Matrix, Data.Matrix.Algebraic, Data.Matrix.Numeric,
31+ , Data.Matrix.Algebraic
32+ , Data.Matrix.Numeric
33+ , Data.Nat.DivMod
20− Data.Nat.DivMod, Data.Nat.DivMod.IteratedSubtraction,
34+ , Data.Nat.DivMod.IteratedSubtraction
35+ , Data.Pairs.Implicit
36+ , Data.Rel
21− Data.ZZ, Data.Sign,
37+ , Data.Sign
22− Data.BoundedList,
23− Data.Heap,
24− Data.SortedMap, Data.SortedSet,
38+ , Data.SortedMap
39+ , Data.SortedSet
25− Data.CoList, Data.Storable,
40+ , Data.Storable
26− Data.List.Zipper,
41+ , Data.Stream.Extra
27− Data.Pairs.Implicit,
42+ , Data.String.Extra
28−
43+ , Data.ZZ
29− Decidable.Decidable, Decidable.Order,
44+ , Decidable.Decidable
30−
45+ , Decidable.Order
46+ , Interfaces.Correlative
47+ , Interfaces.Verified
48+ , Network.Cgi
49+ , Network.Socket
50+ , Network.Socket.Data
31− Network.Cgi, Network.Socket.Data, Network.Socket.Raw, Network.Socket,
51+ , Network.Socket.Raw
32−
33− System.Concurrency.Process,
52+ , System.Concurrency.Process
34−
53+ , Text.Lexer
54+ , Text.Literate
35− Text.Lexer, Text.Parser,
55+ , Text.Parser
36−
37− Text.PrettyPrint.WL,
38− Text.PrettyPrint.WL.Core,
56+ , Text.PrettyPrint.WL
39− Text.PrettyPrint.WL.Characters,
57+ , Text.PrettyPrint.WL.Characters
40− Text.PrettyPrint.WL.Combinators,
58+ , Text.PrettyPrint.WL.Combinators
41−
59+ , Text.PrettyPrint.WL.Core
42− Text.Literate,
43−
44− Data.Fin.Extra,
45− Data.Stream.Extra
libs/effects/effects.ipkg+11−12
@@ -1,21 +1,20 @@
1package effects
1package effects
2
2
3−opts = "--nobasepkgs --partial-eval --typeintype -i ../prelude -i ../base"
3+opts = "--nobasepkgs --partial-eval --typeintype -i ../prelude -i ../base"
4−
5−modules = Effects
6− , Effect.Default
7− , Effect.Monad
8
4
5+modules = Effect.Default
9 , Effect.Exception
6 , Effect.Exception
10 , Effect.File
7 , Effect.File
11− , Effect.State
8+ , Effect.Logging.Category
9+ , Effect.Logging.Default
10+ , Effect.Logging.Level
11+ , Effect.Memory
12+ , Effect.Monad
13+ , Effect.Perf
12 , Effect.Random
14 , Effect.Random
13− , Effect.StdIO
14 , Effect.Select
15 , Effect.Select
15− , Effect.Memory
16+ , Effect.State
17+ , Effect.StdIO
16 , Effect.System
18 , Effect.System
17 , Effect.Trans
19 , Effect.Trans
18− , Effect.Logging.Level
20+ , Effects
19− , Effect.Logging.Default
20− , Effect.Logging.Category
21− , Effect.Perf
libs/oldeffects/Effect/Default.idrdeleted−44
@@ -1,44 +0,0 @@
1−module Default
2−
3−interface Default a where
4− default : a
5−
6−implementation Default Int where
7− default = 0
8−
9−implementation Default Integer where
10− default = 0
11−
12−implementation Default Double where
13− default = 0
14−
15−implementation Default Nat where
16− default = 0
17−
18−implementation Default Char where
19− default = '\0'
20−
21−implementation Default String where
22− default = ""
23−
24−implementation Default Bool where
25− default = False
26−
27−implementation Default () where
28− default = ()
29−
30−implementation (Default a, Default b) => Default (a, b) where
31− default = (default, default)
32−
33−implementation Default (Maybe a) where
34− default = Nothing
35−
36−implementation Default (List a) where
37− default = []
38−
39−implementation Default a => Default (Vect n a) where
40− default = mkDef _ where
41− mkDef : (n : Nat) -> Vect n a
42− mkDef Z = []
43− mkDef (S k) = default :: mkDef k
44−
libs/oldeffects/Effect/Exception.idrdeleted−41
@@ -1,41 +0,0 @@
1−module Effect.Exception
2−
3−import Effects
4−import System
5−import Control.IOExcept
6−
7−data Exception : Type -> Effect where
8− Raise : a -> { () } Exception a b
9−
10−implementation Handler (Exception a) Maybe where
11− handle _ (Raise e) k = Nothing
12−
13−implementation Handler (Exception a) List where
14− handle _ (Raise e) k = []
15−
16−implementation Show a => Handler (Exception a) IO where
17− handle _ (Raise e) k = do printLn e
18− believe_me (exit 1)
19−
20−implementation Handler (Exception a) (IOExcept a) where
21− handle _ (Raise e) k = ioM (pure (Left e))
22−
23−implementation Handler (Exception a) (Either a) where
24− handle _ (Raise e) k = Left e
25−
26−EXCEPTION : Type -> EFFECT
27−EXCEPTION t = MkEff () (Exception t)
28−
29−raise : a -> { [EXCEPTION a ] } Eff m b
30−raise 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/oldeffects/Effect/File.idrdeleted−128
@@ -1,128 +0,0 @@
1−-- -------------------------------------------------------- [ Effectful FileIO ]
2−module Effect.File
3−
4−import Effects
5−import Control.IOExcept
6−
7−
8−||| A Dependent type to describe File Handles. File handles are
9−||| parameterised with the current state of the file: Closed; Open for
10−||| reading; and Open for writing.
11−|||
12−||| @ m The file mode.
13−data OpenFile : (m : Mode) -> Type where
14− FH : File -> OpenFile m
15−
16−openOK : Mode -> Bool -> Type
17−openOK m True = OpenFile m
18−openOK m False = ()
19−
20−-- ------------------------------------------------------------ [ The Protocol ]
21−
22−||| Here the protocol for resource access is defined as an effect.
23−||| The state transitions diagram for the protocol is as follows:
24−|||
25−||| digraph G {
26−|||
27−||| empty; read; write; // States
28−|||
29−||| empty -> read [label="Open R"];
30−||| read -> empty [label="Close"];
31−||| read -> read [label="ReadLine"];
32−||| read -> read [label="EOF"];
33−|||
34−||| empty -> write [label="Open W"];
35−||| write -> empty [label="Close"];
36−||| write -> write [label="WriteLine"];
37−|||
38−||| }
39−data FileIO : Effect where
40− ||| Open a file with the specified mode.
41− |||
42− ||| Opening a file successful moves the state from 'empty' to the
43− ||| specified mode. If not successful the state is still 'empty'.
44− |||
45− ||| @ fname The file name to be opened.
46− ||| @ m The file mode.
47− Open : (fname: String)
48− -> (m : Mode)
49− -> {() ==> {res} if res
50− then OpenFile m
51− else ()} FileIO Bool
52−
53− ||| Close a file.
54− |||
55− ||| Closing a file moves the state from Open to closed.
56− Close : {OpenFile m ==> ()} FileIO ()
57−
58− ||| Read a line from the file.
59− |||
60− ||| Only files that are open for reading can be read.
61− ReadLine : {OpenFile Read} FileIO String
62−
63− ||| Write a line to a file.
64− |||
65− ||| Only file that are open for writing can be written to.
66− WriteLine : String -> {OpenFile Write} FileIO ()
67−
68− ||| End of file?
69− |||
70− ||| Only files open for reading can be tested for EOF
71− EOF : {OpenFile Read} FileIO Bool
72−
73−-- ------------------------------------------------------------ [ The Handlers ]
74−
75−--- An implementation of the resource access protocol for the IO Context.
76−implementation Handler FileIO IO where
77− handle () (Open fname m) k = do h <- openFile fname m
78− valid <- validFile h
79− if valid then k True (FH h)
80− else k False ()
81− handle (FH h) Close k = do closeFile h
82− k () ()
83− handle (FH h) ReadLine k = do str <- fread h
84− k str (FH h)
85− handle (FH h) (WriteLine str) k = do fwrite h str
86− k () (FH h)
87− handle (FH h) EOF k = do e <- feof h
88− k e (FH h)
89−
90−-- -------------------------------------------------------------- [ The Effect ]
91−FILE_IO : Type -> EFFECT
92−FILE_IO t = MkEff t FileIO
93−
94−-- ------------------------------------------------------------ [ The Bindings ]
95−--
96−-- Bind the IO context handlers to functions. These functions will run
97−-- in the IO context.
98−--
99−
100−||| Open a file with the specified mode.
101−|||
102−||| @ fname The file name to be opened.
103−||| @ m The file mode.
104−open : (fname : String)
105− -> (m : Mode)
106− -> { [FILE_IO ()] ==> [FILE_IO (if result
107− then OpenFile m
108− else ())] } Eff e Bool
109−open f m = call $ Open f m
110−
111−
112−||| Close a file.
113−close : { [FILE_IO (OpenFile m)] ==> [FILE_IO ()] } Eff e ()
114−close = call $ Close
115−
116−||| Read a line from the file.
117−readLine : { [FILE_IO (OpenFile Read)] } Eff e String
118−readLine = call $ ReadLine
119−
120−||| Write a line to a file.
121−writeLine : String -> { [FILE_IO (OpenFile Write)] } Eff e ()
122−writeLine str = call $ WriteLine str
123−
124−||| End of file?
125−eof : { [FILE_IO (OpenFile Read)] } Eff e Bool
126−eof = call $ EOF
127−
128−-- --------------------------------------------------------------------- [ EOF ]
libs/oldeffects/Effect/Memory.idrdeleted−175
@@ -1,175 +0,0 @@
1−module Effect.Memory
2−
3−import Effects
4−import Control.IOExcept
5−
6−%access public
7−
8−abstract
9−data MemoryChunk : Nat -> Nat -> Type where
10− CH : Ptr -> MemoryChunk size initialized
11−
12−abstract
13−data RawMemory : Effect where
14− Allocate : (n : Nat) ->
15− RawMemory () () (\v => MemoryChunk n 0)
16− Free : RawMemory () (MemoryChunk n i) (\v => ())
17− Initialize : Bits8 ->
18− (size : Nat) ->
19− so (i + size <= n) ->
20− RawMemory () (MemoryChunk n i) (\v => MemoryChunk n (i + size))
21− Peek : (offset : Nat) ->
22− (size : Nat) ->
23− so (offset + size <= i) ->
24− RawMemory (Vect size Bits8)
25− (MemoryChunk n i) (\v => MemoryChunk n i)
26− Poke : (offset : Nat) ->
27− (Vect size Bits8) ->
28− so (offset <= i && offset + size <= n) ->
29− RawMemory () (MemoryChunk n i) (\v => MemoryChunk n (max i (offset + size)))
30− Move : (src : MemoryChunk src_size src_init) ->
31− (dst_offset : Nat) ->
32− (src_offset : Nat) ->
33− (size : Nat) ->
34− so (dst_offset <= dst_init && dst_offset + size <= dst_size) ->
35− so (src_offset + size <= src_init) ->
36− RawMemory () (MemoryChunk dst_size dst_init)
37− (\v => MemoryChunk dst_size (max dst_init (dst_offset + size)))
38− GetRawPtr : RawMemory (MemoryChunk n i) (MemoryChunk n i) (\v => MemoryChunk n i)
39−
40−private
41−do_malloc : Nat -> IOExcept String Ptr
42−do_malloc size with (fromInteger (cast size) == size)
43− | True = do ptr <- ioe_lift $ mkForeign (FFun "malloc" [FInt] FPtr) (fromInteger $ cast size)
44− fail <- ioe_lift $ nullPtr ptr
45− if fail then ioe_fail "Cannot allocate memory"
46− else pure ptr
47− | False = ioe_fail "The target architecture does not support adressing enough memory"
48−
49−private
50−do_memset : Ptr -> Nat -> Bits8 -> Nat -> IO ()
51−do_memset ptr offset c size
52− = mkForeign (FFun "idris_memset" [FPtr, FInt, FByte, FInt] FUnit)
53− ptr (fromInteger $ cast offset) c (fromInteger $ cast size)
54−
55−private
56−do_free : Ptr -> IO ()
57−do_free ptr = mkForeign (FFun "free" [FPtr] FUnit) ptr
58−
59−private
60−do_memmove : Ptr -> Ptr -> Nat -> Nat -> Nat -> IO ()
61−do_memmove dest src dest_offset src_offset size
62− = mkForeign (FFun "idris_memmove" [FPtr, FPtr, FInt, FInt, FInt] FUnit)
63− dest src (fromInteger $ cast dest_offset) (fromInteger $ cast src_offset) (fromInteger $ cast size)
64−
65−private
66−do_peek : Ptr -> Nat -> (size : Nat) -> IO (Vect size Bits8)
67−do_peek _ _ Z = pure (Prelude.Vect.Nil)
68−do_peek ptr offset (S n)
69− = do b <- mkForeign (FFun "idris_peek" [FPtr, FInt] FByte) ptr (fromInteger $ cast offset)
70− bs <- do_peek ptr (S offset) n
71− Prelude.Applicative.pure (Prelude.Vect.(::) b bs)
72−
73−private
74−do_poke : Ptr -> Nat -> Vect size Bits8 -> IO ()
75−do_poke _ _ [] = pure ()
76−do_poke ptr offset (b::bs)
77− = do mkForeign (FFun "idris_poke" [FPtr, FInt, FByte] FUnit) ptr (fromInteger $ cast offset) b
78− do_poke ptr (S offset) bs
79−
80−implementation Handler RawMemory (IOExcept String) where
81− handle () (Allocate n) k
82− = do ptr <- do_malloc n
83− k () (CH ptr)
84− handle {-{res = MemoryChunk _ offset}-} (CH ptr) (Initialize {i} c size _) k
85− = ioe_lift (do_memset ptr i c size) $> k () (CH ptr)
86− handle (CH ptr) (Free) k
87− = ioe_lift (do_free ptr) $> k () ()
88− handle (CH ptr) (Peek offset size _) k
89− = do res <- ioe_lift (do_peek ptr offset size)
90− k res (CH ptr)
91− handle (CH ptr) (Poke offset content _) k
92− = do ioe_lift (do_poke ptr offset content)
93− k () (CH ptr)
94− handle (CH dest_ptr) (Move (CH src_ptr) dest_offset src_offset size _ _) k
95− = do ioe_lift (do_memmove dest_ptr src_ptr dest_offset src_offset size)
96− k () (CH dest_ptr)
97− handle chunk (GetRawPtr) k
98− = k chunk chunk
99−
100−RAW_MEMORY : Type -> EFFECT
101−RAW_MEMORY t = MkEff t RawMemory
102−
103−allocate : (n : Nat) ->
104− Eff m () [RAW_MEMORY ()] (\v => [RAW_MEMORY (MemoryChunk n 0)])
105−allocate size = call $ Allocate size
106−
107−initialize : {i : Nat} ->
108− {n : Nat} ->
109− Bits8 ->
110− (size : Nat) ->
111− so (i + size <= n) ->
112− Eff m () [RAW_MEMORY (MemoryChunk n i)]
113− (\v => [RAW_MEMORY (MemoryChunk n (i + size))])
114−initialize c size prf = call $ Initialize c size prf
115−
116−free : Eff m () [RAW_MEMORY (MemoryChunk n i)] (\v => [RAW_MEMORY ()])
117−free = call Free
118−
119−peek : {i : Nat} ->
120− (offset : Nat) ->
121− (size : Nat) ->
122− so (offset + size <= i) ->
123− { [RAW_MEMORY (MemoryChunk n i)] } Eff m (Vect size Bits8)
124−peek offset size prf = call $ Peek offset size prf
125−
126−poke : {n : Nat} ->
127− {i : Nat} ->
128− (offset : Nat) ->
129− Vect size Bits8 ->
130− so (offset <= i && offset + size <= n) ->
131− Eff m () [RAW_MEMORY (MemoryChunk n i)]
132− (\v => [RAW_MEMORY (MemoryChunk n (max i (offset + size)))])
133−poke offset content prf = call $ Poke offset content prf
134−
135−private
136−getRawPtr : { [RAW_MEMORY (MemoryChunk n i)] } Eff m (MemoryChunk n i)
137−getRawPtr = call $ GetRawPtr
138−
139−private
140−move' : {dst_size : Nat} ->
141− {dst_init : Nat} ->
142− {src_init : Nat} ->
143− (src_ptr : MemoryChunk src_size src_init) ->
144− (dst_offset : Nat) ->
145− (src_offset : Nat) ->
146− (size : Nat) ->
147− so (dst_offset <= dst_init && dst_offset + size <= dst_size) ->
148− so (src_offset + size <= src_init) ->
149− Eff m () [RAW_MEMORY (MemoryChunk dst_size dst_init)]
150− (\v => [RAW_MEMORY (MemoryChunk dst_size (max dst_init (dst_offset + size)))])
151−move' src_ptr dst_offset src_offset size dst_bounds src_bounds
152− = call $ Move src_ptr dst_offset src_offset size dst_bounds src_bounds
153−
154−data MoveDescriptor = Dst | Src
155−
156−move : {dst_size : Nat} ->
157− {dst_init : Nat} ->
158− {src_size : Nat} ->
159− {src_init : Nat} ->
160− (dst_offset : Nat) ->
161− (src_offset : Nat) ->
162− (size : Nat) ->
163− so (dst_offset <= dst_init && dst_offset + size <= dst_size) ->
164− so (src_offset + size <= src_init) ->
165− Eff m ()
166− [ Dst ::: RAW_MEMORY (MemoryChunk dst_size dst_init)
167− , Src ::: RAW_MEMORY (MemoryChunk src_size src_init)]
168− (\v =>
169− [ Dst ::: RAW_MEMORY (MemoryChunk dst_size (max dst_init (dst_offset + size)))
170− , Src ::: RAW_MEMORY (MemoryChunk src_size src_init)])
171−move dst_offset src_offset size dst_bounds src_bounds
172− = do src_ptr <- Src :- getRawPtr
173− Dst :- move' src_ptr dst_offset src_offset size dst_bounds src_bounds
174− pure ()
175−
libs/oldeffects/Effect/Monad.idrdeleted−21
@@ -1,21 +0,0 @@
1−module Effect.Monad
2−
3−import Effects
4−
5−-- Eff is a monad too, so we can happily use it in a monad transformer.
6−
7−using (xs : List EFFECT, m : Type -> Type)
8− implementation Functor (\a => EffM m a xs (\v => xs)) where
9− map f prog = do t <- prog
10− value (f t)
11−
12− implementation Applicative (\a => EffM m a xs (\v => xs)) where
13− pure = value
14− (<*>) f a = do f' <- f
15− a' <- a
16− value (f' a')
17−
18− implementation Monad (\a => Eff m a xs (\v => xs)) where
19− (>>=) = Effects.(>>=)
20−
21−
libs/oldeffects/Effect/Random.idrdeleted−47
@@ -1,47 +0,0 @@
1−module Effect.Random
2−
3−import Effects
4−
5−data Random : Effect where
6− getRandom : { Integer } Random Integer
7− setSeed : Integer -> { Integer } Random ()
8−
9−using (m : Type -> Type)
10− implementation Handler Random m where
11− handle seed getRandom k
12− = let seed' = assert_total ((1664525 * seed + 1013904223) `prim__sremBigInt` (pow 2 32)) in
13− k seed' seed'
14− handle seed (setSeed n) k = k () n
15−
16−RND : EFFECT
17−RND = MkEff Integer Random
18−
19−||| Generates a random Integer in a given range
20−rndInt : Integer -> Integer -> { [RND] } Eff m Integer
21−rndInt lower upper = do v <- call $ getRandom
22− pure (v `prim__sremBigInt` (upper - lower) + lower)
23−
24−||| Generate a random number in Fin (S `k`)
25−|||
26−||| Note that rndFin k takes values 0, 1, ..., k.
27−rndFin : (k : Nat) -> { [RND] } Eff m (Fin (S k))
28−rndFin k = do let v = assert_total $ !(call getRandom) `prim__sremBigInt` (cast (S k))
29− pure (toFin v)
30− where toFin : Integer -> Fin (S k)
31− toFin x = case integerToFin x (S k) of
32− Just v => v
33− Nothing => toFin (assert_smaller x (x - cast (S k)))
34−
35−||| Select a random element from a vector
36−rndSelect' : Vect (S k) a -> { [RND] } Eff IO a
37−rndSelect' {k} xs = pure (Vect.index !(rndFin k) xs)
38−
39−||| Select a random element from a list, or Nothing if the list is empty
40−rndSelect : List a -> { [RND] } Eff IO (Maybe a)
41−rndSelect [] = pure Nothing
42−rndSelect (x::xs) = pure (Just !(rndSelect' (x::(fromList xs))))
43−
44−||| Sets the random seed
45−srand : Integer -> { [RND] } Eff m ()
46−srand n = call $ setSeed n
47−
libs/oldeffects/Effect/Select.idrdeleted−23
@@ -1,23 +0,0 @@
1−module Effect.Select
2−
3−import Effects
4−
5−data Selection : Effect where
6− Select : List a -> { () } Selection a
7−
8−implementation Handler Selection Maybe where
9− handle _ (Select xs) k = tryAll xs where
10− tryAll [] = Nothing
11− tryAll (x :: xs) = case k x () of
12− Nothing => tryAll xs
13− Just v => Just v
14−
15−implementation Handler Selection List where
16− handle r (Select xs) k = concatMap (\x => k x r) xs
17−
18−SELECT : EFFECT
19−SELECT = MkEff () Selection
20−
21−select : List a -> { [SELECT] } Eff m a
22−select xs = call $ Select xs
23−
libs/oldeffects/Effect/State.idrdeleted−40
@@ -1,40 +0,0 @@
1−module Effect.State
2−
3−import Effects
4−
5−%access public
6−
7−data State : Effect where
8− Get : { a } State a
9− Put : b -> { a ==> b } State ()
10−
11−using (m : Type -> Type)
12− implementation Handler State m where
13− handle st Get k = k st st
14− handle st (Put n) k = k () n
15−
16−STATE : Type -> EFFECT
17−STATE t = MkEff t State
18−
19−get : { [STATE x] } Eff m x
20−get = call $ Get
21−
22−put : x -> { [STATE x] } Eff m ()
23−put val = call $ Put val
24−
25−putM : y -> { [STATE x] ==> [STATE y] } Eff m ()
26−putM val = call $ Put val
27−
28−update : (x -> x) -> { [STATE x] } Eff m ()
29−update f = put (f !get)
30−
31−updateM : (x -> y) -> { [STATE x] ==> [STATE y] } Eff m ()
32−updateM f = putM (f !get)
33−
34−locally : x -> ({ [STATE x] } Eff m t) -> { [STATE y] } Eff m t
35−locally newst prog = do st <- get
36− putM newst
37− val <- prog
38− putM st
39− pure val
40−
libs/oldeffects/Effect/StdIO.idrdeleted−60
@@ -1,60 +0,0 @@
1−module Effect.StdIO
2−
3−import Effects
4−import Control.IOExcept
5−
6−-------------------------------------------------------------
7−-- IO effects internals
8−-------------------------------------------------------------
9−
10−||| The internal representation of StdIO effects
11−data StdIO : Effect where
12− PutStr : String -> { () } StdIO ()
13− GetStr : { () } StdIO String
14− PutCh : Char -> { () } StdIO ()
15− GetCh : { () } StdIO Char
16−
17−
18−-------------------------------------------------------------
19−-- IO effects handlers
20−-------------------------------------------------------------
21−
22−implementation Handler StdIO IO where
23− handle () (PutStr s) k = do putStr s; k () ()
24− handle () GetStr k = do x <- getLine; k x ()
25− handle () (PutCh c) k = do putChar c; k () ()
26− handle () GetCh k = do x <- getChar; k x ()
27−
28−implementation Handler StdIO (IOExcept a) where
29− handle () (PutStr s) k = do ioe_lift $ putStr s; k () ()
30− handle () GetStr k = do x <- ioe_lift $ getLine; k x ()
31− handle () (PutCh c) k = do ioe_lift $ putChar c; k () ()
32− handle () GetCh k = do x <- ioe_lift $ getChar; k x ()
33−
34−-------------------------------------------------------------
35−--- The Effect and associated functions
36−-------------------------------------------------------------
37−
38−STDIO : EFFECT
39−STDIO = MkEff () StdIO
40−
41−||| Write a string to standard output.
42−putStr : String -> { [STDIO] } Eff e ()
43−putStr s = call $ PutStr s
44−
45−||| Write a character to standard output.
46−putChar : Char -> { [STDIO] } Eff e ()
47−putChar c = call $ PutCh c
48−
49−||| Write a string to standard output, terminating with a newline.
50−putStrLn : String -> { [STDIO] } Eff e ()
51−putStrLn s = putStr (s ++ "\n")
52−
53−||| Read a string from standard input.
54−getStr : { [STDIO] } Eff e String
55−getStr = call $ GetStr
56−
57−||| Read a character from standard input.
58−getChar : { [STDIO] } Eff e Char
59−getChar = call $ GetCh
60−
libs/oldeffects/Effect/System.idrdeleted−43
@@ -1,43 +0,0 @@
1−module Effect.System
2−
3−-- Various system interaction features (this is not necessarily the right way
4−-- to split them up, I just need some of them now :))
5−
6−import Effects
7−import System
8−import Control.IOExcept
9−
10−data System : Effect where
11− Args : { () } System (List String)
12− Time : { () } System Int
13− GetEnv : String -> { () } System (Maybe String)
14− CSystem : String -> { () } System Int
15−
16−implementation Handler System IO where
17− handle () Args k = do x <- getArgs; k x ()
18− handle () Time k = do x <- time; k x ()
19− handle () (GetEnv s) k = do x <- getEnv s; k x ()
20− handle () (CSystem s) k = do x <- system s; k x ()
21−
22−implementation Handler System (IOExcept a) where
23− handle () Args k = do x <- ioe_lift getArgs; k x ()
24− handle () Time k = do x <- ioe_lift time; k x ()
25− handle () (GetEnv s) k = do x <- ioe_lift $ getEnv s; k x ()
26− handle () (CSystem s) k = do x <- ioe_lift $ system s; k x ()
27−
28−--- The Effect and associated functions
29−
30−SYSTEM : EFFECT
31−SYSTEM = MkEff () System
32−
33−getArgs : Handler System e => { [SYSTEM] } Eff e (List String)
34−getArgs = call Args
35−
36−time : Handler System e => { [SYSTEM] } Eff e Int
37−time = call Time
38−
39−getEnv : Handler System e => String -> { [SYSTEM] } Eff e (Maybe String)
40−getEnv s = call $ GetEnv s
41−
42−system : Handler System e => String -> { [SYSTEM] } Eff e Int
43−system s = call $ CSystem s
libs/oldeffects/Effects.idrdeleted−333
@@ -1,333 +0,0 @@
1−module Effects
2−
3−import Language.Reflection
4−import Control.Catchable
5−import Effect.Default
6−
7−--- Effectful computations are described as algebraic data types that
8−--- explain how an effect is interpreted in some underlying context.
9−
10−%access public
11−-- ----------------------------------------------------------------- [ Effects ]
12−||| The Effect type describes effectful computations.
13−|||
14−||| This type is parameterised by:
15−||| + The input resource.
16−||| + The return type of the computation.
17−||| + The computation to run on the resource.
18−Effect : Type
19−Effect = (x : Type) -> Type -> (x -> Type) -> Type
20−
21−||| The `EFFECT` Data type describes how to promote the Effect
22−||| description into a concrete effect.
23−%error_reverse
24−data EFFECT : Type where
25− MkEff : Type -> Effect -> EFFECT
26−
27−||| Handler interfaces describe how an effect `e` is translated to the
28−||| underlying computation context `m` for execution.
29−interface Handler (e : Effect) (m : Type -> Type) where
30− ||| How to handle the effect.
31− |||
32− ||| @ r The resource being handled.
33− ||| @ eff The effect to be applied.
34− ||| @ k The continuation to pass the result of the effect
35− covering handle : (r : res) -> (eff : e t res resk) ->
36− (k : ((x : t) -> resk x -> m a)) -> m a
37−
38−||| Get the resource type (handy at the REPL to find out about an effect)
39−resourceType : EFFECT -> Type
40−resourceType (MkEff t e) = t
41−
42−-- --------------------------------------------------------- [ Syntactic Sugar ]
43−
44−-- A bit of syntactic sugar ('syntax' is not very flexible so we only go
45−-- up to a small number of parameters...)
46−
47−-- No state transition
48−syntax "{" [inst] "}" [eff] = eff inst (\result => inst)
49−
50−-- The state transition is dependent on a result `b`, a bound variable.
51−syntax "{" [inst] "==>" "{" {b} "}" [outst] "}" [eff]
52− = eff inst (\b => outst)
53−
54−--- A simple state transition
55−syntax "{" [inst] "==>" [outst] "}" [eff] = eff inst (\result => outst)
56−
57−-- --------------------------------------- [ Properties and Proof Construction ]
58−using (xs : List a, ys : List a)
59− data SubList : List a -> List a -> Type where
60− SubNil : SubList {a} [] []
61− Keep : SubList xs ys -> SubList (x :: xs) (x :: ys)
62− Drop : SubList xs ys -> SubList xs (x :: ys)
63−
64− subListId : SubList xs xs
65− subListId {xs = Nil} = SubNil
66− subListId {xs = x :: xs} = Keep subListId
67−
68−namespace Env
69− data Env : (m : Type -> Type) -> List EFFECT -> Type where
70− Nil : Env m Nil
71− (::) : Handler eff m => a -> Env m xs -> Env m (MkEff a eff :: xs)
72−
73−data EffElem : Effect -> Type ->
74− List EFFECT -> Type where
75− Here : EffElem x a (MkEff a x :: xs)
76− There : EffElem x a xs -> EffElem x a (y :: xs)
77−
78−||| make an environment corresponding to a sub-list
79−dropEnv : Env m ys -> SubList xs ys -> Env m xs
80−dropEnv [] SubNil = []
81−dropEnv (v :: vs) (Keep rest) = v :: dropEnv vs rest
82−dropEnv (v :: vs) (Drop rest) = dropEnv vs rest
83−
84−updateWith : (ys' : List a) -> (xs : List a) ->
85− SubList ys xs -> List a
86−updateWith (y :: ys) (x :: xs) (Keep rest) = y :: updateWith ys xs rest
87−updateWith ys (x :: xs) (Drop rest) = x :: updateWith ys xs rest
88−updateWith [] [] SubNil = []
89−updateWith (y :: ys) [] SubNil = y :: ys
90−updateWith [] (x :: xs) (Keep rest) = []
91−
92−||| Put things back, replacing old with new in the sub-environment
93−rebuildEnv : Env m ys' -> (prf : SubList ys xs) ->
94− Env m xs -> Env m (updateWith ys' xs prf)
95−rebuildEnv [] SubNil env = env
96−rebuildEnv (x :: xs) SubNil env = x :: xs
97−rebuildEnv [] (Keep rest) (y :: env) = []
98−rebuildEnv (x :: xs) (Keep rest) (y :: env) = x :: rebuildEnv xs rest env
99−rebuildEnv xs (Drop rest) (y :: env) = y :: rebuildEnv xs rest env
100−
101−
102−-- -------------------------------------------------- [ The Effect EDSL itself ]
103−
104−updateResTy : (val : t) ->
105− (xs : List EFFECT) -> EffElem e a xs -> e t a b ->
106− List EFFECT
107−updateResTy {b} val (MkEff a e :: xs) Here n = (MkEff (b val) e) :: xs
108−updateResTy val (x :: xs) (There p) n = x :: updateResTy val xs p n
109−
110−infix 5 :::, :-, :=
111−
112−data LRes : lbl -> Type -> Type where
113− (:=) : (x : lbl) -> res -> LRes x res
114−
115−(:::) : lbl -> EFFECT -> EFFECT
116−(:::) {lbl} x (MkEff r e) = MkEff (LRes x r) e
117−
118−using (lbl : Type)
119− implementation Default a => Default (LRes lbl a) where
120− default = lbl := default
121−
122−private
123−unlabel : {l : ty} -> Env m [l ::: x] -> Env m [x]
124−unlabel {m} {x = MkEff a eff} [l := v] = [v]
125−
126−private
127−relabel : (l : ty) -> Env m xs -> Env m (map (\x => l ::: x) xs)
128−relabel {xs = []} l [] = []
129−relabel {xs = (MkEff a e :: xs)} l (v :: vs) = (l := v) :: relabel l vs
130−
131−-- ------------------------------------------------- [ The Language of Effects ]
132−||| Definition of an Effect.
133−|||
134−||| @ m The computation context
135−||| @ x The return type of the result.
136−||| @ es The list of allowed side-effects.
137−||| @ ce Function to compute a new list of allowed side-effects.
138−data Eff : (m : Type -> Type)
139− -> (x : Type)
140− -> (es : List EFFECT)
141− -> (ce : x -> List EFFECT) -> Type where
142− value : a -> Eff m a xs (\v => xs)
143− with_val : (val : a) -> Eff m () xs (\v => xs' val) ->
144− Eff m a xs xs'
145− ebind : Eff m a xs xs' ->
146− ((val : a) -> Eff m b (xs' val) xs'') -> Eff m b xs xs''
147− callP : (prf : EffElem e a xs) ->
148− (eff : e t a b) ->
149− Eff m t xs (\v => updateResTy v xs prf eff)
150−
151− liftP : (prf : SubList ys xs) ->
152− Eff m t ys ys' -> Eff m t xs (\v => updateWith (ys' v) xs prf)
153− newInit : Handler e m =>
154− res ->
155− Eff m a (MkEff res e :: xs) (\v => (MkEff res' e :: xs')) ->
156− Eff m a xs (\v => xs')
157− catch : Catchable m err =>
158− Eff m a xs xs' -> (err -> Eff m a xs xs') ->
159− Eff m a xs xs'
160−
161− (:-) : (l : ty) ->
162− Eff m t [x] xs' -> -- [x] (\v => xs) ->
163− Eff m t [l ::: x] (\v => map (l :::) (xs' v))
164−
165−(>>=) : Eff m a xs xs' ->
166− ((val : a) -> Eff m b (xs' val) xs'') -> Eff m b xs xs''
167−(>>=) = ebind
168−
169−-- namespace SimpleBind
170−-- (>>=) : Eff m a xs (\v => xs) ->
171−-- ((val : a) -> Eff m b xs xs') -> Eff m b xs xs'
172−-- (>>=) = ebind
173−
174−||| Run a subprogram which results in an effect state the same as the input.
175−staticEff : Eff m a xs (\v => xs) -> Eff m a xs (\v => xs)
176−staticEff = id
177−
178−||| Explicitly give the expected set of result effects for an effectful
179−||| operation.
180−toEff : .(xs' : List EFFECT) -> Eff m a xs (\v => xs') -> Eff m a xs (\v => xs')
181−toEff xs' = id
182−
183−return : a -> Eff m a xs (\v => xs)
184−return x = value x
185−
186−-- ------------------------------------------------------ [ for idiom brackets ]
187−
188−infixl 2 <*>
189−
190−pure : a -> Eff m a xs (\v => xs)
191−pure = value
192−
193−syntax pureM [val] = with_val val (pure ())
194−
195−(<*>) : Eff m (a -> b) xs (\v => xs) ->
196− Eff m a xs (\v => xs) -> Eff m b xs (\v => xs)
197−(<*>) prog v = do fn <- prog
198− arg <- v
199− return (fn arg)
200−
201−-- ---------------------------------------------------------- [ an interpreter ]
202−
203−private
204−execEff : Env m xs -> (p : EffElem e res xs) ->
205− (eff : e a res resk) ->
206− ((v : a) -> Env m (updateResTy v xs p eff) -> m t) -> m t
207−execEff (val :: env) Here eff' k
208− = handle val eff' (\v, res => k v (res :: env))
209−-- FIXME: Teach the elaborator to propagate parameters here
210−execEff {e} {a} {res} {resk} (val :: env) (There p) eff k
211− = execEff {e} {a} {res} {resk} env p eff (\v, env' => k v (val :: env'))
212−
213−-- Q: Instead of m b, implement as StateT (Env m xs') m b, so that state
214−-- updates can be propagated even through failing computations?
215−
216−eff : Env m xs -> Eff m a xs xs' -> ((x : a) -> Env m (xs' x) -> m b) -> m b
217−eff env (value x) k = k x env
218−eff env (with_val x prog) k = eff env prog (\p', env' => k x env')
219−eff env (prog `ebind` c) k
220− = eff env prog (\p', env' => eff env' (c p') k)
221−eff env (callP prf effP) k = execEff env prf effP k
222−eff env (liftP prf effP) k
223− = let env' = dropEnv env prf in
224− eff env' effP (\p', envk => k p' (rebuildEnv envk prf env))
225−eff env (newInit r prog) k
226− = eff (r :: env) prog (\p' => \ (v :: envk) => k p' envk)
227−eff env (catch prog handler) k
228− = catch (eff env prog k)
229− (\e => eff env (handler e) k)
230−-- FIXME:
231−-- xs is needed explicitly because otherwise the pattern binding for
232−-- 'l' appears too late. Solution seems to be to reorder patterns at the
233−-- end so that everything is in scope when it needs to be.
234−eff {xs = [l ::: x]} env (l :- prog) k
235− = let env' = unlabel env in
236− eff env' prog (\p', envk => k p' (relabel l envk))
237−
238−-- yuck :) Haven't got interface implementations working nicely in tactic
239−-- proofs yet, and 'search' can't be told about any hints yet,
240−-- so just brute force it.
241−syntax MkDefaultEnv = with Env
242− (| [], [default], [default, default],
243− [default, default, default],
244− [default, default, default, default],
245− [default, default, default, default, default],
246− [default, default, default, default, default, default],
247− [default, default, default, default, default, default, default],
248− [default, default, default, default, default, default, default, default] |)
249−
250−call : {a, b: _} -> {e : Effect} ->
251− (eff : e t a b) ->
252− {auto prf : EffElem e a xs} ->
253− Eff m t xs (\v => updateResTy v xs prf eff)
254−call e {prf} = callP prf e
255−
256−implicit
257−lift : Eff m t ys ys' ->
258− {auto prf : SubList ys xs} ->
259− Eff m t xs (\v => updateWith (ys' v) xs prf)
260−lift e {prf} = liftP prf e
261−
262−
263−new : Handler e m =>
264− {default default r : res} ->
265− Eff m a (MkEff res e :: xs) (\v => (MkEff res' e :: xs')) ->
266− Eff m a xs (\v => xs')
267−new {r} e = newInit r e
268−
269−-- --------------------------------------------------------- [ Running Effects ]
270−
271−||| Run an effectful program.
272−|||
273−||| The content (`m`) in which to run the program is taken from the environment in which the program is called.
274−||| The `env` argument is implicit and initialised automatically.
275−|||
276−||| @prog The effectful program to run.
277−run : Applicative m => {default MkDefaultEnv env : Env m xs} -> (prog : Eff m a xs xs') -> m a
278−run {env} prog = eff env prog (\r, env => pure r)
279−
280−||| Run an effectful program in the identity context `id`.
281−|||
282−||| A helper function useful for when the given context is 'pure'.
283−||| The `env` argument is implicit and initialised automatically.
284−|||
285−||| @prog The effectful program to run.
286−runPure : {default MkDefaultEnv env : Env id xs} -> (prog : Eff id a xs xs') -> a
287−runPure {env} prog = eff env prog (\r, env => r)
288−
289−||| Run an effectful program with a default value for the environment context.
290−|||
291−||| This is useful for when no default value exists for a given resource type.
292−|||
293−||| @val The default value for the resource type.
294−||| @prog The effectful program to run.
295−runInit : Applicative m => (val : Env m xs) -> (prog : Eff m a xs xs') -> m a
296−runInit env prog = eff env prog (\r, env => pure r)
297−
298−||| Run an effectful program in the identity context `id` with a given default value for the environment context.
299−|||
300−||| A helper function useful for when the given context is 'pure'.
301−|||
302−||| @val The default value for the resource type.
303−||| @prog The effectful program to run.
304−runPureInit : (val : Env id xs) -> (prog : Eff id a xs xs') -> a
305−runPureInit env prog = eff env prog (\r, env => r)
306−
307−runWith : (a -> m a) -> Env m xs -> Eff m a xs xs' -> m a
308−runWith inj env prog = eff env prog (\r, env => inj r)
309−
310−runEnv : Applicative m => Env m xs -> Eff m a xs xs' ->
311− m (x : a ** Env m (xs' x))
312−runEnv env prog = eff env prog (\r, env => pure (r ** env))
313−
314−-- ----------------------------------------------- [ some higher order things ]
315−
316−mapE : Applicative m => (a -> {xs} Eff m b) -> List a -> {xs} Eff m (List b)
317−mapE f [] = pure []
318−mapE f (x :: xs) = [| f x :: mapE f xs |]
319−
320−
321−mapVE : Applicative m =>
322− (a -> {xs} Eff m b) ->
323− Vect n a ->
324− {xs} Eff m (Vect n b)
325−mapVE f [] = pure []
326−mapVE f (x :: xs) = [| f x :: mapVE f xs |]
327−
328−
329−when : Applicative m => Bool -> Lazy ({xs} Eff m ()) -> {xs} Eff m ()
330−when True e = Force e
331−when False e = pure ()
332−
333−-- --------------------------------------------------------------------- [ EOF ]
libs/oldeffects/Makefiledeleted−22
@@ -1,22 +0,0 @@
1−IDRIS := idris
2−
3−PKG := effects
4−
5−build:
6− $(IDRIS) --build ${PKG}.ipkg
7−
8−clean:
9− $(IDRIS) --clean ${PKG}.ipkg
10−
11−install:
12− $(IDRIS) --install ${PKG}.ipkg
13−
14−rebuild: clean build
15−
16−doc:
17− $(IDRIS) --mkdoc ${PKG}.ipkg
18−
19−doc_clean:
20− rm -rf ${PKG}_doc
21−
22−.PHONY: build clean install rebuild doc doc_clean
libs/oldeffects/effects.ipkgdeleted−9
@@ -1,9 +0,0 @@
1−package oldeffects
2−
3−opts = "--nobasepkgs -i ../prelude -i ../base"
4−modules = Effects, Effect.Default,
5−
6− Effect.Exception, Effect.File, Effect.State,
7− Effect.Random, Effect.StdIO, Effect.Select,
8− Effect.Memory, Effect.System
9−
libs/prelude/Prelude/Nat.idr+3
@@ -25,6 +25,9 @@ import Prelude.Uninhabited
25
25
26Uninhabited (Z = S n) where
26Uninhabited (Z = S n) where
27 uninhabited Refl impossible
27 uninhabited Refl impossible
28+
29+Uninhabited (S n = Z) where
30+ uninhabited Refl impossible
28
31
29--------------------------------------------------------------------------------
32--------------------------------------------------------------------------------
30-- Syntactic tests
33-- Syntactic tests
libs/prelude/prelude.ipkg+33−13
@@ -1,17 +1,37 @@
1package prelude
1package prelude
2
2
3opts = "--nobuiltins --total --no-elim-deprecation-warnings --partial-eval"
3opts = "--nobuiltins --total --no-elim-deprecation-warnings --partial-eval"
4−modules = Builtins, Prelude, IO,
5
4
5+modules = Builtins
6+ , Decidable.Equality
7+ , IO
8+ , Language.Reflection
9+ , Language.Reflection.Elab
10+ , Language.Reflection.Errors
11+ , Prelude
6− Prelude.Algebra, Prelude.Basics, Prelude.Bool, Prelude.Cast,
12+ , Prelude.Algebra
13+ , Prelude.Applicative
14+ , Prelude.Basics
15+ , Prelude.Bits
16+ , Prelude.Bool
17+ , Prelude.Cast
18+ , Prelude.Chars
19+ , Prelude.Doubles
20+ , Prelude.Either
21+ , Prelude.File
22+ , Prelude.Foldable
23+ , Prelude.Functor
24+ , Prelude.Interactive
7− Prelude.Interfaces, Prelude.Nat, Prelude.List,
25+ , Prelude.Interfaces
8− Prelude.Maybe, Prelude.Monad, Prelude.Applicative, Prelude.Either,
26+ , Prelude.List
27+ , Prelude.Maybe
28+ , Prelude.Monad
29+ , Prelude.Nat
30+ , Prelude.Pairs
31+ , Prelude.Providers
32+ , Prelude.Show
33+ , Prelude.Stream
9− Prelude.Strings, Prelude.Chars, Prelude.Show, Prelude.Functor,
34+ , Prelude.Strings
10− Prelude.Foldable, Prelude.Traversable, Prelude.Bits, Prelude.Stream,
35+ , Prelude.Traversable
11− Prelude.Uninhabited, Prelude.Pairs, Prelude.Providers,
36+ , Prelude.Uninhabited
12− Prelude.Interactive, Prelude.File, Prelude.Doubles,
13− Prelude.WellFounded,
37+ , Prelude.WellFounded
14−
15− Language.Reflection, Language.Reflection.Errors, Language.Reflection.Elab,
16−
17− Decidable.Equality
libs/pruviloj/pruviloj.ipkg+2−1
@@ -1,6 +1,7 @@
1package pruviloj
1package pruviloj
2
2
3−opts = "--nobasepkgs --partial-eval -i ../prelude -i ../base"
3+opts = "--nobasepkgs --partial-eval -i ../prelude -i ../base"
4+
4modules = Pruviloj
5modules = Pruviloj
5 , Pruviloj.Core
6 , Pruviloj.Core
6 , Pruviloj.Derive.DecEq
7 , Pruviloj.Derive.DecEq
rts/idris_gc.c+15−3
@@ -5,7 +5,7 @@
5#include <assert.h>
5#include <assert.h>
6
6
7VAL copy(VM* vm, VAL x) {
7VAL copy(VM* vm, VAL x) {
8− int ar;
8+ int ar, len;
9 Closure* cl = NULL;
9 Closure* cl = NULL;
10 if (x==NULL || ISINT(x)) {
10 if (x==NULL || ISINT(x)) {
11 return x;
11 return x;
@@ -20,6 +20,11 @@ VAL copy(VM* vm, VAL x) {
20 memcpy(&(cl->info.c.args), &(x->info.c.args), sizeof(VAL)*ar);
20 memcpy(&(cl->info.c.args), &(x->info.c.args), sizeof(VAL)*ar);
21 }
21 }
22 break;
22 break;
23+ case CT_ARRAY:
24+ len = x->info.arr.length;
25+ allocArray(cl, vm, len, 1);
26+ memcpy(&(cl->info.arr.content), &(x->info.arr.content), sizeof(VAL)*len);
27+ break;
23 case CT_FLOAT:
28 case CT_FLOAT:
24 cl = MKFLOATc(vm, x->info.f);
29 cl = MKFLOATc(vm, x->info.f);
25 break;
30 break;
@@ -58,7 +63,7 @@ VAL copy(VM* vm, VAL x) {
58 case CT_RAWDATA:
63 case CT_RAWDATA:
59 {
64 {
60 size_t size = x->info.size + sizeof(Closure);
65 size_t size = x->info.size + sizeof(Closure);
61− cl = allocate(size, 0);
66+ cl = allocate(size, 1);
62 memcpy(cl, x, size);
67 memcpy(cl, x, size);
63 }
68 }
64 break;
69 break;
@@ -76,7 +81,7 @@ VAL copy(VM* vm, VAL x) {
76
81
77void cheney(VM *vm) {
82void cheney(VM *vm) {
78 int i;
83 int i;
79− int ar;
84+ int ar, len;
80 char* scan = aligned_heap_pointer(vm->heap.heap);
85 char* scan = aligned_heap_pointer(vm->heap.heap);
81
86
82 while(scan < vm->heap.next) {
87 while(scan < vm->heap.next) {
@@ -91,6 +96,13 @@ void cheney(VM *vm) {
91 heap_item->info.c.args[i] = newptr;
96 heap_item->info.c.args[i] = newptr;
92 }
97 }
93 break;
98 break;
99+ case CT_ARRAY:
100+ len = heap_item->info.arr.length;
101+ for(i = 0; i < len; ++i) {
102+ VAL newptr = copy(vm, heap_item->info.arr.content[i]);
103+ heap_item->info.arr.content[i] = newptr;
104+ }
105+ break;
94 case CT_REF:
106 case CT_REF:
95 heap_item->info.ptr = copy(vm, (VAL)(heap_item->info.ptr));
107 heap_item->info.ptr = copy(vm, (VAL)(heap_item->info.ptr));
96 break;
108 break;
rts/idris_rts.c+30−2
@@ -714,7 +714,7 @@ VAL idris_strCons(VM* vm, VAL x, VAL xs) {
714 int xval = GETINT(x);
714 int xval = GETINT(x);
715 int xlen = GETSTRLEN(xs);
715 int xlen = GETSTRLEN(xs);
716
716
717− if ((xval & 0x80) == 0) { // ASCII char
717+ if (xval < 0x80) { // ASCII char
718 Closure* cl = allocate(sizeof(Closure) +
718 Closure* cl = allocate(sizeof(Closure) +
719 xlen + 2, 0);
719 xlen + 2, 0);
720 SETTY(cl, CT_STRING);
720 SETTY(cl, CT_STRING);
@@ -796,6 +796,24 @@ VAL idris_readRef(VAL ref) {
796 return (VAL)(ref->info.ptr);
796 return (VAL)(ref->info.ptr);
797}
797}
798
798
799+VAL idris_newArray(VM* vm, int size, VAL def) {
800+ Closure* cl;
801+ int i;
802+ allocArray(cl, vm, size, 0);
803+ for(i=0; i<size; ++i) {
804+ cl->info.arr.content[i] = def;
805+ }
806+ return cl;
807+}
808+
809+void idris_arraySet(VAL arr, int index, VAL newval) {
810+ arr->info.arr.content[index] = newval;
811+}
812+
813+VAL idris_arrayGet(VAL arr, int index) {
814+ return arr->info.arr.content[index];
815+}
816+
799VAL idris_systemInfo(VM* vm, VAL index) {
817VAL idris_systemInfo(VM* vm, VAL index) {
800 int i = GETINT(index);
818 int i = GETINT(index);
801 switch(i) {
819 switch(i) {
@@ -877,7 +895,7 @@ void* idris_stopThread(VM* vm) {
877// VM is assumed to be a different vm from the one x lives on
895// VM is assumed to be a different vm from the one x lives on
878
896
879VAL doCopyTo(VM* vm, VAL x) {
897VAL doCopyTo(VM* vm, VAL x) {
880− int i, ar;
898+ int i, ar, len;
881 VAL* argptr;
899 VAL* argptr;
882 Closure* cl;
900 Closure* cl;
883 if (x==NULL || ISINT(x)) {
901 if (x==NULL || ISINT(x)) {
@@ -898,6 +916,16 @@ VAL doCopyTo(VM* vm, VAL x) {
898 }
916 }
899 }
917 }
900 break;
918 break;
919+ case CT_ARRAY:
920+ len = x->info.arr.length;
921+ allocArray(cl, vm, len, 1);
922+
923+ argptr = (VAL*)(cl->info.arr.content);
924+ for(i = 0; i < len; ++i) {
925+ *argptr = doCopyTo(vm, *((VAL*)(x->info.arr.content)+i)); // recursive version
926+ argptr++;
927+ }
928+ break;
901 case CT_FLOAT:
929 case CT_FLOAT:
902 cl = MKFLOATc(vm, x->info.f);
930 cl = MKFLOATc(vm, x->info.f);
903 break;
931 break;
rts/idris_rts.h+22−1
@@ -25,18 +25,28 @@
25
25
26// Closures
26// Closures
27typedef enum {
27typedef enum {
28− CT_CON, CT_INT, CT_BIGINT, CT_FLOAT, CT_STRING, CT_STROFFSET,
28+ CT_CON, CT_ARRAY, CT_INT, CT_BIGINT, CT_FLOAT, CT_STRING, CT_STROFFSET,
29 CT_BITS8, CT_BITS16, CT_BITS32, CT_BITS64, CT_UNIT, CT_PTR, CT_REF,
29 CT_BITS8, CT_BITS16, CT_BITS32, CT_BITS64, CT_UNIT, CT_PTR, CT_REF,
30 CT_FWD, CT_MANAGEDPTR, CT_RAWDATA, CT_CDATA
30 CT_FWD, CT_MANAGEDPTR, CT_RAWDATA, CT_CDATA
31} ClosureType;
31} ClosureType;
32
32
33typedef struct Closure *VAL;
33typedef struct Closure *VAL;
34
34
35+// A constructor, consisting of a tag, an arity (16 bits each of the
36+// tag_arity field) and arguments
35typedef struct {
37typedef struct {
36 uint32_t tag_arity;
38 uint32_t tag_arity;
37 VAL args[];
39 VAL args[];
38} con;
40} con;
39
41
42+// An array; similar to a constructor but with a length, and contents
43+// initialised to NULL (high level Idris programs are responsible for
44+// initialising them properly)
45+typedef struct {
46+ uint32_t length;
47+ VAL content[];
48+} array;
49+
40typedef struct {
50typedef struct {
41 VAL str;
51 VAL str;
42 size_t offset;
52 size_t offset;
@@ -62,6 +72,7 @@ typedef struct Closure {
62 uint32_t ty;
72 uint32_t ty;
63 union {
73 union {
64 con c;
74 con c;
75+ array arr;
65 int i;
76 int i;
66 double f;
77 double f;
67 String str;
78 String str;
@@ -312,6 +323,11 @@ void idris_free(void* ptr, size_t size);
312
323
313#define NULL_CON(x) nullary_cons[x]
324#define NULL_CON(x) nullary_cons[x]
314
325
326+#define allocArray(cl, vm, len, o) \
327+ cl = allocate(sizeof(Closure) + sizeof(VAL)*len, o); \
328+ SETTY(cl, CT_ARRAY); \
329+ cl->info.arr.length = len;
330+
315int idris_errno(void);
331int idris_errno(void);
316char* idris_showerror(int err);
332char* idris_showerror(int err);
317
333
@@ -407,6 +423,11 @@ VAL idris_newRef(VAL x);
407void idris_writeRef(VAL ref, VAL x);
423void idris_writeRef(VAL ref, VAL x);
408VAL idris_readRef(VAL ref);
424VAL idris_readRef(VAL ref);
409
425
426+// Support for IOArrays
427+VAL idris_newArray(VM* vm, int size, VAL def);
428+void idris_arraySet(VAL arr, int index, VAL newval);
429+VAL idris_arrayGet(VAL arr, int index);
430+
410// system infox
431// system infox
411// used indices:
432// used indices:
412// 0 returns backend
433// 0 returns backend
rts/idris_utf8.c+1−1
@@ -119,7 +119,7 @@ char* idris_utf8_fromChar(int x) {
119 char* str;
119 char* str;
120 int bytes = 0, top = 0;
120 int bytes = 0, top = 0;
121
121
122− if ((x & 0x80) == 0) {
122+ if (x < 0x80) {
123 str = malloc(2);
123 str = malloc(2);
124 str[0] = (char)x;
124 str[0] = (char)x;
125 str[1] = '\0';
125 str[1] = '\0';
samples/ST/Login.idr+1−1
@@ -41,7 +41,7 @@ DataStore IO where
41
41
42 disconnect store = delete store
42 disconnect store = delete store
43
43
44− readSecret store = readSecret store
44+ readSecret store = read store
45
45
46 login store = do putStr "Enter password: "
46 login store = do putStr "Enter password: "
47 p <- getStr
47 p <- getStr
src/Idris/AbsSyntaxTree.hs+9−5
@@ -1697,6 +1697,9 @@ pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1697 where
1697 where
1698 startPrec = 0
1698 startPrec = 0
1699 funcAppPrec = 10
1699 funcAppPrec = 10
1700+ lbrace = annotate (AnnSyntax "{") (text "{")
1701+ rbrace = annotate (AnnSyntax "}") (text "}")
1702+ percent = annotate (AnnSyntax "%") (text "%")
1700
1703
1701 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1704 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1702 prettySe d p bnd (PQuote r) =
1705 prettySe d p bnd (PQuote r) =
@@ -1709,7 +1712,8 @@ pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1709 prettySe d p bnd (PLam fc n nfc ty sc) =
1712 prettySe d p bnd (PLam fc n nfc ty sc) =
1710 let (ns, sc') = getLamNames [n] sc in
1713 let (ns, sc') = getLamNames [n] sc in
1711 depth d . bracket p startPrec . group . align . hang 2 $
1714 depth d . bracket p startPrec . group . align . hang 2 $
1715+ (annotate (AnnSyntax "\\") (text "\\"))
1712− text "\\" <> prettyBindingsOf ns False <+> text "=>" <$>
1716+ <> prettyBindingsOf ns False <+> text "=>" <$>
1713 prettySe (decD d) startPrec ((n, False):bnd) sc'
1717 prettySe (decD d) startPrec ((n, False):bnd) sc'
1714 where
1718 where
1715 getLamNames acc (PLam fc n nfc ty sc) = getLamNames (n : acc) sc
1719 getLamNames acc (PLam fc n nfc ty sc) = getLamNames (n : acc) sc
@@ -1749,7 +1753,7 @@ pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1749
1753
1750 st =
1754 st =
1751 case s of
1755 case s of
1752− Static -> text "%static" <> space
1756+ Static -> percent <> text "static" <> space
1753 _ -> empty
1757 _ -> empty
1754 prettySe d p bnd (PPi (Imp l s _ fa _ rig) n _ ty sc)
1758 prettySe d p bnd (PPi (Imp l s _ fa _ rig) n _ ty sc)
1755 | ppopt_impl ppo =
1759 | ppopt_impl ppo =
@@ -1769,7 +1773,7 @@ pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1769
1773
1770 st =
1774 st =
1771 case s of
1775 case s of
1772− Static -> text "%static" <> space
1776+ Static -> percent <> text "static" <> space
1773 _ -> empty
1777 _ -> empty
1774 prettySe d p bnd (PPi (Constraint _ _ rig) n _ ty sc) =
1778 prettySe d p bnd (PPi (Constraint _ _ rig) n _ ty sc) =
1775 depth d . bracket p startPrec $
1779 depth d . bracket p startPrec $
@@ -1876,7 +1880,7 @@ pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1876 , kwd "else" <+> prettySe (decD d) startPrec bnd f
1880 , kwd "else" <+> prettySe (decD d) startPrec bnd f
1877 ]
1881 ]
1878 prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
1882 prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
1879− prettySe d p bnd (PResolveTC _) = kwd "%implementation"
1883+ prettySe d p bnd (PResolveTC _) = percent <> kwd "implementation"
1880 prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1884 prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1881 prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1885 prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1882 prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
1886 prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
@@ -1981,7 +1985,7 @@ pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1981 end = if res then "}" else "}}"
1985 end = if res then "}" else "}}"
1982 prettySe d p bnd (PRunElab _ tm _) =
1986 prettySe d p bnd (PRunElab _ tm _) =
1983 bracket p funcAppPrec . group . align . hang 2 $
1987 bracket p funcAppPrec . group . align . hang 2 $
1984− text "%runElab" <$>
1988+ (percent <> text "runElab") <$>
1985 prettySe (decD d) funcAppPrec bnd tm
1989 prettySe (decD d) funcAppPrec bnd tm
1986 prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
1990 prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
1987 prettySe d p bnd _ = text "missing pretty-printer for term"
1991 prettySe d p bnd _ = text "missing pretty-printer for term"
src/Idris/Core/ProofState.hs−1
@@ -31,7 +31,6 @@ import Util.Pretty hiding (fill)
31import Control.Arrow ((***))
31import Control.Arrow ((***))
32import Control.Monad.State.Strict
32import Control.Monad.State.Strict
33import Data.List
33import Data.List
34−import Debug.Trace
35
34
36data ProofState = PS { thname :: Name,
35data ProofState = PS { thname :: Name,
37 holes :: [Name], -- ^ holes still to be solved
36 holes :: [Name], -- ^ holes still to be solved
src/Idris/Core/TT.hs+1
@@ -224,6 +224,7 @@ data OutputAnnotation = AnnName Name (Maybe NameOutput) (Maybe String) (Maybe St
224 -- from that file.
224 -- from that file.
225 | AnnQuasiquote
225 | AnnQuasiquote
226 | AnnAntiquote
226 | AnnAntiquote
227+ | AnnSyntax String -- ^ type of syntax element: backslash or braces etc.
227 deriving (Show, Eq, Generic)
228 deriving (Show, Eq, Generic)
228
229
229-- | Used for error reflection
230-- | Used for error reflection
src/Idris/Elab/Type.hs−1
@@ -16,7 +16,6 @@ import Idris.ASTUtils
16import Idris.Core.Elaborate hiding (Tactic(..))
16import Idris.Core.Elaborate hiding (Tactic(..))
17import Idris.Core.Evaluate
17import Idris.Core.Evaluate
18import Idris.Core.TT
18import Idris.Core.TT
19−import Idris.Core.WHNF
20import Idris.Docstrings (Docstring)
19import Idris.Docstrings (Docstring)
21import Idris.Elab.Term
20import Idris.Elab.Term
22import Idris.Elab.Utils
21import Idris.Elab.Utils
src/Idris/Elab/Utils.hs−1
@@ -26,7 +26,6 @@ import Control.Monad.State
26import Data.List
26import Data.List
27import qualified Data.Map as Map
27import qualified Data.Map as Map
28import Data.Maybe
28import Data.Maybe
29−import Debug.Trace
30
29
31recheckC = recheckC_borrowing False True []
30recheckC = recheckC_borrowing False True []
32
31
src/Idris/IBC.hs+2−2
@@ -144,9 +144,9 @@ loadIBC reexport phase fp
144 addImported reexport fp
144 addImported reexport fp
145
145
146-- | Load an entire package from its index file
146-- | Load an entire package from its index file
147−loadPkgIndex :: String -> Idris ()
147+loadPkgIndex :: PkgName -> Idris ()
148loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir
148loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir
149− addImportDir (ddir </> pkg)
149+ addImportDir (ddir </> unPkgName pkg)
150 fp <- findPkgIndex pkg
150 fp <- findPkgIndex pkg
151 loadIBC True IBC_Building fp
151 loadIBC True IBC_Building fp
152
152
src/Idris/IdeMode.hs+1
@@ -172,6 +172,7 @@ instance SExpable OutputAnnotation where
172 maybeProps [("source-file", file)]
172 maybeProps [("source-file", file)]
173 toSExp AnnQuasiquote = toSExp [(SymbolAtom "quasiquotation", True)]
173 toSExp AnnQuasiquote = toSExp [(SymbolAtom "quasiquotation", True)]
174 toSExp AnnAntiquote = toSExp [(SymbolAtom "antiquotation", True)]
174 toSExp AnnAntiquote = toSExp [(SymbolAtom "antiquotation", True)]
175+ toSExp (AnnSyntax c) = SexpList []
175
176
176encodeName :: Name -> String
177encodeName :: Name -> String
177encodeName n = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ n
178encodeName n = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ n
src/Idris/Imports.hs+27−3
@@ -8,6 +8,7 @@ Maintainer : The Idris Community.
8module Idris.Imports(
8module Idris.Imports(
9 IFileType(..), findIBC, findImport, findInPath, findPkgIndex
9 IFileType(..), findIBC, findImport, findInPath, findPkgIndex
10 , ibcPathNoFallback, installedPackages, pkgIndex
10 , ibcPathNoFallback, installedPackages, pkgIndex
11+ , PkgName, pkgName, unPkgName, unInitializedPkgName
11 ) where
12 ) where
12
13
13import Idris.AbsSyntax
14import Idris.AbsSyntax
@@ -17,6 +18,7 @@ import IRTS.System (getIdrisLibDir)
17
18
18import Control.Applicative ((<$>))
19import Control.Applicative ((<$>))
19import Control.Monad.State.Strict
20import Control.Monad.State.Strict
21+import Data.Char (isAlpha, isDigit, toLower)
20import Data.List (isSuffixOf)
22import Data.List (isSuffixOf)
21import System.Directory
23import System.Directory
22import System.FilePath
24import System.FilePath
@@ -24,9 +26,31 @@ import System.FilePath
24data IFileType = IDR FilePath | LIDR FilePath | IBC FilePath IFileType
26data IFileType = IDR FilePath | LIDR FilePath | IBC FilePath IFileType
25 deriving (Show, Eq)
27 deriving (Show, Eq)
26
28
29+newtype PkgName = PkgName String
30+
31+unPkgName :: PkgName -> String
32+unPkgName (PkgName s) = map toLower s
33+
34+instance Show PkgName where
35+ show (PkgName pkg) = pkg
36+instance Eq PkgName where
37+ a == b = unPkgName a == unPkgName b
38+
39+unInitializedPkgName :: PkgName
40+unInitializedPkgName = PkgName ""
41+
42+pkgName :: String -> Either String PkgName
43+pkgName "" = Left "empty package name"
44+pkgName s@(f:l)
45+ | not $ isAlpha f =
46+ Left "package name need to start by a letter"
47+ | not $ all (\c -> isAlpha c || isDigit c || c `elem` "-_") l =
48+ Left "package name need to contain only letter, digits, and -_"
49+ | otherwise = Right $ PkgName s
50+
27-- | Get the index file name for a package name
51-- | Get the index file name for a package name
28−pkgIndex :: String -> FilePath
52+pkgIndex :: PkgName -> FilePath
29−pkgIndex s = "00" ++ s ++ "-idx.ibc"
53+pkgIndex s = "00" ++ unPkgName s ++ "-idx.ibc"
30
54
31srcPath :: FilePath -> FilePath
55srcPath :: FilePath -> FilePath
32srcPath fp = let (_, ext) = splitExtension fp in
56srcPath fp = let (_, ext) = splitExtension fp in
@@ -96,7 +120,7 @@ findInPath (d:ds) fp = do let p = d </> fp
96 e <- doesFileExist' p
120 e <- doesFileExist' p
97 if e then return p else findInPath ds fp
121 if e then return p else findInPath ds fp
98
122
99−findPkgIndex :: String -> Idris FilePath
123+findPkgIndex :: PkgName -> Idris FilePath
100findPkgIndex p = do let idx = pkgIndex p
124findPkgIndex p = do let idx = pkgIndex p
101 ids <- allImportDirs
125 ids <- allImportDirs
102 runIO $ findInPath ids idx
126 runIO $ findInPath ids idx
src/Idris/Output.hs+8
@@ -318,6 +318,7 @@ renderExternal fmt width doc
318 \txt -> "<a href=\"" ++ url ++ "\">" ++ txt ++ "</a>"
318 \txt -> "<a href=\"" ++ url ++ "\">" ++ txt ++ "</a>"
319 decorate HTMLOutput AnnQuasiquote = id
319 decorate HTMLOutput AnnQuasiquote = id
320 decorate HTMLOutput AnnAntiquote = id
320 decorate HTMLOutput AnnAntiquote = id
321+ decorate HTMLOutput (AnnSyntax c) = \txt -> c
321
322
322 decorate LaTeXOutput (AnnName _ (Just TypeOutput) _ _) =
323 decorate LaTeXOutput (AnnName _ (Just TypeOutput) _ _) =
323 latex "IdrisType"
324 latex "IdrisType"
@@ -349,6 +350,13 @@ renderExternal fmt width doc
349 decorate LaTeXOutput (AnnLink url) = (++ "(\\url{" ++ url ++ "})")
350 decorate LaTeXOutput (AnnLink url) = (++ "(\\url{" ++ url ++ "})")
350 decorate LaTeXOutput AnnQuasiquote = id
351 decorate LaTeXOutput AnnQuasiquote = id
351 decorate LaTeXOutput AnnAntiquote = id
352 decorate LaTeXOutput AnnAntiquote = id
353+ decorate LaTeXOutput (AnnSyntax c) = \txt ->
354+ case c of
355+ "\\" -> "\\textbackslash"
356+ "{" -> "\\{"
357+ "}" -> "\\}"
358+ "%" -> "\\%"
359+ _ -> c
352
360
353 tag cls docs str = "<span class=\""++cls++"\""++title++">" ++ str ++ "</span>"
361 tag cls docs str = "<span class=\""++cls++"\""++title++">" ++ str ++ "</span>"
354 where title = maybe "" (\d->" title=\"" ++ d ++ "\"") docs
362 where title = maybe "" (\d->" title=\"" ++ d ++ "\"") docs
src/Idris/Package.hs+12−12
@@ -201,7 +201,7 @@ documentPkg copts (install,fp) = do
201 pkgdesc <- parseDesc fp
201 pkgdesc <- parseDesc fp
202 cd <- getCurrentDirectory
202 cd <- getCurrentDirectory
203 let pkgDir = cd </> takeDirectory fp
203 let pkgDir = cd </> takeDirectory fp
204− outputDir = cd </> pkgname pkgdesc ++ "_doc"
204+ outputDir = cd </> unPkgName (pkgname pkgdesc) ++ "_doc"
205 popts = NoREPL : Verbose 1 : idris_opts pkgdesc
205 popts = NoREPL : Verbose 1 : idris_opts pkgdesc
206 mods = modules pkgdesc
206 mods = modules pkgdesc
207 fs = map (foldl1' (</>) . splitOn "." . showCG) mods
207 fs = map (foldl1' (</>) . splitOn "." . showCG) mods
@@ -228,10 +228,10 @@ documentPkg copts (install,fp) = do
228 exitWith (ExitFailure 1)
228 exitWith (ExitFailure 1)
229 Right ist -> do
229 Right ist -> do
230 iDocDir <- getIdrisDocDir
230 iDocDir <- getIdrisDocDir
231− pkgDocDir <- makeAbsolute (iDocDir </> pkgname pkgdesc)
231+ pkgDocDir <- makeAbsolute (iDocDir </> unPkgName (pkgname pkgdesc))
232 let out_dir = if install then pkgDocDir else outputDir
232 let out_dir = if install then pkgDocDir else outputDir
233 when install $ do
233 when install $ do
234− putStrLn $ unwords ["Attempting to install IdrisDocs for", pkgname pkgdesc, "in:", out_dir]
234+ putStrLn $ unwords ["Attempting to install IdrisDocs for", show $ pkgname pkgdesc, "in:", out_dir]
235
235
236 docRes <- generateDocs ist mods out_dir
236 docRes <- generateDocs ist mods out_dir
237 case docRes of
237 case docRes of
@@ -356,7 +356,7 @@ buildMods opts ns = do let f = map (toPath . showCG) ns
356 where
356 where
357 toPath n = foldl1' (</>) $ splitOn "." n
357 toPath n = foldl1' (</>) $ splitOn "." n
358
358
359−testLib :: Bool -> String -> String -> IO Bool
359+testLib :: Bool -> PkgName -> String -> IO Bool
360testLib warn p f
360testLib warn p f
361 = do d <- getIdrisCRTSDir
361 = do d <- getIdrisCRTSDir
362 gcc <- getCC
362 gcc <- getCC
@@ -367,7 +367,7 @@ testLib warn p f
367 case e of
367 case e of
368 ExitSuccess -> return True
368 ExitSuccess -> return True
369 _ -> do if warn
369 _ -> do if warn
370− then do putStrLn $ "Not building " ++ p ++
370+ then do putStrLn $ "Not building " ++ show p ++
371 " due to missing library " ++ f
371 " due to missing library " ++ f
372 return False
372 return False
373 else fail $ "Missing library " ++ f
373 else fail $ "Missing library " ++ f
@@ -375,7 +375,7 @@ testLib warn p f
375rmIBC :: Name -> IO ()
375rmIBC :: Name -> IO ()
376rmIBC m = rmFile $ toIBCFile m
376rmIBC m = rmFile $ toIBCFile m
377
377
378−rmIdx :: String -> IO ()
378+rmIdx :: PkgName -> IO ()
379rmIdx p = do let f = pkgIndex p
379rmIdx p = do let f = pkgIndex p
380 ex <- doesFileExist f
380 ex <- doesFileExist f
381 when ex $ rmFile f
381 when ex $ rmFile f
@@ -389,10 +389,10 @@ rmExe p = do
389toIBCFile (UN n) = str n ++ ".ibc"
389toIBCFile (UN n) = str n ++ ".ibc"
390toIBCFile (NS n ns) = foldl1' (</>) (reverse (toIBCFile n : map str ns))
390toIBCFile (NS n ns) = foldl1' (</>) (reverse (toIBCFile n : map str ns))
391
391
392−installIBC :: String -> String -> Name -> IO ()
392+installIBC :: String -> PkgName -> Name -> IO ()
393installIBC dest p m = do
393installIBC dest p m = do
394 let f = toIBCFile m
394 let f = toIBCFile m
395− let destdir = dest </> p </> getDest m
395+ let destdir = dest </> unPkgName p </> getDest m
396 putStrLn $ "Installing " ++ f ++ " to " ++ destdir
396 putStrLn $ "Installing " ++ f ++ " to " ++ destdir
397 createDirectoryIfMissing True destdir
397 createDirectoryIfMissing True destdir
398 copyFile f (destdir </> takeFileName f)
398 copyFile f (destdir </> takeFileName f)
@@ -401,18 +401,18 @@ installIBC dest p m = do
401 getDest (UN n) = ""
401 getDest (UN n) = ""
402 getDest (NS n ns) = foldl1' (</>) (reverse (getDest n : map str ns))
402 getDest (NS n ns) = foldl1' (</>) (reverse (getDest n : map str ns))
403
403
404−installIdx :: String -> String -> IO ()
404+installIdx :: String -> PkgName -> IO ()
405installIdx dest p = do
405installIdx dest p = do
406 let f = pkgIndex p
406 let f = pkgIndex p
407− let destdir = dest </> p
407+ let destdir = dest </> unPkgName p
408 putStrLn $ "Installing " ++ f ++ " to " ++ destdir
408 putStrLn $ "Installing " ++ f ++ " to " ++ destdir
409 createDirectoryIfMissing True destdir
409 createDirectoryIfMissing True destdir
410 copyFile f (destdir </> takeFileName f)
410 copyFile f (destdir </> takeFileName f)
411 return ()
411 return ()
412
412
413−installObj :: String -> String -> String -> IO ()
413+installObj :: String -> PkgName -> String -> IO ()
414installObj dest p o = do
414installObj dest p o = do
415− let destdir = addTrailingPathSeparator (dest </> p)
415+ let destdir = addTrailingPathSeparator (dest </> unPkgName p)
416 putStrLn $ "Installing " ++ o ++ " to " ++ destdir
416 putStrLn $ "Installing " ++ o ++ " to " ++ destdir
417 createDirectoryIfMissing True destdir
417 createDirectoryIfMissing True destdir
418 copyFile o (destdir </> takeFileName o)
418 copyFile o (destdir </> takeFileName o)
src/Idris/Package/Common.hs+4−3
@@ -7,12 +7,13 @@ Maintainer : The Idris Community.
7module Idris.Package.Common where
7module Idris.Package.Common where
8
8
9import Idris.Core.TT (Name)
9import Idris.Core.TT (Name)
10+import Idris.Imports
10import Idris.Options (Opt(..))
11import Idris.Options (Opt(..))
11
12
12-- | Description of an Idris package.
13-- | Description of an Idris package.
13data PkgDesc = PkgDesc {
14data PkgDesc = PkgDesc {
14− pkgname :: String -- ^ Name associated with a package.
15+ pkgname :: PkgName -- ^ Name associated with a package.
15− , pkgdeps :: [String] -- ^ List of packages this package depends on.
16+ , pkgdeps :: [PkgName] -- ^ List of packages this package depends on.
16 , pkgbrief :: Maybe String -- ^ Brief description of the package.
17 , pkgbrief :: Maybe String -- ^ Brief description of the package.
17 , pkgversion :: Maybe String -- ^ Version string to associate with the package.
18 , pkgversion :: Maybe String -- ^ Version string to associate with the package.
18 , pkgreadme :: Maybe String -- ^ Location of the README file.
19 , pkgreadme :: Maybe String -- ^ Location of the README file.
@@ -35,6 +36,6 @@ data PkgDesc = PkgDesc {
35
36
36-- | Default settings for package descriptions.
37-- | Default settings for package descriptions.
37defaultPkg :: PkgDesc
38defaultPkg :: PkgDesc
38−defaultPkg = PkgDesc "" [] Nothing Nothing Nothing Nothing
39+defaultPkg = PkgDesc unInitializedPkgName [] Nothing Nothing Nothing Nothing
39 Nothing Nothing Nothing Nothing
40 Nothing Nothing Nothing Nothing
40 Nothing [] [] Nothing [] "" [] Nothing Nothing []
41 Nothing [] [] Nothing [] "" [] Nothing Nothing []
src/Idris/Package/Parser.hs+7−3
@@ -9,6 +9,7 @@ Maintainer : The Idris Community.
9module Idris.Package.Parser where
9module Idris.Package.Parser where
10
10
11import Idris.CmdOptions
11import Idris.CmdOptions
12+import Idris.Imports
12import Idris.Package.Common
13import Idris.Package.Common
13import Idris.Parser.Helpers hiding (stringLiteral)
14import Idris.Parser.Helpers hiding (stringLiteral)
14
15
@@ -64,7 +65,8 @@ parseDesc fp = do
64pPkg :: PParser PkgDesc
65pPkg :: PParser PkgDesc
65pPkg = do
66pPkg = do
66 reserved "package"
67 reserved "package"
67− p <- filename
68+ p <- pPkgName
69+ someSpace
68 st <- get
70 st <- get
69 put (st { pkgname = p })
71 put (st { pkgname = p })
70 some pClause
72 some pClause
@@ -72,6 +74,8 @@ pPkg = do
72 eof
74 eof
73 return st
75 return st
74
76
77+pPkgName :: PParser PkgName
78+pPkgName = (either fail pure . pkgName =<< packageName) <?> "PkgName"
75
79
76-- | Parses a filename.
80-- | Parses a filename.
77-- |
81-- |
@@ -139,9 +143,9 @@ pClause = do reserved "executable"; lchar '=';
139 put (st { idris_opts = args ++ idris_opts st })
143 put (st { idris_opts = args ++ idris_opts st })
140
144
141 <|> do reserved "pkgs"; lchar '=';
145 <|> do reserved "pkgs"; lchar '=';
142− ps <- sepBy1 (fst <$> identifier) (lchar ',')
146+ ps <- sepBy1 (pPkgName <* someSpace) (lchar ',')
143 st <- get
147 st <- get
144− let pkgs = pureArgParser $ concatMap (\x -> ["-p", x]) ps
148+ let pkgs = pureArgParser $ concatMap (\x -> ["-p", show x]) ps
145
149
146 put (st { pkgdeps = ps `union` (pkgdeps st)
150 put (st { pkgdeps = ps `union` (pkgdeps st)
147 , idris_opts = pkgs ++ idris_opts st})
151 , idris_opts = pkgs ++ idris_opts st})
src/Idris/Parser/Expr.hs+31−17
@@ -468,27 +468,41 @@ bracketed' open syn =
468 lchar ')'
468 lchar ')'
469 return $ PTrue (spanFC open (FC f start (l, c+1))) TypeOrTerm
469 return $ PTrue (spanFC open (FC f start (l, c+1))) TypeOrTerm
470 <|> try (dependentPair TypeOrTerm [] open syn)
470 <|> try (dependentPair TypeOrTerm [] open syn)
471− <|> try (do fc <- getFC; o <- operator; e <- expr syn; lchar ')'
471+ <|> try (do fc <- getFC
472− -- No prefix operators! (bit of a hack here...)
472+ opName <- operatorName
473− if (o == "-" || o == "!")
473+ guardNotPrefix opName
474− then fail "minus not allowed in section"
474+
475+ e <- expr syn
476+ lchar ')'
475− else return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder
477+ return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder
476− (PApp fc (PRef fc [] (sUN o)) [pexp (PRef fc [] (sMN 1000 "ARG")),
478+ (PApp fc (PRef fc [] opName) [pexp (PRef fc [] (sMN 1000 "ARG")),
477− pexp e]))
479+ pexp e]))
478− <|> try (do l <- simpleExpr syn
480+ <|> try (simpleExpr syn >>= \l ->
479− op <- option Nothing (do o <- operator
481+ try (do opName <- operatorName
480− lchar ')'
482+ lchar ')'
481− return (Just o))
483+ fc <- getFC
482− fc0 <- getFC
484+ return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder
483− case op of
485+ (PApp fc (PRef fc [] opName) [pexp l,
486+ pexp (PRef fc [] (sMN 1000 "ARG"))]))
484− Nothing -> bracketedExpr syn open l
487+ <|> bracketedExpr syn open l)
485− Just o -> return $ PLam fc0 (sMN 1000 "ARG") NoFC Placeholder
486− (PApp fc0 (PRef fc0 [] (sUN o)) [pexp l,
487− pexp (PRef fc0 [] (sMN 1000 "ARG"))]))
488 <|> do l <- expr (allowConstr syn)
488 <|> do l <- expr (allowConstr syn)
489 bracketedExpr (allowConstr syn) open l
489 bracketedExpr (allowConstr syn) open l
490+ where
491+ operatorName :: IdrisParser Name
492+ operatorName = sUN <$> operator
493+ <|> fst <$> between (lchar '`') (lchar '`') fnName
494+
495+ justPrefix :: FixDecl -> Maybe Name
496+ justPrefix (Fix (PrefixN _) opName) = Just (sUN opName)
497+ justPrefix _ = Nothing
490
498
499+ guardNotPrefix :: Name -> IdrisParser ()
500+ guardNotPrefix opName = do
501+ guard $ opName /= sUN "-"
502+ guard $ opName /= sUN "!"
491
503
504+ ops <- idris_infixes <$> get
505+ guard . not . (opName `elem`) . mapMaybe justPrefix $ ops
492
506
493{-| Parses the rest of a dependent pair after '(' or '(Expr **' -}
507{-| Parses the rest of a dependent pair after '(' or '(Expr **' -}
494dependentPair :: PunInfo -> [(PTerm, Maybe (FC, PTerm), FC)] -> FC -> SyntaxInfo -> IdrisParser PTerm
508dependentPair :: PunInfo -> [(PTerm, Maybe (FC, PTerm), FC)] -> FC -> SyntaxInfo -> IdrisParser PTerm
src/Idris/Parser/Helpers.hs+5
@@ -395,6 +395,11 @@ opChars = ":!#$%&*+./<=>?@\\^|-~"
395operatorLetter :: MonadicParsing m => m Char
395operatorLetter :: MonadicParsing m => m Char
396operatorLetter = oneOf opChars
396operatorLetter = oneOf opChars
397
397
398+-- | Parse a package name
399+packageName :: MonadicParsing m => m String
400+packageName = (:) <$> oneOf firstChars <*> many (oneOf remChars)
401+ where firstChars = ['a'..'z'] ++ ['A'..'Z']
402+ remChars = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['-','_']
398
403
399commentMarkers :: [String]
404commentMarkers :: [String]
400commentMarkers = [ "--", "|||" ]
405commentMarkers = [ "--", "|||" ]
src/Idris/REPL.hs+1−1
@@ -1373,7 +1373,7 @@ process fn (SetPrinterDepth d) = setDepth d
1373process fn (Apropos pkgs a) =
1373process fn (Apropos pkgs a) =
1374 do orig <- getIState
1374 do orig <- getIState
1375 when (not (null pkgs)) $
1375 when (not (null pkgs)) $
1376− iputStrLn $ "Searching packages: " ++ showSep ", " pkgs
1376+ iputStrLn $ "Searching packages: " ++ showSep ", " (map show pkgs)
1377 mapM_ loadPkgIndex pkgs
1377 mapM_ loadPkgIndex pkgs
1378 ist <- getIState
1378 ist <- getIState
1379 let mods = aproposModules ist (T.pack a)
1379 let mods = aproposModules ist (T.pack a)
src/Idris/REPL/Commands.hs+3−2
@@ -3,6 +3,7 @@ module Idris.REPL.Commands where
3import Idris.AbsSyntaxTree
3import Idris.AbsSyntaxTree
4import Idris.Colours
4import Idris.Colours
5import Idris.Core.TT
5import Idris.Core.TT
6+import Idris.Imports
6import Idris.Options
7import Idris.Options
7
8
8-- | REPL commands
9-- | REPL commands
@@ -43,7 +44,7 @@ data Command = Quit
43 | DynamicLink FilePath
44 | DynamicLink FilePath
44 | ListDynamic
45 | ListDynamic
45 | Pattelab PTerm
46 | Pattelab PTerm
46− | Search [String] PTerm
47+ | Search [PkgName] PTerm
47 | CaseSplitAt Bool Int Name
48 | CaseSplitAt Bool Int Name
48 | AddClauseFrom Bool Int Name
49 | AddClauseFrom Bool Int Name
49 | AddProofClauseFrom Bool Int Name
50 | AddProofClauseFrom Bool Int Name
@@ -65,7 +66,7 @@ data Command = Quit
65 | ListErrorHandlers
66 | ListErrorHandlers
66 | SetConsoleWidth ConsoleWidth
67 | SetConsoleWidth ConsoleWidth
67 | SetPrinterDepth (Maybe Int)
68 | SetPrinterDepth (Maybe Int)
68− | Apropos [String] String
69+ | Apropos [PkgName] String
69 | WhoCalls Name
70 | WhoCalls Name
70 | CallsWho Name
71 | CallsWho Name
71 | Browse [String]
72 | Browse [String]
src/Idris/REPL/Parser.hs+5−2
@@ -15,6 +15,7 @@ import Idris.AbsSyntax
15import Idris.Colours
15import Idris.Colours
16import Idris.Core.TT
16import Idris.Core.TT
17import Idris.Help
17import Idris.Help
18+import Idris.Imports
18import Idris.Options
19import Idris.Options
19import qualified Idris.Parser as P
20import qualified Idris.Parser as P
20import qualified Idris.Parser.Expr as P
21import qualified Idris.Parser.Expr as P
@@ -507,16 +508,18 @@ idChar = oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
507cmd_apropos :: String -> P.IdrisParser (Either String Command)
508cmd_apropos :: String -> P.IdrisParser (Either String Command)
508cmd_apropos = packageBasedCmd (some idChar) Apropos
509cmd_apropos = packageBasedCmd (some idChar) Apropos
509
510
510−packageBasedCmd :: P.IdrisParser a -> ([String] -> a -> Command)
511+packageBasedCmd :: P.IdrisParser a -> ([PkgName] -> a -> Command)
511 -> String -> P.IdrisParser (Either String Command)
512 -> String -> P.IdrisParser (Either String Command)
512packageBasedCmd valParser cmd name =
513packageBasedCmd valParser cmd name =
513 try (do P.lchar '('
514 try (do P.lchar '('
514− pkgs <- sepBy (some idChar) (P.lchar ',')
515+ pkgs <- sepBy (pkg <* P.whiteSpace) (P.lchar ',')
515 P.lchar ')'
516 P.lchar ')'
516 val <- valParser
517 val <- valParser
517 return (Right (cmd pkgs val)))
518 return (Right (cmd pkgs val)))
518 <|> do val <- valParser
519 <|> do val <- valParser
519 return (Right (cmd [] val))
520 return (Right (cmd [] val))
521+ where
522+ pkg = either fail pure . pkgName =<< P.packageName
520
523
521cmd_search :: String -> P.IdrisParser (Either String Command)
524cmd_search :: String -> P.IdrisParser (Either String Command)
522cmd_search = packageBasedCmd
525cmd_search = packageBasedCmd
src/Idris/TypeSearch.hs+3−2
@@ -26,6 +26,7 @@ import Idris.Delaborate (delabTy)
26import Idris.Docstrings (noDocs, overview)
26import Idris.Docstrings (noDocs, overview)
27import Idris.Elab.Type (elabType)
27import Idris.Elab.Type (elabType)
28import Idris.IBC
28import Idris.IBC
29+import Idris.Imports (PkgName)
29import Idris.Output (iPrintResult, iRenderError, iRenderOutput, iRenderResult,
30import Idris.Output (iPrintResult, iRenderError, iRenderOutput, iRenderResult,
30 iputStrLn, prettyDocumentedIst)
31 iputStrLn, prettyDocumentedIst)
31
32
@@ -48,11 +49,11 @@ import qualified Data.Set as S
48import qualified Data.Text as T (isPrefixOf, pack)
49import qualified Data.Text as T (isPrefixOf, pack)
49import Data.Traversable (traverse)
50import Data.Traversable (traverse)
50
51
51−searchByType :: [String] -> PTerm -> Idris ()
52+searchByType :: [PkgName] -> PTerm -> Idris ()
52searchByType pkgs pterm = do
53searchByType pkgs pterm = do
53 i <- getIState -- save original
54 i <- getIState -- save original
54 when (not (null pkgs)) $
55 when (not (null pkgs)) $
55− iputStrLn $ "Searching packages: " ++ showSep ", " pkgs
56+ iputStrLn $ "Searching packages: " ++ showSep ", " (map show pkgs)
56
57
57 mapM_ loadPkgIndex pkgs
58 mapM_ loadPkgIndex pkgs
58 pterm' <- addUsingConstraints syn emptyFC pterm
59 pterm' <- addUsingConstraints syn emptyFC pterm
stack-shell.nix+5−15
@@ -1,9 +1,7 @@
1+{ ghc }:
1with (import <nixpkgs> {});
2with (import <nixpkgs> {});
2
3
3let
4let
4− # MUST match GHC of resolver in stack.yaml
5− ghc = haskell.packages.ghc802.ghc;
6−
7 native_libs = [
5 native_libs = [
8 libffi
6 libffi
9 zlib
7 zlib
@@ -15,17 +13,9 @@ let
15 CoreServices
13 CoreServices
16 ]);
14 ]);
17
15
18−in stdenv.mkDerivation {
16+in haskell.lib.buildStackProject {
19−
17+ inherit ghc;
18+ buildInputs = native_libs;
20 name = "idrisBuildEnv";
19 name = "idrisBuildEnv";
21−
20+ src = ./.;
22− buildInputs = [ ghc ] ++ native_libs;
23−
24− STACK_IN_NIX_EXTRA_ARGS = builtins.foldl'
25− (acc: lib:
26− " --extra-lib-dirs=${lib}/lib --extra-include-dirs=${lib}/include" + acc)
27− "" native_libs;
28−
29− # Needed if one wants to use ghci, due to https://ghc.haskell.org/trac/ghc/ticket/11042
30− LD_LIBRARY_PATH = builtins.concatStringsSep ":" (map (lib: lib.out + "/lib") native_libs);
31}
21}
test/TestData.hs+23−22
@@ -52,28 +52,29 @@ testFamiliesData = [
52 ("base", "Base",
52 ("base", "Base",
53 [ ( 1, C_CG )]),
53 [ ( 1, C_CG )]),
54 ("basic", "Basic",
54 ("basic", "Basic",
55− [ ( 1, ANY ),
55+ [ ( 1, ANY ),
56− ( 2, ANY ),
56+ ( 2, ANY ),
57− ( 3, ANY ),
57+ ( 3, ANY ),
58− ( 4, ANY ),
58+ ( 4, ANY ),
59− ( 5, ANY ),
59+ ( 5, ANY ),
60− ( 6, ANY ),
60+ ( 6, ANY ),
61− ( 7, C_CG ),
61+ ( 7, C_CG ),
62− ( 8, ANY ),
62+ ( 8, ANY ),
63− ( 9, ANY ),
63+ ( 9, ANY ),
64− ( 10, ANY ),
64+ ( 10, ANY ),
65− ( 11, C_CG ),
65+ ( 11, C_CG ),
66− ( 12, ANY ),
66+ ( 12, ANY ),
67− ( 13, ANY ),
67+ ( 13, ANY ),
68− ( 14, ANY ),
68+ ( 14, ANY ),
69− ( 15, ANY ),
69+ ( 15, ANY ),
70− ( 16, ANY ),
70+ ( 16, ANY ),
71− ( 17, ANY ),
71+ ( 17, ANY ),
72− ( 18, ANY ),
72+ ( 18, ANY ),
73− ( 19, ANY ),
73+ ( 19, ANY ),
74− ( 20, ANY ),
74+ ( 20, ANY ),
75− ( 21, C_CG ),
75+ ( 21, C_CG ),
76− ( 22, NODE_CG )]),
76+ ( 22, NODE_CG ),
77+ ( 23, ANY )]),
77 ("bignum", "Bignum",
78 ("bignum", "Bignum",
78 [ ( 1, ANY ),
79 [ ( 1, ANY ),
79 ( 2, ANY )]),
80 ( 2, ANY )]),
test/basic013/basic013.idr+2
@@ -20,6 +20,8 @@ main = do putStrLn foo
20 putStrLn (reverse (foo ++ bar))
20 putStrLn (reverse (foo ++ bar))
21 printLn (length foo)
21 printLn (length foo)
22 printLn baz
22 printLn baz
23+ printLn (strCons '\x141' "")
24+ printLn (singleton (chr 0x141))
23 let x = 4
25 let x = 4
24 let newstr = appMany (toNat x)
26 let newstr = appMany (toNat x)
25 putStrLn newstr
27 putStrLn newstr
test/basic013/expected+2
@@ -3,6 +3,8 @@
3x→xλx→xλ
3x→xλx→xλ
44
44
5'\955'
5'\955'
6+"\321"
7+"\321"
6λx→xλx→xλx→xλx→xλx→x
8λx→xλx→xλx→xλx→xλx→x
7'\955'
9'\955'
820
1020
test/basic023/expectednew file+7
@@ -0,0 +1,7 @@
1+True
2+True
3+True
4+True
5+True
6+True
7+True
test/basic023/runnew file+4
@@ -0,0 +1,4 @@
1+#!/usr/bin/env bash
2+${IDRIS:-idris} $@ sections.idr -o sections
3+./sections
4+rm -f sections *.ibc
test/basic023/sections.idrnew file+21
@@ -0,0 +1,21 @@
1+postInc : Nat -> Nat
2+postInc = (`plus` 1)
3+
4+cons : Int -> List Int -> List Int
5+cons = (::)
6+
7+prefix 1 :/
8+(:/) : Nat -> Nat
9+(:/) = (1 `plus`)
10+
11+main : IO ()
12+main = do
13+ printLn $ (1 `cons`) [2] == [1,2]
14+ printLn $ (1 ::) [2] == [1,2]
15+ printLn $ (`cons` [2]) 1 == [1,2]
16+ printLn $ (:: [2]) 1 == [1,2]
17+ let x : Integer = 4
18+ printLn $ (- x) == -4 -- prefix, not section
19+ let io : IO Integer = pure 9
20+ printLn $ (! io) == 9 -- prefix, not section
21+ printLn $ (:/ 3) == 4 -- custom prefix operator (#2571)
test/pkg001/test-pkg.ipkg+1−1
@@ -1,4 +1,4 @@
1−package "test-pkg"
1+package test-pkg
2
2
3pkgs = effects
3pkgs = effects
4
4