on master help sign in
Merge remote-tracking branch 'upstream/master' into providers
161ef3dDavid Christiansen
CHANGELOG+1
@@ -3,6 +3,7 @@ New in 0.9.8:
3
3
4User visible changes:
4User visible changes:
5
5
6+* Added "rewrite ... in ..." construct
6* Renamed EFF to EFFECT in Effect package
7* Renamed EFF to EFFECT in Effect package
7* Experimental Java backend
8* Experimental Java backend
8* Tab completion in REPL
9* Tab completion in REPL
contribs/tool-support/sublime-text/Idris/Idris.JSON-tmLanguagenew file+70
@@ -0,0 +1,70 @@
1+{ "name": "Idris",
2+ "scopeName": "source.idris",
3+ "fileTypes": ["idr"],
4+ "patterns": [
5+ { "name": "keyword.control.idris",
6+ "match": "\\b(if|then|else|do|let|in|data|codata|record|dsl|import)\\b"
7+
8+ },
9+ { "name": "keyword.control.idris",
10+ "match": "\\b(impossible|case|of|total|partial|mutual|infix|infixl|infixr)\\b"
11+
12+ },
13+ { "name": "keyword.control.idris",
14+ "match": "\\b(where|with|syntax|proof|postulate|using|namespace|class|instance)\\b"
15+
16+ },
17+ { "name": "keyword.control.idris",
18+ "match": "\\b(public|private|abstract|implicit)\\b"
19+
20+ },
21+ { "name": "keyword.other.idris",
22+ "match": "\\b(Type|Int|Integer|Float|Char|String|Ptr|Bits8|Bits16|Bits32|Bits64)\\b"
23+ },
24+ { "name": "constant.numeric.idris",
25+ "match": "\\b(S|O)\\b"
26+ },
27+ { "match": "\\b([0-9]+|0([xX][0-9a-fA-F]+|[oO][0-7]+))\\b",
28+ "name": "constant.numeric.idris",
29+ "comment": "integers"
30+ },
31+ {
32+ "match": "\\b([0-9]+\\.[0-9]+([eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)\\b",
33+ "name": "constant.numeric.float.idris",
34+ "comment": "floats"
35+ },
36+ {
37+ "name": "comment.line.idris",
38+ "match": "(--).*$\n?",
39+ "comment": "Line comment"
40+ },
41+ { "name": "comment.block.idris",
42+ "begin": "\\{-",
43+ "end": "-\\}",
44+ "comment": "Block comment"
45+ },
46+ {
47+ "name": "string.quoted.idris",
48+ "begin": "\"",
49+ "beginCaptures": {
50+ "0": { "name": "punctuation.definition.string.begin.idris"}
51+ },
52+ "end": "\"",
53+ "endCaptures": {
54+ "0": { "name": "punctuation.definition.string.end.idris"}
55+ },
56+ "patterns": [
57+ { "name": "constant.character.escape.idris",
58+ "match": "\\\\\""
59+ }
60+ ]
61+
62+ }
63+
64+
65+ ],
66+ "repository": {
67+
68+ },
69+ "uuid": "4dd16092-ffa5-4ba4-8075-e5da9f368a72"
70+}
contribs/tool-support/sublime-text/Idris/Idris.tmLanguagenew file+126
@@ -0,0 +1,126 @@
1+<?xml version="1.0" encoding="UTF-8"?>
2+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+<plist version="1.0">
4+<dict>
5+ <key>fileTypes</key>
6+ <array>
7+ <string>idr</string>
8+ </array>
9+ <key>name</key>
10+ <string>Idris</string>
11+ <key>patterns</key>
12+ <array>
13+ <dict>
14+ <key>match</key>
15+ <string>\b(if|then|else|do|let|in|data|codata|record|dsl|import)\b</string>
16+ <key>name</key>
17+ <string>keyword.control.idris</string>
18+ </dict>
19+ <dict>
20+ <key>match</key>
21+ <string>\b(impossible|case|of|total|partial|mutual|infix|infixl|infixr)\b</string>
22+ <key>name</key>
23+ <string>keyword.control.idris</string>
24+ </dict>
25+ <dict>
26+ <key>match</key>
27+ <string>\b(where|with|syntax|proof|postulate|using|namespace|class|instance)\b</string>
28+ <key>name</key>
29+ <string>keyword.control.idris</string>
30+ </dict>
31+ <dict>
32+ <key>match</key>
33+ <string>\b(public|private|abstract|implicit)\b</string>
34+ <key>name</key>
35+ <string>keyword.control.idris</string>
36+ </dict>
37+ <dict>
38+ <key>match</key>
39+ <string>\b(Type|Int|Integer|Float|Char|String|Ptr|Bits8|Bits16|Bits32|Bits64)\b</string>
40+ <key>name</key>
41+ <string>keyword.other.idris</string>
42+ </dict>
43+ <dict>
44+ <key>match</key>
45+ <string>\b(S|O)\b</string>
46+ <key>name</key>
47+ <string>constant.numeric.idris</string>
48+ </dict>
49+ <dict>
50+ <key>comment</key>
51+ <string>integers</string>
52+ <key>match</key>
53+ <string>\b([0-9]+|0([xX][0-9a-fA-F]+|[oO][0-7]+))\b</string>
54+ <key>name</key>
55+ <string>constant.numeric.idris</string>
56+ </dict>
57+ <dict>
58+ <key>comment</key>
59+ <string>floats</string>
60+ <key>match</key>
61+ <string>\b([0-9]+\.[0-9]+([eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)\b</string>
62+ <key>name</key>
63+ <string>constant.numeric.float.idris</string>
64+ </dict>
65+ <dict>
66+ <key>comment</key>
67+ <string>Line comment</string>
68+ <key>match</key>
69+ <string>(--).*$
70+?</string>
71+ <key>name</key>
72+ <string>comment.line.idris</string>
73+ </dict>
74+ <dict>
75+ <key>begin</key>
76+ <string>\{-</string>
77+ <key>comment</key>
78+ <string>Block comment</string>
79+ <key>end</key>
80+ <string>-\}</string>
81+ <key>name</key>
82+ <string>comment.block.idris</string>
83+ </dict>
84+ <dict>
85+ <key>begin</key>
86+ <string>"</string>
87+ <key>beginCaptures</key>
88+ <dict>
89+ <key>0</key>
90+ <dict>
91+ <key>name</key>
92+ <string>punctuation.definition.string.begin.idris</string>
93+ </dict>
94+ </dict>
95+ <key>end</key>
96+ <string>"</string>
97+ <key>endCaptures</key>
98+ <dict>
99+ <key>0</key>
100+ <dict>
101+ <key>name</key>
102+ <string>punctuation.definition.string.end.idris</string>
103+ </dict>
104+ </dict>
105+ <key>name</key>
106+ <string>string.quoted.idris</string>
107+ <key>patterns</key>
108+ <array>
109+ <dict>
110+ <key>match</key>
111+ <string>\\"</string>
112+ <key>name</key>
113+ <string>constant.character.escape.idris</string>
114+ </dict>
115+ </array>
116+ </dict>
117+ </array>
118+ <key>repository</key>
119+ <dict>
120+ </dict>
121+ <key>scopeName</key>
122+ <string>source.idris</string>
123+ <key>uuid</key>
124+ <string>4dd16092-ffa5-4ba4-8075-e5da9f368a72</string>
125+</dict>
126+</plist>
contribs/tool-support/sublime-text/Idris/idris.sublime-buildnew file+5
@@ -0,0 +1,5 @@
1+{
2+ "cmd": ["idris", "$file"],
3+ "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
4+ "selector": "source.idris"
5+}
contribs/tool-support/sublime-text/README.mdnew file+11
@@ -0,0 +1,11 @@
1+#### Idris support for Sublime Text 2
2+
3+To install, copy the Idris directory to Sublime Text's Packages directory.
4+
5+To build a new Idris.tmLanguage file from the Idris.JSON-tmLanguage file, Sublime Text needs to have the AAAPackageDev package installed.
6+
7+Syntax Definitions tutorial: https://sublime-text-unofficial-documentation.readthedocs.org/en/latest/extensibility/syntaxdefs.html
8+
9+Syntax Definitions reference: https://sublime-text-unofficial-documentation.readthedocs.org/en/latest/reference/syntaxdefs.html
10+
11+Most used scopes: http://manual.macromates.com/en/language_grammars#naming_conventions
contribs/tool-support/vim/indent/idris.vim+11−1
@@ -3,7 +3,7 @@
3" Based on haskell indentation by motemen <motemen@gmail.com>
3" Based on haskell indentation by motemen <motemen@gmail.com>
4"
4"
5" author: raichoo (raichoo@googlemail.com)
5" author: raichoo (raichoo@googlemail.com)
6−" date: Nov 2 2012
6+" date: Mar 19 2013
7"
7"
8" Modify g:idris_indent_if and g:idris_indent_case to
8" Modify g:idris_indent_if and g:idris_indent_case to
9" change indentation for `if'(default 3) and `case'(default 5).
9" change indentation for `if'(default 3) and `case'(default 5).
@@ -36,6 +36,12 @@ if !exists('g:idris_indent_let')
36 let g:idris_indent_let = 4
36 let g:idris_indent_let = 4
37endif
37endif
38
38
39+if !exists('g:idris_indent_rewrite')
40+ " rewrite prf in expr
41+ " >>>>x
42+ let g:idris_indent_rewrite = 8
43+endif
44+
39if !exists('g:idris_indent_where')
45if !exists('g:idris_indent_where')
40 " where f : Nat -> Nat
46 " where f : Nat -> Nat
41 " >>>>>>f x = x
47 " >>>>>>f x = x
@@ -71,6 +77,10 @@ function! GetIdrisIndent()
71 return match(prevline, 'let') + g:idris_indent_let
77 return match(prevline, 'let') + g:idris_indent_let
72 endif
78 endif
73
79
80+ if prevline =~ '\<rewrite\>\s\+.\+\<in\>\s*$'
81+ return match(prevline, 'rewrite') + g:idris_indent_rewrite
82+ endif
83+
74 if prevline !~ '\<else\>'
84 if prevline !~ '\<else\>'
75 let s = match(prevline, '\<if\>.*\&.*\zs\<then\>')
85 let s = match(prevline, '\<if\>.*\&.*\zs\<then\>')
76 if s > 0
86 if s > 0
contribs/tool-support/vim/syntax/idris.vim+3−3
@@ -4,7 +4,7 @@
4" highlighter to support idris.
4" highlighter to support idris.
5"
5"
6" author: raichoo (raichoo@googlemail.com)
6" author: raichoo (raichoo@googlemail.com)
7−" date: Mar 12 2013
7+" date: Mar 20 2013
8
8
9syn match idrisModule "\<\(module\|namespace\)\>"
9syn match idrisModule "\<\(module\|namespace\)\>"
10syn match idrisImport "\<import\>"
10syn match idrisImport "\<import\>"
@@ -12,7 +12,7 @@ syn match idrisStructure "\<\(class\|\(co\)\?data\|instance\|where\|record\|dsl\
12syn match idrisVisibility "\<\(public\|abstract\|private\)\>"
12syn match idrisVisibility "\<\(public\|abstract\|private\)\>"
13syn match idrisBlock "\<\(parameters\|mutual\|postulate\|using\)\>"
13syn match idrisBlock "\<\(parameters\|mutual\|postulate\|using\)\>"
14syn match idrisAnnotation "\<\(total\|partial\|auto\|impossible\|static\|implicit\)\>"
14syn match idrisAnnotation "\<\(total\|partial\|auto\|impossible\|static\|implicit\)\>"
15−syn match idrisStatement "\<\(do\|case\|of\|let\|in\|with\)\>"
15+syn match idrisStatement "\<\(do\|case\|of\|rewrite\|let\|in\|with\)\>"
16syn match idrisSyntax "\(pattern \+\|term \+\)\?syntax"
16syn match idrisSyntax "\(pattern \+\|term \+\)\?syntax"
17syn match idrisConditional "\<\(if\|then\|else\)\>"
17syn match idrisConditional "\<\(if\|then\|else\)\>"
18syn match idrisTactic contained "\<\(intros\?\|rewrite\|exact\|refine\|trivial\|let\|focus\|try\|compute\|solve\|attack\|reflect\)\>"
18syn match idrisTactic contained "\<\(intros\?\|rewrite\|exact\|refine\|trivial\|let\|focus\|try\|compute\|solve\|attack\|reflect\)\>"
@@ -28,7 +28,7 @@ syn match idrisLink "%\(lib\|link\|include\)"
28syn match idrisDirective "%\(access\|default\|assert_total\)"
28syn match idrisDirective "%\(access\|default\|assert_total\)"
29syn match idrisDSL "\(lambda\|variable\|\index_first\|index_next\)"
29syn match idrisDSL "\(lambda\|variable\|\index_first\|index_next\)"
30syn region idrisString start=+"+ skip=+\\\\\|\\"+ end=+"+
30syn region idrisString start=+"+ skip=+\\\\\|\\"+ end=+"+
31−syn region idrisBlockComment start="{-" end="-}"
31+syn region idrisBlockComment start="{-" end="-}" contains=idrisBlockComment
32syn region idrisProofBlock start="\(default\s\+\)\?\(proof\|tactics\) *{" end="}" contains=idrisTactic
32syn region idrisProofBlock start="\(default\s\+\)\?\(proof\|tactics\) *{" end="}" contains=idrisTactic
33
33
34syn match idrisBadLeadingWhiteSpace "^\s*\t\+"
34syn match idrisBadLeadingWhiteSpace "^\s*\t\+"
effects/Effect/Exception.idr+3
@@ -17,6 +17,9 @@ instance Show a => Handler (Exception a) IO where
17instance Handler (Exception a) (IOExcept a) where
17instance Handler (Exception a) (IOExcept a) where
18 handle _ (Raise e) k = ioM (return (Left e))
18 handle _ (Raise e) k = ioM (return (Left e))
19
19
20+instance Handler (Exception a) (Either a) where
21+ handle _ (Raise e) k = Left e
22+
20EXCEPTION : Type -> EFFECT
23EXCEPTION : Type -> EFFECT
21EXCEPTION t = MkEff () (Exception t)
24EXCEPTION t = MkEff () (Exception t)
22
25
effects/Effect/StdIO.idr+5−4
@@ -19,9 +19,6 @@ instance Handler StdIO (IOExcept a) where
19
19
20data IOStream a = MkStream (List String -> (a, List String))
20data IOStream a = MkStream (List String -> (a, List String))
21
21
22−injStream : a -> IOStream a
23−injStream v = MkStream (\x => (v, []))
24−
25instance Handler StdIO IOStream where
22instance Handler StdIO IOStream where
26 handle () (PutStr s) k
23 handle () (PutStr s) k
27 = MkStream (\x => case k () () of
24 = MkStream (\x => case k () () of
@@ -55,5 +52,9 @@ mkStrFn : Env IOStream xs ->
55 List String -> (a, List String)
52 List String -> (a, List String)
56mkStrFn {a} env p input = case mkStrFn' of
53mkStrFn {a} env p input = case mkStrFn' of
57 MkStream f => f input
54 MkStream f => f input
55+ where injStream : a -> IOStream a
56+ injStream v = MkStream (\x => (v, []))
58− where mkStrFn' : IOStream a
57+ mkStrFn' : IOStream a
59 mkStrFn' = runWith injStream env p
58 mkStrFn' = runWith injStream env p
59+
60+
effects/Effects.idr+4−2
@@ -100,8 +100,7 @@ data EffM : (m : Type -> Type) ->
100 List EFFECT -> List EFFECT -> Type -> Type where
100 List EFFECT -> List EFFECT -> Type -> Type where
101 value : a -> EffM m xs xs a
101 value : a -> EffM m xs xs a
102 ebind : EffM m xs xs' a -> (a -> EffM m xs' xs'' b) -> EffM m xs xs'' b
102 ebind : EffM m xs xs' a -> (a -> EffM m xs' xs'' b) -> EffM m xs xs'' b
103− effect : {a, b: _} -> {e : Effect} ->
104− (prf : EffElem e a xs) ->
103+ effect : (prf : EffElem e a xs) ->
105 (eff : e a b t) ->
104 (eff : e a b t) ->
106 EffM m xs (updateResTy xs prf eff) t
105 EffM m xs (updateResTy xs prf eff) t
107 lift : (prf : SubList ys xs) ->
106 lift : (prf : SubList ys xs) ->
@@ -189,6 +188,9 @@ runEnv env prog = eff env prog (\env, r => pure (env, r))
189runPure : Env id xs -> EffM id xs xs' a -> a
188runPure : Env id xs -> EffM id xs xs' a -> a
190runPure env prog = eff env prog (\env, r => r)
189runPure env prog = eff env prog (\env, r => r)
191
190
191+runPureEnv : Env id xs -> EffM id xs xs' a -> (Env id xs', a)
192+runPureEnv env prog = eff env prog (\env, r => (env, r))
193+
192runWith : (a -> m a) -> Env m xs -> EffM m xs xs' a -> m a
194runWith : (a -> m a) -> Env m xs -> EffM m xs xs' a -> m a
193runWith inj env prog = eff env prog (\env, r => inj r)
195runWith inj env prog = eff env prog (\env, r => inj r)
194
196
java/executable_pom_template.xml+1
@@ -17,6 +17,7 @@
17 <artifactId>idris</artifactId>
17 <artifactId>idris</artifactId>
18 <version>$RTS-VERSION$</version>
18 <version>$RTS-VERSION$</version>
19 </dependency>
19 </dependency>
20+$DEPENDENCIES$
20 </dependencies>
21 </dependencies>
21
22
22
23
java/src/main/java/org/idris/rts/ForeignPrimitives.java+138−123
@@ -1,5 +1,6 @@
1package org.idris.rts;
1package org.idris.rts;
2
2
3+import java.lang.reflect.InvocationTargetException;
3import java.util.Arrays;
4import java.util.Arrays;
4import java.util.List;
5import java.util.List;
5import java.util.Map;
6import java.util.Map;
@@ -9,7 +10,6 @@ import java.util.HashSet;
9import java.io.Closeable;
10import java.io.Closeable;
10import java.io.File;
11import java.io.File;
11import java.io.IOException;
12import java.io.IOException;
12−import java.io.EOFException;
13import java.io.PrintStream;
13import java.io.PrintStream;
14import java.io.InputStream;
14import java.io.InputStream;
15import java.nio.ByteBuffer;
15import java.nio.ByteBuffer;
@@ -25,190 +25,205 @@ import java.util.concurrent.Semaphore;
25
25
26@SuppressWarnings("unchecked")
26@SuppressWarnings("unchecked")
27public class ForeignPrimitives {
27public class ForeignPrimitives {
28+
28 private static final Map<Thread, List<String>> args = new HashMap<>();
29 private static final Map<Thread, List<String>> args = new HashMap<>();
29 private static final Semaphore messageMutex = new Semaphore(1);
30 private static final Semaphore messageMutex = new Semaphore(1);
30 private static final Map<Thread, BlockingQueue<Object>> messages = new HashMap<>();
31 private static final Map<Thread, BlockingQueue<Object>> messages = new HashMap<>();
31 private static final Set<Object> feofFiles = new HashSet<>();
32 private static final Set<Object> feofFiles = new HashSet<>();
32
33
33− public static synchronized void idris_initArgs(Thread t, String [] args) {
34+ public static synchronized void idris_initArgs(Thread t, String[] args) {
34− ForeignPrimitives.args.put(t, Arrays.asList(args));
35+ ForeignPrimitives.args.put(t, Arrays.asList(args));
35 }
36 }
36
37
37 public static synchronized int idris_numArgs(Object thread) {
38 public static synchronized int idris_numArgs(Object thread) {
38− List<String> argsForThread = ForeignPrimitives.args.get((Thread)thread);
39+ List<String> argsForThread = ForeignPrimitives.args.get((Thread) thread);
39− return (argsForThread == null ? 0 : argsForThread.size());
40+ return (argsForThread == null ? 0 : argsForThread.size());
40 }
41 }
41
42
42 public static synchronized String idris_getArg(Object thread, int num) {
43 public static synchronized String idris_getArg(Object thread, int num) {
43− List<String> argsForThread = ForeignPrimitives.args.get((Thread)thread);
44+ List<String> argsForThread = ForeignPrimitives.args.get((Thread) thread);
44− return (argsForThread == null ? null : argsForThread.get(num));
45+ return (argsForThread == null ? null : argsForThread.get(num));
45 }
46 }
46
47
47 public static String getenv(String x) {
48 public static String getenv(String x) {
48− return System.getenv(x);
49+ return System.getenv(x);
49 }
50 }
50
51
51 public static void exit(int exitCode) {
52 public static void exit(int exitCode) {
52− System.exit(exitCode);
53+ System.exit(exitCode);
53 }
54 }
54
55
55 public static void usleep(int microsecs) {
56 public static void usleep(int microsecs) {
56− try {
57+ try {
57− Thread.sleep(microsecs / 1000, microsecs % 1000);
58+ Thread.sleep(microsecs / 1000, microsecs % 1000);
58− } catch (InterruptedException ex) {
59+ } catch (InterruptedException ex) {
59− }
60+ }
60 }
61 }
61
62
62 public static void idris_sendMessage(Object from, Object dest, Object message) throws InterruptedException {
63 public static void idris_sendMessage(Object from, Object dest, Object message) throws InterruptedException {
63− messageMutex.acquire();
64+ messageMutex.acquire();
64− BlockingQueue<Object> messagesForTarget = messages.get((Thread)dest);
65+ BlockingQueue<Object> messagesForTarget = messages.get((Thread) dest);
65− if (messagesForTarget == null) {
66+ if (messagesForTarget == null) {
66− messagesForTarget = new LinkedBlockingQueue<>();
67+ messagesForTarget = new LinkedBlockingQueue<>();
67− messages.put((Thread)dest, messagesForTarget);
68+ messages.put((Thread) dest, messagesForTarget);
68− }
69+ }
69− messagesForTarget.put(message);
70+ messagesForTarget.put(message);
70 messageMutex.release();
71 messageMutex.release();
71 }
72 }
72
73
73 public static int idris_checkMessage(Object dest) throws InterruptedException {
74 public static int idris_checkMessage(Object dest) throws InterruptedException {
74− messageMutex.acquire();
75+ messageMutex.acquire();
75− BlockingQueue<Object> messagesForTarget = messages.get((Thread)dest);
76+ BlockingQueue<Object> messagesForTarget = messages.get((Thread) dest);
76− messageMutex.release();
77+ messageMutex.release();
77− return (messagesForTarget == null ? 0 : messagesForTarget.size());
78+ return (messagesForTarget == null ? 0 : messagesForTarget.size());
78 }
79 }
79
80
80 public static Object idris_recvMessage(Object dest) throws InterruptedException {
81 public static Object idris_recvMessage(Object dest) throws InterruptedException {
81− messageMutex.acquire();
82+ messageMutex.acquire();
82− BlockingQueue<Object> messagesForTarget = messages.get((Thread)dest);
83+ BlockingQueue<Object> messagesForTarget = messages.get((Thread) dest);
83− if (messagesForTarget == null) {
84+ if (messagesForTarget == null) {
84− messagesForTarget = new LinkedBlockingQueue();
85+ messagesForTarget = new LinkedBlockingQueue();
85− messages.put((Thread)dest, messagesForTarget);
86+ messages.put((Thread) dest, messagesForTarget);
86− }
87+ }
87− messageMutex.release();
88+ messageMutex.release();
88− return messagesForTarget.take();
89+ return messagesForTarget.take();
89 }
90 }
90
91
91 public static void putStr(String str) {
92 public static void putStr(String str) {
92− System.out.print(str);
93+ System.out.print(str);
93 }
94 }
94
95
95 public static void putchar(char c) {
96 public static void putchar(char c) {
96− System.out.print(c);
97+ System.out.print(c);
97 }
98 }
98
99
99 public static int getchar() {
100 public static int getchar() {
100− try {
101+ try {
101− return (char)System.in.read();
102+ return (char) System.in.read();
102− } catch (IOException ex) {
103+ } catch (IOException ex) {
103− return -1;
104+ return -1;
104− }
105+ }
105 }
106 }
106
107
107 public static SeekableByteChannel fileOpen(String name, String privs) {
108 public static SeekableByteChannel fileOpen(String name, String privs) {
108− try {
109+ try {
109− OpenOption [] options;
110+ OpenOption[] options;
110− switch (privs) {
111+ switch (privs) {
111− case "r" :
112+ case "r":
112− options = new StandardOpenOption []
113+ options = new StandardOpenOption[]{StandardOpenOption.READ};
113− { StandardOpenOption.READ };
114− break;
114+ break;
115− case "r+" :
115+ case "r+":
116− options = new StandardOpenOption []
116+ options = new StandardOpenOption[]{StandardOpenOption.READ,
117− { StandardOpenOption.READ,
118− StandardOpenOption.WRITE };
117+ StandardOpenOption.WRITE};
119− break;
118+ break;
120− case "w" :
119+ case "w":
121− options = new StandardOpenOption []
120+ options = new StandardOpenOption[]{StandardOpenOption.WRITE,
122− { StandardOpenOption.WRITE,
123− StandardOpenOption.CREATE };
121+ StandardOpenOption.CREATE};
124− break;
122+ break;
125− case "w+" :
123+ case "w+":
126− options = new StandardOpenOption []
124+ options = new StandardOpenOption[]{StandardOpenOption.READ,
127− { StandardOpenOption.READ,
128− StandardOpenOption.WRITE,
125+ StandardOpenOption.WRITE,
129− StandardOpenOption.CREATE };
126+ StandardOpenOption.CREATE};
130− break;
127+ break;
131− case "a" :
128+ case "a":
132− options = new StandardOpenOption []
129+ options = new StandardOpenOption[]{StandardOpenOption.WRITE,
133− { StandardOpenOption.WRITE,
134− StandardOpenOption.CREATE,
130+ StandardOpenOption.CREATE,
135− StandardOpenOption.APPEND };
131+ StandardOpenOption.APPEND};
136− break;
132+ break;
137− case "a+" :
133+ case "a+":
138− options = new StandardOpenOption []
134+ options = new StandardOpenOption[]{StandardOpenOption.READ,
139− { StandardOpenOption.READ,
140− StandardOpenOption.WRITE,
135+ StandardOpenOption.WRITE,
141− StandardOpenOption.CREATE,
136+ StandardOpenOption.CREATE,
142− StandardOpenOption.APPEND };
137+ StandardOpenOption.APPEND};
143− break;
138+ break;
144− default :
139+ default:
145− options = new StandardOpenOption [] {};
140+ options = new StandardOpenOption[]{};
146− break;
141+ break;
147− }
142+ }
148− return Files.newByteChannel(new File(name).toPath(), options);
143+ return Files.newByteChannel(new File(name).toPath(), options);
149− } catch (IOException ex) {
144+ } catch (IOException ex) {
150− return null;
145+ return null;
151− }
146+ }
152 }
147 }
153
148
154 public static synchronized void fileClose(Object file) throws IOException {
149 public static synchronized void fileClose(Object file) throws IOException {
155− ((Closeable)file).close();
150+ ((Closeable) file).close();
156− feofFiles.remove(file);
151+ feofFiles.remove(file);
157 }
152 }
158
153
159 public static void fputStr(Object file, String string) throws IOException {
154 public static void fputStr(Object file, String string) throws IOException {
160− if (file instanceof PrintStream) {
155+ if (file instanceof PrintStream) {
161− ((PrintStream)file).print(string);
156+ ((PrintStream) file).print(string);
162− } else if (file instanceof SeekableByteChannel) {
157+ } else if (file instanceof SeekableByteChannel) {
163− ((SeekableByteChannel)file).write(ByteBuffer.wrap(string.getBytes()));
158+ ((SeekableByteChannel) file).write(ByteBuffer.wrap(string.getBytes()));
164− }
159+ }
165 }
160 }
166
161
167 public static synchronized String idris_readStr(Object file) throws IOException {
162 public static synchronized String idris_readStr(Object file) throws IOException {
168− ReadableByteChannel channel = file instanceof InputStream ?
163+ ReadableByteChannel channel = file instanceof InputStream
169− Channels.newChannel((InputStream)file) :
164+ ? Channels.newChannel((InputStream) file)
170− (ReadableByteChannel)file;
165+ : (ReadableByteChannel) file;
171− ByteBuffer buf = ByteBuffer.allocate(1);
166+ ByteBuffer buf = ByteBuffer.allocate(1);
172− StringBuilder resultBuilder = new StringBuilder("");
167+ StringBuilder resultBuilder = new StringBuilder("");
173− String delimiter = System.getProperty("line.separator");
168+ String delimiter = System.getProperty("line.separator");
174− int read = 0;
169+ int read = 0;
175− do {
170+ do {
176− buf.rewind();
171+ buf.rewind();
177− read = channel.read(buf);
172+ read = channel.read(buf);
178− if (read > 0) {
173+ if (read > 0) {
179− resultBuilder.append(new String(buf.array()));
174+ resultBuilder.append(new String(buf.array()));
180− if (resultBuilder.lastIndexOf(delimiter) > -1) {
175+ if (resultBuilder.lastIndexOf(delimiter) > -1) {
181− return resultBuilder.toString();
176+ return resultBuilder.toString();
182− }
177+ }
183− }
178+ }
184− if (read < 0) {
179+ if (read < 0) {
185− feofFiles.add(file);
180+ feofFiles.add(file);
186− }
181+ }
187− } while (read >= 0);
182+ } while (read >= 0);
188− return resultBuilder.toString();
183+ return resultBuilder.toString();
189 }
184 }
190
185
191 public static int fileEOF(Object file) {
186 public static int fileEOF(Object file) {
192− return (feofFiles.contains(file) ? 1 : 0);
187+ return (feofFiles.contains(file) ? 1 : 0);
193 }
188 }
194
189
195 public static int isNull(Object o) {
190 public static int isNull(Object o) {
196− return (o == null ? 1 : 0);
191+ return (o == null ? 1 : 0);
197 }
192 }
198
193
199 public final static Object idris_K(final Object result, final Object drop) {
194 public final static Object idris_K(final Object result, final Object drop) {
200− return result;
195+ return result;
201 }
196 }
202
197
203 public final static Object idris_flipK(final Object drop, final Object result) {
198 public final static Object idris_flipK(final Object drop, final Object result) {
204− return result;
199+ return result;
205− }
200+ }
206−
201+
207− public final static Object idris_assignStack(final Object [] context, final int start, final Object ... vars) {
202+ public final static Object idris_assignStack(final Object[] context, final int start, final Object... vars) {
208− int i = start;
203+ int i = start;
209− for (Object var : vars) {
204+ for (Object var : vars) {
210− context[i] = var;
205+ context[i] = var;
211− }
206+ }
212− return context;
207+ return context;
208+ }
209+
210+ public final static Object invokeOn(final Object obj, final String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
211+ Class cls = (obj instanceof Class ? (Class)obj : obj.getClass());
212+ Class argClasses[] = new Class[args.length];
213+ int i = 0;
214+ for (Object arg : args) {
215+ argClasses[i] = arg.getClass();
216+ }
217+ return cls.getMethod(methodName, argClasses).invoke(obj, args);
218+ }
219+
220+ public final static Object newObject(final Object cls, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
221+ Class clazz = (cls instanceof Class ? (Class)cls : cls.getClass());
222+ Class argClasses[] = new Class[args.length];
223+ int i = 0;
224+ for (Object arg : args) {
225+ argClasses[i] = arg.getClass();
226+ }
227+ return clazz.getConstructor(argClasses).newInstance(args);
213 }
228 }
214}
229}
lib/IO.idr+2−4
@@ -33,10 +33,8 @@ interpFTy (FAny t) = t
33interpFTy FUnit = ()
33interpFTy FUnit = ()
34
34
35ForeignTy : (xs:List FTy) -> (t:FTy) -> Type
35ForeignTy : (xs:List FTy) -> (t:FTy) -> Type
36−ForeignTy xs t = mkForeign' (reverse xs) (IO (interpFTy t)) where
36+ForeignTy Nil rt = IO (interpFTy rt)
37− mkForeign' : List FTy -> Type -> Type
37+ForeignTy (t::ts) rt = interpFTy t -> ForeignTy ts rt
38− mkForeign' Nil ty = ty
39− mkForeign' (s :: ss) ty = mkForeign' ss (interpFTy s -> ty)
40
38
41
39
42data Foreign : Type -> Type where
40data Foreign : Type -> Type where
rts/idris_gc.c+1−3
@@ -101,9 +101,7 @@ void idris_gc(VM* vm) {
101 for(root = vm->inbox_ptr; root < vm->inbox_write; ++root) {
101 for(root = vm->inbox_ptr; root < vm->inbox_write; ++root) {
102 *root = copy(vm, *root);
102 *root = copy(vm, *root);
103 }
103 }
104− for(root = vm->argv; root < vm->argv + vm->argc; ++root) {
104+
105− *root = copy(vm, *root);
106− }
107 vm->ret = copy(vm, vm->ret);
105 vm->ret = copy(vm, vm->ret);
108 vm->reg1 = copy(vm, vm->reg1);
106 vm->reg1 = copy(vm, vm->reg1);
109
107
rts/idris_rts.c+2−18
@@ -20,16 +20,10 @@ VM* init_vm(int stack_size, size_t heap_size,
20 STATS_ENTER_INIT(vm->stats)
20 STATS_ENTER_INIT(vm->stats)
21
21
22 VAL* valstack = malloc(stack_size * sizeof(VAL));
22 VAL* valstack = malloc(stack_size * sizeof(VAL));
23− int* intstack = malloc(stack_size * sizeof(int));
24− double* floatstack = malloc(stack_size*sizeof(double));
25
23
26 vm->valstack = valstack;
24 vm->valstack = valstack;
27 vm->valstack_top = valstack;
25 vm->valstack_top = valstack;
28 vm->valstack_base = valstack;
26 vm->valstack_base = valstack;
29− vm->intstack = intstack;
30− vm->intstack_ptr = intstack;
31− vm->floatstack = floatstack;
32− vm->floatstack_ptr = floatstack;
33 vm->stack_max = valstack + stack_size;
27 vm->stack_max = valstack + stack_size;
34
28
35 alloc_heap(&(vm->heap), heap_size);
29 alloc_heap(&(vm->heap), heap_size);
@@ -51,15 +45,9 @@ VM* init_vm(int stack_size, size_t heap_size,
51 vm->max_threads = max_threads;
45 vm->max_threads = max_threads;
52 vm->processes = 0;
46 vm->processes = 0;
53
47
54− int i;
48+ vm->argv = argv;
55− // Assumption: there's enough space for this in the initial heap.
56− vm->argv = malloc(argc*sizeof(VAL));
57 vm->argc = argc;
49 vm->argc = argc;
58
50
59− for(i = 0; i < argc; ++i) {
60− vm->argv[i] = MKSTR(vm, argv[i]);
61− }
62−
63 STATS_LEAVE_INIT(vm->stats)
51 STATS_LEAVE_INIT(vm->stats)
64 return vm;
52 return vm;
65}
53}
@@ -70,10 +58,7 @@ Stats terminate(VM* vm) {
70
58
71 free(vm->inbox);
59 free(vm->inbox);
72 free(vm->valstack);
60 free(vm->valstack);
73− free(vm->intstack);
74− free(vm->floatstack);
75 free_heap(&(vm->heap));
61 free_heap(&(vm->heap));
76− free(vm->argv);
77
62
78 pthread_mutex_destroy(&(vm -> inbox_lock));
63 pthread_mutex_destroy(&(vm -> inbox_lock));
79 pthread_mutex_destroy(&(vm -> inbox_block));
64 pthread_mutex_destroy(&(vm -> inbox_block));
@@ -592,11 +577,10 @@ int idris_numArgs(VM* vm) {
592}
577}
593
578
594VAL idris_getArg(VM* vm, int i) {
579VAL idris_getArg(VM* vm, int i) {
595− return vm->argv[i];
580+ return MKSTR(vm, vm->argv[i]);
596}
581}
597
582
598void stackOverflow() {
583void stackOverflow() {
599 fprintf(stderr, "Stack overflow");
584 fprintf(stderr, "Stack overflow");
600 exit(-1);
585 exit(-1);
601}
586}
602−
rts/idris_rts.h+1−5
@@ -44,12 +44,8 @@ typedef struct Closure {
44
44
45typedef struct {
45typedef struct {
46 VAL* valstack;
46 VAL* valstack;
47− int* intstack;
48− double* floatstack;
49 VAL* valstack_top;
47 VAL* valstack_top;
50 VAL* valstack_base;
48 VAL* valstack_base;
51− int* intstack_ptr;
52− double* floatstack_ptr;
53 VAL* stack_max;
49 VAL* stack_max;
54
50
55 Heap heap;
51 Heap heap;
@@ -71,7 +67,7 @@ typedef struct {
71 Stats stats;
67 Stats stats;
72
68
73 int argc;
69 int argc;
74− VAL* argv; // command line arguments
70+ char** argv; // command line arguments
75
71
76 VAL ret;
72 VAL ret;
77 VAL reg1;
73 VAL reg1;
rts/idris_stats.c+19−4
@@ -9,8 +9,23 @@ void print_stats(const Stats * stats) {
9 clock_t total = clock() - stats->start_time;
9 clock_t total = clock() - stats->start_time;
10 clock_t mut = total - stats->init_time - stats->gc_time - stats->exit_time;
10 clock_t mut = total - stats->init_time - stats->gc_time - stats->exit_time;
11 double mut_sec = (double)mut / CLOCKS_PER_SEC;
11 double mut_sec = (double)mut / CLOCKS_PER_SEC;
12+
13+ int avg_chunk = 0;
14+ if (stats->alloc_count > 0) {
12− int avg_chunk = (int)((double)stats->allocations / (double)stats->alloc_count);
15+ avg_chunk = (int)((double)stats->allocations / (double)stats->alloc_count);
16+ }
17+
18+ int alloc_rate = 0;
19+ if (mut > 0) {
13− int alloc_rate = (int)((double)(stats->allocations) / mut_sec);
20+ alloc_rate = (int)((double)(stats->allocations) / mut_sec);
21+ }
22+
23+ double gc_percent = 0.0;
24+ double productivity = 0.0;
25+ if (total > 0) {
26+ gc_percent = 100 * (double)stats->gc_time / (double)total;
27+ productivity = 100 * ((double)mut / (double)total);
28+ }
14
29
15 setlocale(LC_NUMERIC, "");
30 setlocale(LC_NUMERIC, "");
16 printf("\n");
31 printf("\n");
@@ -28,11 +43,11 @@ void print_stats(const Stats * stats) {
28 printf("EXIT time: %8.3fs\n", (double)stats->exit_time / CLOCKS_PER_SEC);
43 printf("EXIT time: %8.3fs\n", (double)stats->exit_time / CLOCKS_PER_SEC);
29 printf("TOTAL time: %8.3fs\n\n", (double)total / CLOCKS_PER_SEC);
44 printf("TOTAL time: %8.3fs\n\n", (double)total / CLOCKS_PER_SEC);
30
45
31− printf("%%GC time: %.2f%%\n\n", 100 * (double)stats->gc_time / (double)total);
46+ printf("%%GC time: %.2f%%\n\n", gc_percent);
32
47
33 printf("Alloc rate %'d bytes per MUT sec\n\n", alloc_rate);
48 printf("Alloc rate %'d bytes per MUT sec\n\n", alloc_rate);
34
49
35− printf("Productivity %.2f%%\n", 100 * ((double)mut / (double)total));
50+ printf("Productivity %.2f%%\n", productivity);
36}
51}
37
52
38void aggregate_stats(Stats * stats1, const Stats * stats2) {
53void aggregate_stats(Stats * stats1, const Stats * stats2) {
samples/javaffi.idrnew file+12
@@ -0,0 +1,12 @@
1+module Main
2+
3+%include "com.google.common.math.IntMath"
4+%lib "com.google.guava:guava:14.0"
5+
6+binom : Int -> Int -> IO Int
7+binom n k = mkForeign (FFun "IntMath.binomial" [FInt, FInt] FInt) n k
8+
9+main : IO ()
10+main = do print "The number of possibilities in lotto is 49 choose 6:"
11+ res <- binom 49 6
12+ print res
src/Core/CoreParser.hs+1−1
@@ -31,7 +31,7 @@ idrisDef = haskellDef {
31 = ["let", "in", "data", "codata", "record", "Type",
31 = ["let", "in", "data", "codata", "record", "Type",
32 "do", "dsl", "import", "impossible",
32 "do", "dsl", "import", "impossible",
33 "case", "of", "total", "partial", "mutual",
33 "case", "of", "total", "partial", "mutual",
34− "infix", "infixl", "infixr",
34+ "infix", "infixl", "infixr", "rewrite",
35 "where", "with", "syntax", "proof", "postulate",
35 "where", "with", "syntax", "proof", "postulate",
36 "using", "namespace", "class", "instance",
36 "using", "namespace", "class", "instance",
37 "public", "private", "abstract", "implicit",
37 "public", "private", "abstract", "implicit",
src/Core/ProofState.hs+1−2
@@ -444,8 +444,7 @@ intro n ctxt env _ = fail "Can't introduce here."
444forall :: Name -> Raw -> RunTactic
444forall :: Name -> Raw -> RunTactic
445forall n ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
445forall n ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
446 do (tyv, tyt) <- lift $ check ctxt env ty
446 do (tyv, tyt) <- lift $ check ctxt env ty
447− lift $ isType ctxt env tyt
447+ unify' ctxt env tyt (TType (UVar 0))
448− lift $ isType ctxt env t
449 return $ Bind n (Pi tyv) (Bind x (Hole t) (P Bound x t))
448 return $ Bind n (Pi tyv) (Bind x (Hole t) (P Bound x t))
450forall n ty ctxt env _ = fail "Can't pi bind here"
449forall n ty ctxt env _ = fail "Can't pi bind here"
451
450
src/Core/TT.hs+2
@@ -69,6 +69,7 @@ data Err = Msg String
69 | NonCollapsiblePostulate Name
69 | NonCollapsiblePostulate Name
70 | AlreadyDefined Name
70 | AlreadyDefined Name
71 | ProofSearchFail Err
71 | ProofSearchFail Err
72+ | NoRewriting Term
72 | At FC Err
73 | At FC Err
73 deriving Eq
74 deriving Eq
74
75
@@ -82,6 +83,7 @@ instance Sized Err where
82 size (NoTypeDecl name) = size name
83 size (NoTypeDecl name) = size name
83 size (NotInjective l c r) = size l + size c + size r
84 size (NotInjective l c r) = size l + size c + size r
84 size (CantResolve trm) = size trm
85 size (CantResolve trm) = size trm
86+ size (NoRewriting trm) = size trm
85 size (CantResolveAlts _) = 1
87 size (CantResolveAlts _) = 1
86 size (IncompleteTerm trm) = size trm
88 size (IncompleteTerm trm) = size trm
87 size UniverseError = 1
89 size UniverseError = 1
src/IRTS/CodegenJava.hs+51−22
@@ -15,7 +15,7 @@ import qualified Control.Monad.Trans as T
15import Control.Monad.Trans.State
15import Control.Monad.Trans.State
16import Data.Char
16import Data.Char
17import Data.Maybe (fromJust)
17import Data.Maybe (fromJust)
18−import Data.List (isPrefixOf, intercalate)
18+import Data.List (isPrefixOf, isSuffixOf, intercalate)
19import qualified Data.Text as T
19import qualified Data.Text as T
20import qualified Data.Text.IO as TIO
20import qualified Data.Text.IO as TIO
21import Language.Java.Parser
21import Language.Java.Parser
@@ -35,9 +35,11 @@ type CodeGeneration = StateT (CodeGenerationEnv) (Either String)
35codegenJava :: [(Name, SExp)] -> -- initialization of globals
35codegenJava :: [(Name, SExp)] -> -- initialization of globals
36 [(Name, SDecl)] ->
36 [(Name, SDecl)] ->
37 FilePath -> -- output file name
37 FilePath -> -- output file name
38+ [String] -> -- headers
39+ [String] -> -- libs
38 OutputType ->
40 OutputType ->
39 IO ()
41 IO ()
40−codegenJava globalInit defs out exec = do
42+codegenJava globalInit defs out hdrs libs exec = do
41 withTempdir (takeBaseName out) $ \ tmpDir -> do
43 withTempdir (takeBaseName out) $ \ tmpDir -> do
42 let srcdir = tmpDir </> "src" </> "main" </> "java"
44 let srcdir = tmpDir </> "src" </> "main" </> "java"
43 createDirectoryIfMissing True srcdir
45 createDirectoryIfMissing True srcdir
@@ -46,7 +48,7 @@ codegenJava globalInit defs out exec = do
46 let outjava = srcdir </> clsName <.> "java"
48 let outjava = srcdir </> clsName <.> "java"
47 let jout = either error
49 let jout = either error
48 (flatIndent . prettyPrint)
50 (flatIndent . prettyPrint)
49− (evalStateT (mkCompilationUnit globalInit defs out) (mkCodeGenEnv globalInit))
51+ (evalStateT (mkCompilationUnit globalInit defs hdrs out) (mkCodeGenEnv globalInit))
50 writeFile outjava jout
52 writeFile outjava jout
51 if (exec == Raw)
53 if (exec == Raw)
52 then copyFile outjava (takeDirectory out </> clsName <.> "java")
54 then copyFile outjava (takeDirectory out </> clsName <.> "java")
@@ -57,12 +59,16 @@ codegenJava globalInit defs out exec = do
57 (T.pack clsName)
59 (T.pack clsName)
58 (T.replace (T.pack "$ARTIFACT-NAME$")
60 (T.replace (T.pack "$ARTIFACT-NAME$")
59 (T.pack $ takeBaseName out)
61 (T.pack $ takeBaseName out)
62+ (T.replace (T.pack "$DEPENDENCIES$")
63+ (mkPomDependencies libs)
60− execPomTemplate)
64+ execPomTemplate
65+ )
66+ )
61 TIO.writeFile (tmpDir </> "pom.xml") execPom
67 TIO.writeFile (tmpDir </> "pom.xml") execPom
62 mvnCmd <- getMvn
68 mvnCmd <- getMvn
63 let args = ["-f", (tmpDir </> "pom.xml")]
69 let args = ["-f", (tmpDir </> "pom.xml")]
64− (exit, _, err) <- readProcessWithExitCode mvnCmd (args ++ ["compile"]) ""
70+ (exit, mvout, err) <- readProcessWithExitCode mvnCmd (args ++ ["compile"]) ""
65− when (exit /= ExitSuccess) $ error ("FAILURE: " ++ mvnCmd ++ " compile\n" ++ err)
71+ when (exit /= ExitSuccess) $ error ("FAILURE: " ++ mvnCmd ++ " compile\n" ++ err ++ mvout)
66 if (exec == Object)
72 if (exec == Object)
67 then do
73 then do
68 classFiles <-
74 classFiles <-
@@ -72,8 +78,8 @@ codegenJava globalInit defs out exec = do
72 mapM_ (\ clsFile -> copyFile clsFile (takeDirectory out </> takeFileName clsFile))
78 mapM_ (\ clsFile -> copyFile clsFile (takeDirectory out </> takeFileName clsFile))
73 classFiles
79 classFiles
74 else do
80 else do
75− (exit, _, err) <- readProcessWithExitCode mvnCmd (args ++ ["package"]) ""
81+ (exit, mvout, err) <- readProcessWithExitCode mvnCmd (args ++ ["package"]) ""
76− when (exit /= ExitSuccess) (error ("FAILURE: " ++ mvnCmd ++ " package\n" ++ err))
82+ when (exit /= ExitSuccess) (error ("FAILURE: " ++ mvnCmd ++ " package\n" ++ err ++ mvout))
77 copyFile (tmpDir </> "target" </> (takeBaseName out) <.> "jar") out
83 copyFile (tmpDir </> "target" </> (takeBaseName out) <.> "jar") out
78 handle <- openBinaryFile out ReadMode
84 handle <- openBinaryFile out ReadMode
79 contents <- TIO.hGetContents handle
85 contents <- TIO.hGetContents handle
@@ -99,21 +105,40 @@ jarHeader =
99 ++ "exec \"$java\" $java_args -jar $MYSELF \"$@\""
105 ++ "exec \"$java\" $java_args -jar $MYSELF \"$@\""
100 ++ "exit 1\n"
106 ++ "exit 1\n"
101
107
108+mkPomDependencies :: [String] -> T.Text
109+mkPomDependencies deps =
110+ T.concat $ map (T.concat . map (T.append (T.pack " ")) . mkDependency . T.pack) deps
111+ where
112+ mkDependency s =
113+ case T.splitOn (T.pack ":") s of
114+ [g, a, v] ->
115+ [ T.pack $ "<dependency>\n"
116+ , T.append (T.pack " ") $ mkGroupId g
117+ , T.append (T.pack " ") $ mkArtifactId a
118+ , T.append (T.pack " ") $ mkVersion v
119+ , T.pack $ "</dependency>\n"
120+ ]
121+ _ -> []
122+ mkGroupId g = T.append (T.pack $ "<groupId>") (T.append g $ T.pack "</groupId>\n")
123+ mkArtifactId a = T.append (T.pack $ "<artifactId>") (T.append a $ T.pack "</artifactId>\n")
124+ mkVersion v = T.append (T.pack $ "<version>") (T.append v $ T.pack "</version>\n")
125+
102mkCodeGenEnv :: [(Name, SExp)] -> CodeGenerationEnv
126mkCodeGenEnv :: [(Name, SExp)] -> CodeGenerationEnv
103mkCodeGenEnv globalInit =
127mkCodeGenEnv globalInit =
104 CodeGenerationEnv $ zipWith (\ (name, _) pos -> (name, pos)) globalInit [0..]
128 CodeGenerationEnv $ zipWith (\ (name, _) pos -> (name, pos)) globalInit [0..]
105
129
106−mkCompilationUnit :: [(Name, SExp)] -> [(Name, SDecl)] -> FilePath -> CodeGeneration CompilationUnit
130+mkCompilationUnit :: [(Name, SExp)] -> [(Name, SDecl)] -> [String] -> FilePath -> CodeGeneration CompilationUnit
107−mkCompilationUnit globalInit defs out =
131+mkCompilationUnit globalInit defs hdrs out =
108− CompilationUnit Nothing [ ImportDecl False idrisRts True
132+ CompilationUnit Nothing ( [ ImportDecl False idrisRts True
109− , ImportDecl True idrisForeign True
133+ , ImportDecl True idrisForeign True
110− , ImportDecl False bigInteger False
134+ , ImportDecl False bigInteger False
111− , ImportDecl False stringBuffer False
135+ , ImportDecl False stringBuffer False
112− , ImportDecl False runtimeException False
136+ , ImportDecl False runtimeException False
113− , ImportDecl False scanner False
137+ , ImportDecl False scanner False
114− , ImportDecl False arrays False
138+ , ImportDecl False arrays False
115− ] <$>
139+ ] ++ otherHdrs
140+ )
116− mkTypeDecl globalInit defs out
141+ <$> mkTypeDecl globalInit defs out
117 where
142 where
118 idrisRts = J.Name $ map Ident ["org", "idris", "rts"]
143 idrisRts = J.Name $ map Ident ["org", "idris", "rts"]
119 idrisForeign = J.Name $ map Ident ["org", "idris", "rts", "ForeignPrimitives"]
144 idrisForeign = J.Name $ map Ident ["org", "idris", "rts", "ForeignPrimitives"]
@@ -122,6 +147,12 @@ mkCompilationUnit globalInit defs out =
122 runtimeException = J.Name $ map Ident ["java", "lang", "RuntimeException"]
147 runtimeException = J.Name $ map Ident ["java", "lang", "RuntimeException"]
123 scanner = J.Name $ map Ident ["java", "util", "Scanner"]
148 scanner = J.Name $ map Ident ["java", "util", "Scanner"]
124 arrays = J.Name $ map Ident ["java", "util", "Arrays"]
149 arrays = J.Name $ map Ident ["java", "util", "Arrays"]
150+ otherHdrs = map ( (\ name -> ImportDecl False name False)
151+ . J.Name
152+ . map (Ident . T.unpack)
153+ . T.splitOn (T.pack ".")
154+ . T.pack)
155+ $ filter (not . isSuffixOf ".h") hdrs
125
156
126flatIndent :: String -> String
157flatIndent :: String -> String
127flatIndent (' ' : ' ' : xs) = flatIndent xs
158flatIndent (' ' : ' ' : xs) = flatIndent xs
@@ -337,6 +368,7 @@ mkIdentifier (UN name) =
337 cleanReserved "volatile" = "_volatile"
368 cleanReserved "volatile" = "_volatile"
338 cleanReserved "transient" = "_transient"
369 cleanReserved "transient" = "_transient"
339 cleanReserved "native" = "_native"
370 cleanReserved "native" = "_native"
371+ cleanReserved "const" = "_const"
340
372
341 cleanReserved "import" = "_import"
373 cleanReserved "import" = "_import"
342 cleanReserved "package" = "_package"
374 cleanReserved "package" = "_package"
@@ -410,9 +442,6 @@ idrisClosureType = ClassType [(Ident "Closure", [])]
410idrisTailCallClosureType :: ClassType
442idrisTailCallClosureType :: ClassType
411idrisTailCallClosureType = ClassType [(Ident "TailCallClosure", [])]
443idrisTailCallClosureType = ClassType [(Ident "TailCallClosure", [])]
412
444
413−--idrisFunctionType :: ClassType
414−--idrisFunctionType = ClassType [(Ident "IdrisFunction", [])]
415−
416idrisObjectType :: ClassType
445idrisObjectType :: ClassType
417idrisObjectType = ClassType [(Ident "IdrisObject", [])]
446idrisObjectType = ClassType [(Ident "IdrisObject", [])]
418
447
src/IRTS/CodegenJavaScript.hs+2−2
@@ -385,11 +385,11 @@ translateExpression (SForeign _ _ fun args)
385 , (obj:as) <- args =
385 , (obj:as) <- args =
386 concat [object obj, method, arguments as]
386 concat [object obj, method, arguments as]
387
387
388− | "[]=" == fun
388+ | "[]=" `isSuffixOf` fun
389 , (idx:val:[]) <- args =
389 , (idx:val:[]) <- args =
390 concat [array, index idx, assign val]
390 concat [array, index idx, assign val]
391
391
392− | "[]" == fun
392+ | "[]" `isSuffixOf` fun
393 , (idx:[]) <- args =
393 , (idx:[]) <- args =
394 array ++ index idx
394 array ++ index idx
395
395
src/IRTS/Compiler.hs+14−11
@@ -71,7 +71,7 @@ compile target f tm
71 (concatMap mkObj objs)
71 (concatMap mkObj objs)
72 (concatMap mkLib libs) NONE
72 (concatMap mkLib libs) NONE
73 ViaJava ->
73 ViaJava ->
74− codegenJava [] c f outty
74+ codegenJava [] c f hdrs libs outty
75 ViaJavaScript ->
75 ViaJavaScript ->
76 codegenJavaScript JavaScript c f outty
76 codegenJavaScript JavaScript c f outty
77 ViaNode ->
77 ViaNode ->
@@ -264,21 +264,24 @@ instance ToIR (TT Name) where
264 doForeign :: [Name] -> [TT Name] -> Idris LExp
264 doForeign :: [Name] -> [TT Name] -> Idris LExp
265 doForeign env (_ : fgn : args)
265 doForeign env (_ : fgn : args)
266 | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
266 | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
267− = let tys = getFTypes fgnArgTys
267+ = let maybeTys = getFTypes fgnArgTys
268 rty = mkIty' ret in
268 rty = mkIty' ret in
269+ case maybeTys of
270+ Nothing -> fail $ "Foreign type specification is not a constant list: " ++ show (fgn:args)
271+ Just tys -> do
269− do args' <- mapM (ir' env) args
272+ args' <- mapM (ir' env) args
270− -- wrap it in a prim__IO
273+ -- wrap it in a prim__IO
271− -- return $ con_ 0 @@ impossible @@
274+ -- return $ con_ 0 @@ impossible @@
272− return $ -- LLazyExp $
275+ return $ -- LLazyExp $
273− LForeign LANG_C rty fgnName (zip tys args')
276+ LForeign LANG_C rty fgnName (zip tys args')
274 | otherwise = fail "Badly formed foreign function call"
277 | otherwise = fail "Badly formed foreign function call"
275
278
276−getFTypes :: TT Name -> [FType]
279+getFTypes :: TT Name -> Maybe [FType]
277getFTypes tm = case unApply tm of
280getFTypes tm = case unApply tm of
278− (nil, []) -> []
281+ (nil, []) -> Just []
279 (cons, [ty, xs]) ->
282 (cons, [ty, xs]) ->
280− let rest = getFTypes xs in
281− mkIty' ty : rest
283+ fmap (mkIty' ty :) (getFTypes xs)
284+ _ -> Nothing
282
285
283mkIty' (P _ (UN ty) _) = mkIty ty
286mkIty' (P _ (UN ty) _) = mkIty ty
284mkIty' _ = FAny
287mkIty' _ = FAny
src/IRTS/LParser.hs+1−1
@@ -61,7 +61,7 @@ fovm tgt outty f
61 case checked of
61 case checked of
62 OK c -> case tgt of
62 OK c -> case tgt of
63 ViaC -> codegenC c "a.out" outty ["math.h"] "" "" TRACE
63 ViaC -> codegenC c "a.out" outty ["math.h"] "" "" TRACE
64− ViaJava -> codegenJava [] c "a.out" outty
64+ ViaJava -> codegenJava [] c "a.out" [] [] outty
65 Error e -> fail $ show e
65 Error e -> fail $ show e
66
66
67parseFOVM :: FilePath -> IO [(Name, LDecl)]
67parseFOVM :: FilePath -> IO [(Name, LDecl)]
src/Idris/AbsSyntax.hs+21
@@ -288,6 +288,12 @@ setREPL t = do i <- getIState
288 let opt' = opts { opt_repl = t }
288 let opt' = opts { opt_repl = t }
289 putIState $ i { idris_options = opt' }
289 putIState $ i { idris_options = opt' }
290
290
291+setQuiet :: Bool -> Idris ()
292+setQuiet q = do i <- getIState
293+ let opts = idris_options i
294+ let opt' = opts { opt_quiet = q }
295+ putIState $ i { idris_options = opt' }
296+
291setTarget :: Target -> Idris ()
297setTarget :: Target -> Idris ()
292setTarget t = do i <- getIState
298setTarget t = do i <- getIState
293 let opts = idris_options i
299 let opts = idris_options i
@@ -506,6 +512,7 @@ expandParams dec ps ns infs tm = en tm
506 PLet n' (en ty) (en v) (en (shadow n n' s))
512 PLet n' (en ty) (en v) (en (shadow n n' s))
507 | otherwise = PLet n (en ty) (en v) (en s)
513 | otherwise = PLet n (en ty) (en v) (en s)
508 en (PEq f l r) = PEq f (en l) (en r)
514 en (PEq f l r) = PEq f (en l) (en r)
515+ en (PRewrite f l r) = PRewrite f (en l) (en r)
509 en (PTyped l r) = PTyped (en l) (en r)
516 en (PTyped l r) = PTyped (en l) (en r)
510 en (PPair f l r) = PPair f (en l) (en r)
517 en (PPair f l r) = PPair f (en l) (en r)
511 en (PDPair f l t r) = PDPair f (en l) (en t) (en r)
518 en (PDPair f l t r) = PDPair f (en l) (en t) (en r)
@@ -641,6 +648,7 @@ getPriority i tm = 1 -- pri tm
641 pri (PFalse _) = 0
648 pri (PFalse _) = 0
642 pri (PRefl _ _) = 1
649 pri (PRefl _ _) = 1
643 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
650 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
651+ pri (PRewrite _ l r) = max 1 (max (pri l) (pri r))
644 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
652 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
645 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
653 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
646 pri (PTyped l r) = pri l
654 pri (PTyped l r) = pri l
@@ -751,6 +759,10 @@ implicitise syn ignore ist tm
751 = do (decls, ns) <- get
759 = do (decls, ns) <- get
752 let isn = namesIn uvars ist l ++ namesIn uvars ist r
760 let isn = namesIn uvars ist l ++ namesIn uvars ist r
753 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
761 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
762+ imps top env (PRewrite _ l r)
763+ = do (decls, ns) <- get
764+ let isn = namesIn uvars ist l ++ namesIn uvars ist r
765+ put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
754 imps top env (PTyped l r)
766 imps top env (PTyped l r)
755 = imps top env l
767 = imps top env l
756 imps top env (PPair _ l r)
768 imps top env (PPair _ l r)
@@ -810,6 +822,9 @@ addImpl' inpat env infns ist ptm = ai (zip env (repeat Nothing)) ptm
810 ai env (PEq fc l r) = let l' = ai env l
822 ai env (PEq fc l r) = let l' = ai env l
811 r' = ai env r in
823 r' = ai env r in
812 PEq fc l' r'
824 PEq fc l' r'
825+ ai env (PRewrite fc l r) = let l' = ai env l
826+ r' = ai env r in
827+ PRewrite fc l' r'
813 ai env (PTyped l r) = let l' = ai env l
828 ai env (PTyped l r) = let l' = ai env l
814 r' = ai env r in
829 r' = ai env r in
815 PTyped l' r'
830 PTyped l' r'
@@ -1065,6 +1080,10 @@ matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
1065 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
1080 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
1066 mr <- match' r r'
1081 mr <- match' r r'
1067 return (ml ++ mr)
1082 return (ml ++ mr)
1083+ match (PRewrite _ l r) (PRewrite _ l' r')
1084+ = do ml <- match' l l'
1085+ mr <- match' r r'
1086+ return (ml ++ mr)
1068 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
1087 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
1069 mr <- match r r'
1088 mr <- match r r'
1070 return (ml ++ mr)
1089 return (ml ++ mr)
@@ -1146,6 +1165,7 @@ substMatchShadow n shs tm t = sm shs t where
1146 sm xs (PApp f x as) = PApp f (sm xs x) (map (fmap (sm xs)) as)
1165 sm xs (PApp f x as) = PApp f (sm xs x) (map (fmap (sm xs)) as)
1147 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
1166 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
1148 sm xs (PEq f x y) = PEq f (sm xs x) (sm xs y)
1167 sm xs (PEq f x y) = PEq f (sm xs x) (sm xs y)
1168+ sm xs (PRewrite f x y) = PRewrite f (sm xs x) (sm xs y)
1149 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
1169 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
1150 sm xs (PPair f x y) = PPair f (sm xs x) (sm xs y)
1170 sm xs (PPair f x y) = PPair f (sm xs x) (sm xs y)
1151 sm xs (PDPair f x t y) = PDPair f (sm xs x) (sm xs t) (sm xs y)
1171 sm xs (PDPair f x t y) = PDPair f (sm xs x) (sm xs t) (sm xs y)
@@ -1161,6 +1181,7 @@ shadow n n' t = sm t where
1161 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
1181 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
1162 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
1182 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
1163 sm (PEq f x y) = PEq f (sm x) (sm y)
1183 sm (PEq f x y) = PEq f (sm x) (sm y)
1184+ sm (PRewrite f x y) = PRewrite f (sm x) (sm y)
1164 sm (PTyped x y) = PTyped (sm x) (sm y)
1185 sm (PTyped x y) = PTyped (sm x) (sm y)
1165 sm (PPair f x y) = PPair f (sm x) (sm y)
1186 sm (PPair f x y) = PPair f (sm x) (sm y)
1166 sm (PDPair f x t y) = PDPair f (sm x) (sm t) (sm y)
1187 sm (PDPair f x t y) = PDPair f (sm x) (sm t) (sm y)
src/Idris/AbsSyntaxTree.hs+46−17
@@ -24,23 +24,24 @@ import Data.Either
24
24
25import Debug.Trace
25import Debug.Trace
26
26
27−data IOption = IOption { opt_logLevel :: Int,
27+data IOption = IOption { opt_logLevel :: Int,
28− opt_typecase :: Bool,
28+ opt_typecase :: Bool,
29 opt_typeintype :: Bool,
29 opt_typeintype :: Bool,
30− opt_coverage :: Bool,
30+ opt_coverage :: Bool,
31− opt_showimp :: Bool,
31+ opt_showimp :: Bool,
32 opt_errContext :: Bool,
32 opt_errContext :: Bool,
33− opt_repl :: Bool,
33+ opt_repl :: Bool,
34− opt_verbose :: Bool,
34+ opt_verbose :: Bool,
35+ opt_quiet :: Bool,
35− opt_target :: Target,
36+ opt_target :: Target,
36− opt_outputTy :: OutputType,
37+ opt_outputTy :: OutputType,
37− opt_ibcsubdir :: FilePath,
38+ opt_ibcsubdir :: FilePath,
38 opt_importdirs :: [FilePath],
39 opt_importdirs :: [FilePath],
39− opt_cmdline :: [Opt] -- remember whole command line
40+ opt_cmdline :: [Opt] -- remember whole command line
40 }
41 }
41 deriving (Show, Eq)
42 deriving (Show, Eq)
42
43
43−defaultOpts = IOption 0 False False True False False True True ViaC Executable "" [] []
44+defaultOpts = IOption 0 False False True False False True True False ViaC Executable "" [] []
44
45
45-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
46-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
46-- without typechecking).
47-- without typechecking).
@@ -195,6 +196,7 @@ data Command = Quit
195data Opt = Filename String
196data Opt = Filename String
196 | Ver
197 | Ver
197 | Usage
198 | Usage
199+ | Quiet
198 | ShowLibs
200 | ShowLibs
199 | ShowLibdir
201 | ShowLibdir
200 | ShowIncs
202 | ShowIncs
@@ -386,12 +388,19 @@ declared (PFix _ _ _) = []
386declared (PTy _ _ _ _ n t) = [n]
388declared (PTy _ _ _ _ n t) = [n]
387declared (PPostulate _ _ _ _ n t) = [n]
389declared (PPostulate _ _ _ _ n t) = [n]
388declared (PClauses _ _ n _) = [] -- not a declaration
390declared (PClauses _ _ n _) = [] -- not a declaration
389−declared (PRecord _ _ _ n _ _ c _) = [n, c]
391+declared (PCAF _ n _) = [n]
390declared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
392declared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
391 where fstt (_, a, _, _) = a
393 where fstt (_, a, _, _) = a
394+declared (PData _ _ _ _ (PLaterdecl n _)) = [n]
392declared (PParams _ _ ds) = concatMap declared ds
395declared (PParams _ _ ds) = concatMap declared ds
393−declared (PMutual _ ds) = concatMap declared ds
394declared (PNamespace _ ds) = concatMap declared ds
396declared (PNamespace _ ds) = concatMap declared ds
397+declared (PRecord _ _ _ n _ _ c _) = [n, c]
398+declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
399+declared (PInstance _ _ _ _ _ _ _ _) = []
400+declared (PDSL n _) = [n]
401+declared (PSyntax _ _) = []
402+declared (PMutual _ ds) = concatMap declared ds
403+declared (PDirective _) = []
395
404
396-- get the names declared, not counting nested parameter blocks
405-- get the names declared, not counting nested parameter blocks
397tldeclared :: PDecl -> [Name]
406tldeclared :: PDecl -> [Name]
@@ -405,20 +414,27 @@ tldeclared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
405tldeclared (PParams _ _ ds) = []
414tldeclared (PParams _ _ ds) = []
406tldeclared (PMutual _ ds) = concatMap tldeclared ds
415tldeclared (PMutual _ ds) = concatMap tldeclared ds
407tldeclared (PNamespace _ ds) = concatMap tldeclared ds
416tldeclared (PNamespace _ ds) = concatMap tldeclared ds
408−-- declared (PImport _) = []
417+
409
418
410defined :: PDecl -> [Name]
419defined :: PDecl -> [Name]
411defined (PFix _ _ _) = []
420defined (PFix _ _ _) = []
412defined (PTy _ _ _ _ n t) = []
421defined (PTy _ _ _ _ n t) = []
413defined (PPostulate _ _ _ _ n t) = []
422defined (PPostulate _ _ _ _ n t) = []
414defined (PClauses _ _ n _) = [n] -- not a declaration
423defined (PClauses _ _ n _) = [n] -- not a declaration
415−defined (PRecord _ _ _ n _ _ c _) = [n, c]
424+defined (PCAF _ n _) = [n]
416defined (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
425defined (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
417 where fstt (_, a, _, _) = a
426 where fstt (_, a, _, _) = a
427+defined (PData _ _ _ _ (PLaterdecl n _)) = []
418defined (PParams _ _ ds) = concatMap defined ds
428defined (PParams _ _ ds) = concatMap defined ds
419−defined (PMutual _ ds) = concatMap defined ds
420defined (PNamespace _ ds) = concatMap defined ds
429defined (PNamespace _ ds) = concatMap defined ds
421−-- declared (PImport _) = []
430+defined (PRecord _ _ _ n _ _ c _) = [n, c]
431+defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
432+defined (PInstance _ _ _ _ _ _ _ _) = []
433+defined (PDSL n _) = [n]
434+defined (PSyntax _ _) = []
435+defined (PMutual _ ds) = concatMap defined ds
436+defined (PDirective _) = []
437+--defined _ = []
422
438
423updateN :: [(Name, Name)] -> Name -> Name
439updateN :: [(Name, Name)] -> Name -> Name
424updateN ns n | Just n' <- lookup n ns = n'
440updateN ns n | Just n' <- lookup n ns = n'
@@ -457,6 +473,7 @@ data PTerm = PQuote Raw
457 | PRefl FC PTerm
473 | PRefl FC PTerm
458 | PResolveTC FC
474 | PResolveTC FC
459 | PEq FC PTerm PTerm
475 | PEq FC PTerm PTerm
476+ | PRewrite FC PTerm PTerm
460 | PPair FC PTerm PTerm
477 | PPair FC PTerm PTerm
461 | PDPair FC PTerm PTerm PTerm
478 | PDPair FC PTerm PTerm PTerm
462 | PAlternative Bool [PTerm] -- True if only one may work
479 | PAlternative Bool [PTerm] -- True if only one may work
@@ -483,6 +500,7 @@ mapPT f t = f (mpt t) where
483 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
500 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
484 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
501 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
485 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
502 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
503+ mpt (PRewrite fc t s) = PRewrite fc (mapPT f t) (mapPT f s)
486 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
504 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
487 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
505 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
488 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
506 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
@@ -893,6 +911,12 @@ prettyImp impl = prettySe 10
893 prettySe 10 l <+> text "=" $$ nest nestingSize (prettySe 10 r)
911 prettySe 10 l <+> text "=" $$ nest nestingSize (prettySe 10 r)
894 else
912 else
895 prettySe 10 l <+> text "=" <+> prettySe 10 r
913 prettySe 10 l <+> text "=" <+> prettySe 10 r
914+ prettySe p (PRewrite _ l r) =
915+ bracket p 2 $
916+ if size r > breakingSize then
917+ text "rewrite" <+> prettySe 10 l <+> text "in" $$ nest nestingSize (prettySe 10 r)
918+ else
919+ text "rewrite" <+> prettySe 10 l <+> text "in" <+> prettySe 10 r
896 prettySe p (PTyped l r) =
920 prettySe p (PTyped l r) =
897 lparen <> prettySe 10 l <+> colon <+> prettySe 10 r <> rparen
921 lparen <> prettySe 10 l <+> colon <+> prettySe 10 r <> rparen
898 prettySe p (PPair _ l r) =
922 prettySe p (PPair _ l r) =
@@ -1000,6 +1024,7 @@ showImp impl tm = se 10 tm where
1000 se p (PTrue _) = "()"
1024 se p (PTrue _) = "()"
1001 se p (PFalse _) = "_|_"
1025 se p (PFalse _) = "_|_"
1002 se p (PEq _ l r) = bracket p 2 $ se 10 l ++ " = " ++ se 10 r
1026 se p (PEq _ l r) = bracket p 2 $ se 10 l ++ " = " ++ se 10 r
1027+ se p (PRewrite _ l r) = bracket p 2 $ "rewrite " ++ se 10 l ++ " in " ++ se 10 r
1003 se p (PTyped l r) = "(" ++ se 10 l ++ " : " ++ se 10 r ++ ")"
1028 se p (PTyped l r) = "(" ++ se 10 l ++ " : " ++ se 10 r ++ ")"
1004 se p (PPair _ l r) = "(" ++ se 10 l ++ ", " ++ se 10 r ++ ")"
1029 se p (PPair _ l r) = "(" ++ se 10 l ++ ", " ++ se 10 r ++ ")"
1005 se p (PDPair _ l t r) = "(" ++ se 10 l ++ " ** " ++ se 10 r ++ ")"
1030 se p (PDPair _ l t r) = "(" ++ se 10 l ++ " ** " ++ se 10 r ++ ")"
@@ -1045,6 +1070,7 @@ instance Sized PTerm where
1045 size (PRefl fc _) = 1
1070 size (PRefl fc _) = 1
1046 size (PResolveTC fc) = 1
1071 size (PResolveTC fc) = 1
1047 size (PEq fc left right) = 1 + size left + size right
1072 size (PEq fc left right) = 1 + size left + size right
1073+ size (PRewrite fc left right) = 1 + size left + size right
1048 size (PPair fc left right) = 1 + size left + size right
1074 size (PPair fc left right) = 1 + size left + size right
1049 size (PDPair fs left ty right) = 1 + size left + size ty + size right
1075 size (PDPair fs left ty right) = 1 + size left + size ty + size right
1050 size (PAlternative a alts) = 1 + size alts
1076 size (PAlternative a alts) = 1 + size alts
@@ -1077,6 +1103,7 @@ allNamesIn tm = nub $ ni [] tm
1077 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1103 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1078 ni env (PHidden tm) = ni env tm
1104 ni env (PHidden tm) = ni env tm
1079 ni env (PEq _ l r) = ni env l ++ ni env r
1105 ni env (PEq _ l r) = ni env l ++ ni env r
1106+ ni env (PRewrite _ l r) = ni env l ++ ni env r
1080 ni env (PTyped l r) = ni env l ++ ni env r
1107 ni env (PTyped l r) = ni env l ++ ni env r
1081 ni env (PPair _ l r) = ni env l ++ ni env r
1108 ni env (PPair _ l r) = ni env l ++ ni env r
1082 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1109 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
@@ -1099,6 +1126,7 @@ namesIn uvars ist tm = nub $ ni [] tm
1099 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1126 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1100 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1127 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1101 ni env (PEq _ l r) = ni env l ++ ni env r
1128 ni env (PEq _ l r) = ni env l ++ ni env r
1129+ ni env (PRewrite _ l r) = ni env l ++ ni env r
1102 ni env (PTyped l r) = ni env l ++ ni env r
1130 ni env (PTyped l r) = ni env l ++ ni env r
1103 ni env (PPair _ l r) = ni env l ++ ni env r
1131 ni env (PPair _ l r) = ni env l ++ ni env r
1104 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1132 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
@@ -1122,6 +1150,7 @@ usedNamesIn vars ist tm = nub $ ni [] tm
1122 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1150 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1123 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1151 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1124 ni env (PEq _ l r) = ni env l ++ ni env r
1152 ni env (PEq _ l r) = ni env l ++ ni env r
1153+ ni env (PRewrite _ l r) = ni env l ++ ni env r
1125 ni env (PTyped l r) = ni env l ++ ni env r
1154 ni env (PTyped l r) = ni env l ++ ni env r
1126 ni env (PPair _ l r) = ni env l ++ ni env r
1155 ni env (PPair _ l r) = ni env l ++ ni env r
1127 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1156 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
src/Idris/Delaborate.hs+1
@@ -109,6 +109,7 @@ pshow i (NonCollapsiblePostulate n)
109 = "The return type of postulate " ++ show n ++ " is not collapsible"
109 = "The return type of postulate " ++ show n ++ " is not collapsible"
110pshow i (AlreadyDefined n) = show n ++ " is already defined"
110pshow i (AlreadyDefined n) = show n ++ " is already defined"
111pshow i (ProofSearchFail e) = pshow i e
111pshow i (ProofSearchFail e) = pshow i e
112+pshow i (NoRewriting tm) = "rewrite did not change type " ++ show (delab i tm)
112pshow i (At f e) = show f ++ ":" ++ pshow i e
113pshow i (At f e) = show f ++ ":" ++ pshow i e
113
114
114showSc i [] = ""
115showSc i [] = ""
src/Idris/ElabTerm.hs+17
@@ -407,6 +407,23 @@ elab ist info pattern tcgen fn tm
407 | not pattern = do mapM_ (runTac False ist) ts
407 | not pattern = do mapM_ (runTac False ist) ts
408 | otherwise = elab' ina Placeholder
408 | otherwise = elab' ina Placeholder
409 elab' ina (PElabError e) = fail (pshow ist e)
409 elab' ina (PElabError e) = fail (pshow ist e)
410+ elab' ina (PRewrite fc r sc)
411+ = do attack
412+ tyn <- unique_hole (MN 0 "rty")
413+ claim tyn RType
414+ valn <- unique_hole (MN 0 "rval")
415+ claim valn (Var tyn)
416+ letn <- unique_hole (MN 0 "rewrite_rule")
417+ letbind letn (Var tyn) (Var valn)
418+ focus valn
419+ elab' ina r
420+ compute
421+ g <- goal
422+ rewrite (Var letn)
423+ g' <- goal
424+ when (g == g') $ lift $ tfail (NoRewriting g)
425+ elab' ina sc
426+ solve
410 elab' ina@(_, a) c@(PCase fc scr opts)
427 elab' ina@(_, a) c@(PCase fc scr opts)
411 = do attack
428 = do attack
412 tyn <- unique_hole (MN 0 "scty")
429 tyn <- unique_hole (MN 0 "scty")
src/Idris/IBC.hs+8
@@ -1265,6 +1265,10 @@ instance Binary PTerm where
1265 PInferRef x1 x2 -> do putWord8 29
1265 PInferRef x1 x2 -> do putWord8 29
1266 put x1
1266 put x1
1267 put x2
1267 put x2
1268+ PRewrite x1 x2 x3 -> do putWord8 30
1269+ put x1
1270+ put x2
1271+ put x3
1268 get
1272 get
1269 = do i <- getWord8
1273 = do i <- getWord8
1270 case i of
1274 case i of
@@ -1349,6 +1353,10 @@ instance Binary PTerm where
1349 29 -> do x1 <- get
1353 29 -> do x1 <- get
1350 x2 <- get
1354 x2 <- get
1351 return (PInferRef x1 x2)
1355 return (PInferRef x1 x2)
1356+ 30 -> do x1 <- get
1357+ x2 <- get
1358+ x3 <- get
1359+ return (PRewrite x1 x2 x3)
1352 _ -> error "Corrupted binary data for PTerm"
1360 _ -> error "Corrupted binary data for PTerm"
1353
1361
1354instance (Binary t) => Binary (PTactic' t) where
1362instance (Binary t) => Binary (PTactic' t) where
src/Idris/Parser.hs+9
@@ -610,6 +610,7 @@ pNoExtExpr syn =
610 <|> try (pSimpleExpr syn)
610 <|> try (pSimpleExpr syn)
611 <|> pLambda syn
611 <|> pLambda syn
612 <|> pLet syn
612 <|> pLet syn
613+ <|> pRewriteTerm syn
613 <|> pPi syn
614 <|> pPi syn
614 <|> pDoBlock syn
615 <|> pDoBlock syn
615 <|> pComprehension syn
616 <|> pComprehension syn
@@ -940,6 +941,14 @@ pLambda syn = do lchar '\\'
940 (PCase fc (PRef fc (MN i "lamp"))
941 (PCase fc (PRef fc (MN i "lamp"))
941 [(x, pmList xs sc)])
942 [(x, pmList xs sc)])
942
943
944+pRewriteTerm syn =
945+ do reserved "rewrite"
946+ fc <- pfc
947+ prf <- pExpr syn
948+ reserved "in"; sc <- pExpr syn
949+ return (PRewrite fc
950+ (PApp fc (PRef fc (UN "sym")) [pexp prf]) sc)
951+
943pLet syn = try (do reserved "let"; n <- pName;
952pLet syn = try (do reserved "let"; n <- pName;
944 ty <- option Placeholder (do lchar ':'; pExpr' syn)
953 ty <- option Placeholder (do lchar ':'; pExpr' syn)
945 lchar '='
954 lchar '='
src/Idris/REPL.hs+13−5
@@ -61,10 +61,13 @@ repl :: IState -- ^ The initial state
61 -> InputT Idris ()
61 -> InputT Idris ()
62repl orig mods
62repl orig mods
63 = H.catch
63 = H.catch
64+ (do let quiet = opt_quiet (idris_options orig)
65+ let prompt = if quiet
66+ then ""
64− (do let prompt = mkPrompt mods
67+ else mkPrompt mods ++ "> "
65− x <- getInputLine (prompt ++ "> ")
68+ x <- getInputLine prompt
66 case x of
69 case x of
67− Nothing -> do lift $ iputStrLn "Bye bye"
70+ Nothing -> do lift $ when (not quiet) (iputStrLn "Bye bye")
68 return ()
71 return ()
69 Just input -> H.catch
72 Just input -> H.catch
70 (do ms <- lift $ processInput input orig mods
73 (do ms <- lift $ processInput input orig mods
@@ -90,6 +93,8 @@ lit f = case splitExtension f of
90processInput :: String -> IState -> [FilePath] -> Idris (Maybe [FilePath])
93processInput :: String -> IState -> [FilePath] -> Idris (Maybe [FilePath])
91processInput cmd orig inputs
94processInput cmd orig inputs
92 = do i <- getIState
95 = do i <- getIState
96+ let opts = idris_options i
97+ let quiet = opt_quiet opts
93 let fn = case inputs of
98 let fn = case inputs of
94 (f:_) -> f
99 (f:_) -> f
95 _ -> ""
100 _ -> ""
@@ -114,7 +119,7 @@ processInput cmd orig inputs
114 return (Just inputs)
119 return (Just inputs)
115 Right Proofs -> do proofs orig
120 Right Proofs -> do proofs orig
116 return (Just inputs)
121 return (Just inputs)
117− Right Quit -> do iputStrLn "Bye bye"
122+ Right Quit -> do when (not quiet) (iputStrLn "Bye bye")
118 return Nothing
123 return Nothing
119 Right cmd -> do idrisCatch (process fn cmd)
124 Right cmd -> do idrisCatch (process fn cmd)
120 (\e -> iputStrLn (show e))
125 (\e -> iputStrLn (show e))
@@ -453,6 +458,7 @@ parseTarget _ = error "unknown target" -- FIXME: partial function
453
458
454parseArgs :: [String] -> [Opt]
459parseArgs :: [String] -> [Opt]
455parseArgs [] = []
460parseArgs [] = []
461+parseArgs ("--quiet":ns) = Quiet : (parseArgs ns)
456parseArgs ("--log":lvl:ns) = OLogging (read lvl) : (parseArgs ns)
462parseArgs ("--log":lvl:ns) = OLogging (read lvl) : (parseArgs ns)
457parseArgs ("--noprelude":ns) = NoPrelude : (parseArgs ns)
463parseArgs ("--noprelude":ns) = NoPrelude : (parseArgs ns)
458parseArgs ("--check":ns) = NoREPL : (parseArgs ns)
464parseArgs ("--check":ns) = NoREPL : (parseArgs ns)
@@ -504,6 +510,7 @@ idris opts = execStateT (idrisMain opts) idrisInit
504idrisMain :: [Opt] -> Idris ()
510idrisMain :: [Opt] -> Idris ()
505idrisMain opts =
511idrisMain opts =
506 do let inputs = opt getFile opts
512 do let inputs = opt getFile opts
513+ let quiet = Quiet `elem` opts
507 let runrepl = not (NoREPL `elem` opts)
514 let runrepl = not (NoREPL `elem` opts)
508 let output = opt getOutput opts
515 let output = opt getOutput opts
509 let newoutput = opt getNewOutput opts
516 let newoutput = opt getNewOutput opts
@@ -521,6 +528,7 @@ idrisMain opts =
521 when (DefaultTotal `elem` opts) $ do i <- getIState
528 when (DefaultTotal `elem` opts) $ do i <- getIState
522 putIState (i { default_total = True })
529 putIState (i { default_total = True })
523 setREPL runrepl
530 setREPL runrepl
531+ setQuiet quiet
524 setVerbose runrepl
532 setVerbose runrepl
525 setCmdLine opts
533 setCmdLine opts
526 setOutputTy outty
534 setOutputTy outty
@@ -544,7 +552,7 @@ idrisMain opts =
544 elabPrims
552 elabPrims
545 when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude"
553 when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude"
546 return ()
554 return ()
547− when runrepl $ iputStrLn banner
555+ when (runrepl && not quiet) $ iputStrLn banner
548 ist <- getIState
556 ist <- getIState
549 mods <- mapM loadModule inputs
557 mods <- mapM loadModule inputs
550 ok <- noErrors
558 ok <- noErrors
src/Main.hs+1
@@ -78,6 +78,7 @@ usagemsg = "Idris version " ++ ver ++ "\n" ++
78 "--------------" ++ map (\x -> '-') ver ++ "\n" ++
78 "--------------" ++ map (\x -> '-') ver ++ "\n" ++
79 "Usage: idris [input file] [options]\n" ++
79 "Usage: idris [input file] [options]\n" ++
80 "Options:\n" ++
80 "Options:\n" ++
81+ "\t--quiet Quiet mode (for editors)\n" ++
81 "\t--check Type check only\n" ++
82 "\t--check Type check only\n" ++
82 "\t-o [file] Specify output filename\n" ++
83 "\t-o [file] Specify output filename\n" ++
83 "\t-i [dir] Add directory to the list of import paths\n" ++
84 "\t-i [dir] Add directory to the list of import paths\n" ++
test/reg012/reg012.lidr+4−2
@@ -28,5 +28,7 @@
28> (ab : (alpha, beta)) ->
28> (ab : (alpha, beta)) ->
29> modifyFun f ab (fst ab) = snd ab
29> modifyFun f ab (fst ab) = snd ab
30> modifyFunLemma f (a,b) =
30> modifyFunLemma f (a,b) =
31+> rewrite soTrue (reflexive_eqeq a) in refl
32+
31−> replace {P = \ z => boolElim (a == a) b (f a) = boolElim z b (f a)}
33+ replace {P = \ z => boolElim (a == a) b (f a) = boolElim z b (f a)}
32−> (soTrue (reflexive_eqeq a)) refl
34+ (soTrue (reflexive_eqeq a)) refl