on master help sign in
Merge remote-tracking branch 'upstream/master' into providers
commit161ef3d70fc28629aaf72b003ab805f0d41854d3 authorDavid Christiansen <david@davidchristiansen.dk> dateThu 21 Mar 2013, 16:20 (14 years ago) parent918ce77c3dcf56
34 files changed+607−230
CHANGELOG+1 contribs/tool-support/sublime-text/Idris/Idris.JSON-tmLanguage+70 contribs/tool-support/sublime-text/Idris/Idris.tmLanguage+126 contribs/tool-support/sublime-text/Idris/idris.sublime-build+5 contribs/tool-support/sublime-text/README.md+11 contribs/tool-support/vim/indent/idris.vim+11−1 contribs/tool-support/vim/syntax/idris.vim+3−3 effects/Effect/Exception.idr+3 effects/Effect/StdIO.idr+5−4 effects/Effects.idr+4−2 java/executable_pom_template.xml+1 java/src/main/java/org/idris/rts/ForeignPrimitives.java+138−123 lib/IO.idr+2−4 rts/idris_gc.c+1−3 rts/idris_rts.c+2−18 rts/idris_rts.h+1−5 rts/idris_stats.c+19−4 samples/javaffi.idr+12 src/Core/CoreParser.hs+1−1 src/Core/ProofState.hs+1−2 src/Core/TT.hs+2 src/IRTS/CodegenJava.hs+51−22 src/IRTS/CodegenJavaScript.hs+2−2 src/IRTS/Compiler.hs+14−11 src/IRTS/LParser.hs+1−1 src/Idris/AbsSyntax.hs+21 src/Idris/AbsSyntaxTree.hs+46−17 src/Idris/Delaborate.hs+1 src/Idris/ElabTerm.hs+17 src/Idris/IBC.hs+8 src/Idris/Parser.hs+9 src/Idris/REPL.hs+13−5 src/Main.hs+1 test/reg012/reg012.lidr+4−2
CHANGELOG+1
@@ -3,6 +3,7 @@ New in 0.9.8:
33
44User visible changes:
55
6+* Added "rewrite ... in ..." construct
67* Renamed EFF to EFFECT in Effect package
78* Experimental Java backend
89* 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 @@
33" Based on haskell indentation by motemen <motemen@gmail.com>
44"
55" author: raichoo (raichoo@googlemail.com)
6−" date: Nov 2 2012
6+" date: Mar 19 2013
77"
88" Modify g:idris_indent_if and g:idris_indent_case to
99" change indentation for `if'(default 3) and `case'(default 5).
@@ -36,6 +36,12 @@ if !exists('g:idris_indent_let')
3636 let g:idris_indent_let = 4
3737endif
3838
39+if !exists('g:idris_indent_rewrite')
40+ " rewrite prf in expr
41+ " >>>>x
42+ let g:idris_indent_rewrite = 8
43+endif
44+
3945if !exists('g:idris_indent_where')
4046 " where f : Nat -> Nat
4147 " >>>>>>f x = x
@@ -71,6 +77,10 @@ function! GetIdrisIndent()
7177 return match(prevline, 'let') + g:idris_indent_let
7278 endif
7379
80+ if prevline =~ '\<rewrite\>\s\+.\+\<in\>\s*$'
81+ return match(prevline, 'rewrite') + g:idris_indent_rewrite
82+ endif
83+
7484 if prevline !~ '\<else\>'
7585 let s = match(prevline, '\<if\>.*\&.*\zs\<then\>')
7686 if s > 0
contribs/tool-support/vim/syntax/idris.vim+3−3
@@ -4,7 +4,7 @@
44" highlighter to support idris.
55"
66" author: raichoo (raichoo@googlemail.com)
7−" date: Mar 12 2013
7+" date: Mar 20 2013
88
99syn match idrisModule "\<\(module\|namespace\)\>"
1010syn match idrisImport "\<import\>"
@@ -12,7 +12,7 @@ syn match idrisStructure "\<\(class\|\(co\)\?data\|instance\|where\|record\|dsl\
1212syn match idrisVisibility "\<\(public\|abstract\|private\)\>"
1313syn match idrisBlock "\<\(parameters\|mutual\|postulate\|using\)\>"
1414syn 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\)\>"
1616syn match idrisSyntax "\(pattern \+\|term \+\)\?syntax"
1717syn match idrisConditional "\<\(if\|then\|else\)\>"
1818syn 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\)"
2828syn match idrisDirective "%\(access\|default\|assert_total\)"
2929syn match idrisDSL "\(lambda\|variable\|\index_first\|index_next\)"
3030syn region idrisString start=+"+ skip=+\\\\\|\\"+ end=+"+
31−syn region idrisBlockComment start="{-" end="-}"
31+syn region idrisBlockComment start="{-" end="-}" contains=idrisBlockComment
3232syn region idrisProofBlock start="\(default\s\+\)\?\(proof\|tactics\) *{" end="}" contains=idrisTactic
3333
3434syn match idrisBadLeadingWhiteSpace "^\s*\t\+"
effects/Effect/Exception.idr+3
@@ -17,6 +17,9 @@ instance Show a => Handler (Exception a) IO where
1717instance Handler (Exception a) (IOExcept a) where
1818 handle _ (Raise e) k = ioM (return (Left e))
1919
20+instance Handler (Exception a) (Either a) where
21+ handle _ (Raise e) k = Left e
22+
2023EXCEPTION : Type -> EFFECT
2124EXCEPTION t = MkEff () (Exception t)
2225
effects/Effect/StdIO.idr+5−4
@@ -19,9 +19,6 @@ instance Handler StdIO (IOExcept a) where
1919
2020data IOStream a = MkStream (List String -> (a, List String))
2121
22−injStream : a -> IOStream a
23−injStream v = MkStream (\x => (v, []))
24−
2522instance Handler StdIO IOStream where
2623 handle () (PutStr s) k
2724 = MkStream (\x => case k () () of
@@ -55,5 +52,9 @@ mkStrFn : Env IOStream xs ->
5552 List String -> (a, List String)
5653mkStrFn {a} env p input = case mkStrFn' of
5754 MkStream f => f input
58− where mkStrFn' : IOStream a
55+ where injStream : a -> IOStream a
56+ injStream v = MkStream (\x => (v, []))
57+ mkStrFn' : IOStream a
5958 mkStrFn' = runWith injStream env p
59+
60+
effects/Effects.idr+4−2
@@ -100,8 +100,7 @@ data EffM : (m : Type -> Type) ->
100100 List EFFECT -> List EFFECT -> Type -> Type where
101101 value : a -> EffM m xs xs a
102102 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) ->
105104 (eff : e a b t) ->
106105 EffM m xs (updateResTy xs prf eff) t
107106 lift : (prf : SubList ys xs) ->
@@ -189,6 +188,9 @@ runEnv env prog = eff env prog (\env, r => pure (env, r))
189188runPure : Env id xs -> EffM id xs xs' a -> a
190189runPure env prog = eff env prog (\env, r => r)
191190
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+
192194runWith : (a -> m a) -> Env m xs -> EffM m xs xs' a -> m a
193195runWith inj env prog = eff env prog (\env, r => inj r)
194196
java/executable_pom_template.xml+1
@@ -17,6 +17,7 @@
1717 <artifactId>idris</artifactId>
1818 <version>$RTS-VERSION$</version>
1919 </dependency>
20+$DEPENDENCIES$
2021 </dependencies>
2122
2223
java/src/main/java/org/idris/rts/ForeignPrimitives.java+138−123
@@ -1,5 +1,6 @@
11package org.idris.rts;
22
3+import java.lang.reflect.InvocationTargetException;
34import java.util.Arrays;
45import java.util.List;
56import java.util.Map;
@@ -9,7 +10,6 @@ import java.util.HashSet;
910import java.io.Closeable;
1011import java.io.File;
1112import java.io.IOException;
12−import java.io.EOFException;
1313import java.io.PrintStream;
1414import java.io.InputStream;
1515import java.nio.ByteBuffer;
@@ -25,190 +25,205 @@ import java.util.concurrent.Semaphore;
2525
2626@SuppressWarnings("unchecked")
2727public class ForeignPrimitives {
28+
2829 private static final Map<Thread, List<String>> args = new HashMap<>();
2930 private static final Semaphore messageMutex = new Semaphore(1);
3031 private static final Map<Thread, BlockingQueue<Object>> messages = new HashMap<>();
3132 private static final Set<Object> feofFiles = new HashSet<>();
3233
33− public static synchronized void idris_initArgs(Thread t, String [] args) {
34− ForeignPrimitives.args.put(t, Arrays.asList(args));
34+ public static synchronized void idris_initArgs(Thread t, String[] args) {
35+ ForeignPrimitives.args.put(t, Arrays.asList(args));
3536 }
3637
3738 public static synchronized int idris_numArgs(Object thread) {
38− List<String> argsForThread = ForeignPrimitives.args.get((Thread)thread);
39− return (argsForThread == null ? 0 : argsForThread.size());
39+ List<String> argsForThread = ForeignPrimitives.args.get((Thread) thread);
40+ return (argsForThread == null ? 0 : argsForThread.size());
4041 }
4142
4243 public static synchronized String idris_getArg(Object thread, int num) {
43− List<String> argsForThread = ForeignPrimitives.args.get((Thread)thread);
44− return (argsForThread == null ? null : argsForThread.get(num));
44+ List<String> argsForThread = ForeignPrimitives.args.get((Thread) thread);
45+ return (argsForThread == null ? null : argsForThread.get(num));
4546 }
4647
4748 public static String getenv(String x) {
48− return System.getenv(x);
49+ return System.getenv(x);
4950 }
5051
5152 public static void exit(int exitCode) {
52− System.exit(exitCode);
53+ System.exit(exitCode);
5354 }
5455
5556 public static void usleep(int microsecs) {
56− try {
57− Thread.sleep(microsecs / 1000, microsecs % 1000);
58− } catch (InterruptedException ex) {
59− }
57+ try {
58+ Thread.sleep(microsecs / 1000, microsecs % 1000);
59+ } catch (InterruptedException ex) {
60+ }
6061 }
6162
6263 public static void idris_sendMessage(Object from, Object dest, Object message) throws InterruptedException {
63− messageMutex.acquire();
64− BlockingQueue<Object> messagesForTarget = messages.get((Thread)dest);
65− if (messagesForTarget == null) {
66− messagesForTarget = new LinkedBlockingQueue<>();
67− messages.put((Thread)dest, messagesForTarget);
68− }
69− messagesForTarget.put(message);
64+ messageMutex.acquire();
65+ BlockingQueue<Object> messagesForTarget = messages.get((Thread) dest);
66+ if (messagesForTarget == null) {
67+ messagesForTarget = new LinkedBlockingQueue<>();
68+ messages.put((Thread) dest, messagesForTarget);
69+ }
70+ messagesForTarget.put(message);
7071 messageMutex.release();
7172 }
7273
7374 public static int idris_checkMessage(Object dest) throws InterruptedException {
74− messageMutex.acquire();
75− BlockingQueue<Object> messagesForTarget = messages.get((Thread)dest);
76− messageMutex.release();
77− return (messagesForTarget == null ? 0 : messagesForTarget.size());
75+ messageMutex.acquire();
76+ BlockingQueue<Object> messagesForTarget = messages.get((Thread) dest);
77+ messageMutex.release();
78+ return (messagesForTarget == null ? 0 : messagesForTarget.size());
7879 }
7980
8081 public static Object idris_recvMessage(Object dest) throws InterruptedException {
81− messageMutex.acquire();
82− BlockingQueue<Object> messagesForTarget = messages.get((Thread)dest);
83− if (messagesForTarget == null) {
84− messagesForTarget = new LinkedBlockingQueue();
85− messages.put((Thread)dest, messagesForTarget);
86− }
87− messageMutex.release();
88− return messagesForTarget.take();
82+ messageMutex.acquire();
83+ BlockingQueue<Object> messagesForTarget = messages.get((Thread) dest);
84+ if (messagesForTarget == null) {
85+ messagesForTarget = new LinkedBlockingQueue();
86+ messages.put((Thread) dest, messagesForTarget);
87+ }
88+ messageMutex.release();
89+ return messagesForTarget.take();
8990 }
9091
9192 public static void putStr(String str) {
92− System.out.print(str);
93+ System.out.print(str);
9394 }
9495
9596 public static void putchar(char c) {
96− System.out.print(c);
97+ System.out.print(c);
9798 }
9899
99100 public static int getchar() {
100− try {
101− return (char)System.in.read();
102− } catch (IOException ex) {
103− return -1;
104− }
101+ try {
102+ return (char) System.in.read();
103+ } catch (IOException ex) {
104+ return -1;
105+ }
105106 }
106107
107108 public static SeekableByteChannel fileOpen(String name, String privs) {
108− try {
109− OpenOption [] options;
110− switch (privs) {
111− case "r" :
112− options = new StandardOpenOption []
113− { StandardOpenOption.READ };
114− break;
115− case "r+" :
116− options = new StandardOpenOption []
117− { StandardOpenOption.READ,
118− StandardOpenOption.WRITE };
119− break;
120− case "w" :
121− options = new StandardOpenOption []
122− { StandardOpenOption.WRITE,
123− StandardOpenOption.CREATE };
124− break;
125− case "w+" :
126− options = new StandardOpenOption []
127− { StandardOpenOption.READ,
128− StandardOpenOption.WRITE,
129− StandardOpenOption.CREATE };
130− break;
131− case "a" :
132− options = new StandardOpenOption []
133− { StandardOpenOption.WRITE,
134− StandardOpenOption.CREATE,
135− StandardOpenOption.APPEND };
136− break;
137− case "a+" :
138− options = new StandardOpenOption []
139− { StandardOpenOption.READ,
140− StandardOpenOption.WRITE,
141− StandardOpenOption.CREATE,
142− StandardOpenOption.APPEND };
143− break;
144− default :
145− options = new StandardOpenOption [] {};
146− break;
147− }
148− return Files.newByteChannel(new File(name).toPath(), options);
149− } catch (IOException ex) {
150− return null;
151− }
109+ try {
110+ OpenOption[] options;
111+ switch (privs) {
112+ case "r":
113+ options = new StandardOpenOption[]{StandardOpenOption.READ};
114+ break;
115+ case "r+":
116+ options = new StandardOpenOption[]{StandardOpenOption.READ,
117+ StandardOpenOption.WRITE};
118+ break;
119+ case "w":
120+ options = new StandardOpenOption[]{StandardOpenOption.WRITE,
121+ StandardOpenOption.CREATE};
122+ break;
123+ case "w+":
124+ options = new StandardOpenOption[]{StandardOpenOption.READ,
125+ StandardOpenOption.WRITE,
126+ StandardOpenOption.CREATE};
127+ break;
128+ case "a":
129+ options = new StandardOpenOption[]{StandardOpenOption.WRITE,
130+ StandardOpenOption.CREATE,
131+ StandardOpenOption.APPEND};
132+ break;
133+ case "a+":
134+ options = new StandardOpenOption[]{StandardOpenOption.READ,
135+ StandardOpenOption.WRITE,
136+ StandardOpenOption.CREATE,
137+ StandardOpenOption.APPEND};
138+ break;
139+ default:
140+ options = new StandardOpenOption[]{};
141+ break;
142+ }
143+ return Files.newByteChannel(new File(name).toPath(), options);
144+ } catch (IOException ex) {
145+ return null;
146+ }
152147 }
153148
154149 public static synchronized void fileClose(Object file) throws IOException {
155− ((Closeable)file).close();
156− feofFiles.remove(file);
150+ ((Closeable) file).close();
151+ feofFiles.remove(file);
157152 }
158153
159154 public static void fputStr(Object file, String string) throws IOException {
160− if (file instanceof PrintStream) {
161− ((PrintStream)file).print(string);
162− } else if (file instanceof SeekableByteChannel) {
163− ((SeekableByteChannel)file).write(ByteBuffer.wrap(string.getBytes()));
164− }
155+ if (file instanceof PrintStream) {
156+ ((PrintStream) file).print(string);
157+ } else if (file instanceof SeekableByteChannel) {
158+ ((SeekableByteChannel) file).write(ByteBuffer.wrap(string.getBytes()));
159+ }
165160 }
166161
167162 public static synchronized String idris_readStr(Object file) throws IOException {
168− ReadableByteChannel channel = file instanceof InputStream ?
169− Channels.newChannel((InputStream)file) :
170− (ReadableByteChannel)file;
171− ByteBuffer buf = ByteBuffer.allocate(1);
172− StringBuilder resultBuilder = new StringBuilder("");
173− String delimiter = System.getProperty("line.separator");
174− int read = 0;
175− do {
176− buf.rewind();
177− read = channel.read(buf);
178− if (read > 0) {
179− resultBuilder.append(new String(buf.array()));
180− if (resultBuilder.lastIndexOf(delimiter) > -1) {
181− return resultBuilder.toString();
182− }
183− }
184− if (read < 0) {
185− feofFiles.add(file);
186− }
187− } while (read >= 0);
188− return resultBuilder.toString();
163+ ReadableByteChannel channel = file instanceof InputStream
164+ ? Channels.newChannel((InputStream) file)
165+ : (ReadableByteChannel) file;
166+ ByteBuffer buf = ByteBuffer.allocate(1);
167+ StringBuilder resultBuilder = new StringBuilder("");
168+ String delimiter = System.getProperty("line.separator");
169+ int read = 0;
170+ do {
171+ buf.rewind();
172+ read = channel.read(buf);
173+ if (read > 0) {
174+ resultBuilder.append(new String(buf.array()));
175+ if (resultBuilder.lastIndexOf(delimiter) > -1) {
176+ return resultBuilder.toString();
177+ }
178+ }
179+ if (read < 0) {
180+ feofFiles.add(file);
181+ }
182+ } while (read >= 0);
183+ return resultBuilder.toString();
189184 }
190185
191186 public static int fileEOF(Object file) {
192− return (feofFiles.contains(file) ? 1 : 0);
187+ return (feofFiles.contains(file) ? 1 : 0);
193188 }
194189
195190 public static int isNull(Object o) {
196− return (o == null ? 1 : 0);
191+ return (o == null ? 1 : 0);
197192 }
198193
199194 public final static Object idris_K(final Object result, final Object drop) {
200− return result;
195+ return result;
201196 }
202197
203198 public final static Object idris_flipK(final Object drop, final Object result) {
204− return result;
205− }
206−
207− public final static Object idris_assignStack(final Object [] context, final int start, final Object ... vars) {
208− int i = start;
209− for (Object var : vars) {
210− context[i] = var;
211− }
212− return context;
199+ return result;
200+ }
201+
202+ public final static Object idris_assignStack(final Object[] context, final int start, final Object... vars) {
203+ int i = start;
204+ for (Object var : vars) {
205+ context[i] = var;
206+ }
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);
213228 }
214229}
lib/IO.idr+2−4
@@ -33,10 +33,8 @@ interpFTy (FAny t) = t
3333interpFTy FUnit = ()
3434
3535ForeignTy : (xs:List FTy) -> (t:FTy) -> Type
36−ForeignTy xs t = mkForeign' (reverse xs) (IO (interpFTy t)) where
37− mkForeign' : List FTy -> Type -> Type
38− mkForeign' Nil ty = ty
39− mkForeign' (s :: ss) ty = mkForeign' ss (interpFTy s -> ty)
36+ForeignTy Nil rt = IO (interpFTy rt)
37+ForeignTy (t::ts) rt = interpFTy t -> ForeignTy ts rt
4038
4139
4240data Foreign : Type -> Type where
rts/idris_gc.c+1−3
@@ -101,9 +101,7 @@ void idris_gc(VM* vm) {
101101 for(root = vm->inbox_ptr; root < vm->inbox_write; ++root) {
102102 *root = copy(vm, *root);
103103 }
104− for(root = vm->argv; root < vm->argv + vm->argc; ++root) {
105− *root = copy(vm, *root);
106− }
104+
107105 vm->ret = copy(vm, vm->ret);
108106 vm->reg1 = copy(vm, vm->reg1);
109107
rts/idris_rts.c+2−18
@@ -20,16 +20,10 @@ VM* init_vm(int stack_size, size_t heap_size,
2020 STATS_ENTER_INIT(vm->stats)
2121
2222 VAL* valstack = malloc(stack_size * sizeof(VAL));
23− int* intstack = malloc(stack_size * sizeof(int));
24− double* floatstack = malloc(stack_size*sizeof(double));
2523
2624 vm->valstack = valstack;
2725 vm->valstack_top = valstack;
2826 vm->valstack_base = valstack;
29− vm->intstack = intstack;
30− vm->intstack_ptr = intstack;
31− vm->floatstack = floatstack;
32− vm->floatstack_ptr = floatstack;
3327 vm->stack_max = valstack + stack_size;
3428
3529 alloc_heap(&(vm->heap), heap_size);
@@ -51,15 +45,9 @@ VM* init_vm(int stack_size, size_t heap_size,
5145 vm->max_threads = max_threads;
5246 vm->processes = 0;
5347
54− int i;
55− // Assumption: there's enough space for this in the initial heap.
56− vm->argv = malloc(argc*sizeof(VAL));
48+ vm->argv = argv;
5749 vm->argc = argc;
5850
59− for(i = 0; i < argc; ++i) {
60− vm->argv[i] = MKSTR(vm, argv[i]);
61− }
62−
6351 STATS_LEAVE_INIT(vm->stats)
6452 return vm;
6553}
@@ -70,10 +58,7 @@ Stats terminate(VM* vm) {
7058
7159 free(vm->inbox);
7260 free(vm->valstack);
73− free(vm->intstack);
74− free(vm->floatstack);
7561 free_heap(&(vm->heap));
76− free(vm->argv);
7762
7863 pthread_mutex_destroy(&(vm -> inbox_lock));
7964 pthread_mutex_destroy(&(vm -> inbox_block));
@@ -592,11 +577,10 @@ int idris_numArgs(VM* vm) {
592577}
593578
594579VAL idris_getArg(VM* vm, int i) {
595− return vm->argv[i];
580+ return MKSTR(vm, vm->argv[i]);
596581}
597582
598583void stackOverflow() {
599584 fprintf(stderr, "Stack overflow");
600585 exit(-1);
601586}
602−
rts/idris_rts.h+1−5
@@ -44,12 +44,8 @@ typedef struct Closure {
4444
4545typedef struct {
4646 VAL* valstack;
47− int* intstack;
48− double* floatstack;
4947 VAL* valstack_top;
5048 VAL* valstack_base;
51− int* intstack_ptr;
52− double* floatstack_ptr;
5349 VAL* stack_max;
5450
5551 Heap heap;
@@ -71,7 +67,7 @@ typedef struct {
7167 Stats stats;
7268
7369 int argc;
74− VAL* argv; // command line arguments
70+ char** argv; // command line arguments
7571
7672 VAL ret;
7773 VAL reg1;
rts/idris_stats.c+19−4
@@ -9,8 +9,23 @@ void print_stats(const Stats * stats) {
99 clock_t total = clock() - stats->start_time;
1010 clock_t mut = total - stats->init_time - stats->gc_time - stats->exit_time;
1111 double mut_sec = (double)mut / CLOCKS_PER_SEC;
12− int avg_chunk = (int)((double)stats->allocations / (double)stats->alloc_count);
13− int alloc_rate = (int)((double)(stats->allocations) / mut_sec);
12+
13+ int avg_chunk = 0;
14+ if (stats->alloc_count > 0) {
15+ avg_chunk = (int)((double)stats->allocations / (double)stats->alloc_count);
16+ }
17+
18+ int alloc_rate = 0;
19+ if (mut > 0) {
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+ }
1429
1530 setlocale(LC_NUMERIC, "");
1631 printf("\n");
@@ -28,11 +43,11 @@ void print_stats(const Stats * stats) {
2843 printf("EXIT time: %8.3fs\n", (double)stats->exit_time / CLOCKS_PER_SEC);
2944 printf("TOTAL time: %8.3fs\n\n", (double)total / CLOCKS_PER_SEC);
3045
31− printf("%%GC time: %.2f%%\n\n", 100 * (double)stats->gc_time / (double)total);
46+ printf("%%GC time: %.2f%%\n\n", gc_percent);
3247
3348 printf("Alloc rate %'d bytes per MUT sec\n\n", alloc_rate);
3449
35− printf("Productivity %.2f%%\n", 100 * ((double)mut / (double)total));
50+ printf("Productivity %.2f%%\n", productivity);
3651}
3752
3853void 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 {
3131 = ["let", "in", "data", "codata", "record", "Type",
3232 "do", "dsl", "import", "impossible",
3333 "case", "of", "total", "partial", "mutual",
34− "infix", "infixl", "infixr",
34+ "infix", "infixl", "infixr", "rewrite",
3535 "where", "with", "syntax", "proof", "postulate",
3636 "using", "namespace", "class", "instance",
3737 "public", "private", "abstract", "implicit",
src/Core/ProofState.hs+1−2
@@ -444,8 +444,7 @@ intro n ctxt env _ = fail "Can't introduce here."
444444forall :: Name -> Raw -> RunTactic
445445forall n ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
446446 do (tyv, tyt) <- lift $ check ctxt env ty
447− lift $ isType ctxt env tyt
448− lift $ isType ctxt env t
447+ unify' ctxt env tyt (TType (UVar 0))
449448 return $ Bind n (Pi tyv) (Bind x (Hole t) (P Bound x t))
450449forall n ty ctxt env _ = fail "Can't pi bind here"
451450
src/Core/TT.hs+2
@@ -69,6 +69,7 @@ data Err = Msg String
6969 | NonCollapsiblePostulate Name
7070 | AlreadyDefined Name
7171 | ProofSearchFail Err
72+ | NoRewriting Term
7273 | At FC Err
7374 deriving Eq
7475
@@ -82,6 +83,7 @@ instance Sized Err where
8283 size (NoTypeDecl name) = size name
8384 size (NotInjective l c r) = size l + size c + size r
8485 size (CantResolve trm) = size trm
86+ size (NoRewriting trm) = size trm
8587 size (CantResolveAlts _) = 1
8688 size (IncompleteTerm trm) = size trm
8789 size UniverseError = 1
src/IRTS/CodegenJava.hs+51−22
@@ -15,7 +15,7 @@ import qualified Control.Monad.Trans as T
1515import Control.Monad.Trans.State
1616import Data.Char
1717import Data.Maybe (fromJust)
18−import Data.List (isPrefixOf, intercalate)
18+import Data.List (isPrefixOf, isSuffixOf, intercalate)
1919import qualified Data.Text as T
2020import qualified Data.Text.IO as TIO
2121import Language.Java.Parser
@@ -35,9 +35,11 @@ type CodeGeneration = StateT (CodeGenerationEnv) (Either String)
3535codegenJava :: [(Name, SExp)] -> -- initialization of globals
3636 [(Name, SDecl)] ->
3737 FilePath -> -- output file name
38+ [String] -> -- headers
39+ [String] -> -- libs
3840 OutputType ->
3941 IO ()
40−codegenJava globalInit defs out exec = do
42+codegenJava globalInit defs out hdrs libs exec = do
4143 withTempdir (takeBaseName out) $ \ tmpDir -> do
4244 let srcdir = tmpDir </> "src" </> "main" </> "java"
4345 createDirectoryIfMissing True srcdir
@@ -46,7 +48,7 @@ codegenJava globalInit defs out exec = do
4648 let outjava = srcdir </> clsName <.> "java"
4749 let jout = either error
4850 (flatIndent . prettyPrint)
49− (evalStateT (mkCompilationUnit globalInit defs out) (mkCodeGenEnv globalInit))
51+ (evalStateT (mkCompilationUnit globalInit defs hdrs out) (mkCodeGenEnv globalInit))
5052 writeFile outjava jout
5153 if (exec == Raw)
5254 then copyFile outjava (takeDirectory out </> clsName <.> "java")
@@ -57,12 +59,16 @@ codegenJava globalInit defs out exec = do
5759 (T.pack clsName)
5860 (T.replace (T.pack "$ARTIFACT-NAME$")
5961 (T.pack $ takeBaseName out)
60− execPomTemplate)
62+ (T.replace (T.pack "$DEPENDENCIES$")
63+ (mkPomDependencies libs)
64+ execPomTemplate
65+ )
66+ )
6167 TIO.writeFile (tmpDir </> "pom.xml") execPom
6268 mvnCmd <- getMvn
6369 let args = ["-f", (tmpDir </> "pom.xml")]
64− (exit, _, err) <- readProcessWithExitCode mvnCmd (args ++ ["compile"]) ""
65− when (exit /= ExitSuccess) $ error ("FAILURE: " ++ mvnCmd ++ " compile\n" ++ err)
70+ (exit, mvout, err) <- readProcessWithExitCode mvnCmd (args ++ ["compile"]) ""
71+ when (exit /= ExitSuccess) $ error ("FAILURE: " ++ mvnCmd ++ " compile\n" ++ err ++ mvout)
6672 if (exec == Object)
6773 then do
6874 classFiles <-
@@ -72,8 +78,8 @@ codegenJava globalInit defs out exec = do
7278 mapM_ (\ clsFile -> copyFile clsFile (takeDirectory out </> takeFileName clsFile))
7379 classFiles
7480 else do
75− (exit, _, err) <- readProcessWithExitCode mvnCmd (args ++ ["package"]) ""
76− when (exit /= ExitSuccess) (error ("FAILURE: " ++ mvnCmd ++ " package\n" ++ err))
81+ (exit, mvout, err) <- readProcessWithExitCode mvnCmd (args ++ ["package"]) ""
82+ when (exit /= ExitSuccess) (error ("FAILURE: " ++ mvnCmd ++ " package\n" ++ err ++ mvout))
7783 copyFile (tmpDir </> "target" </> (takeBaseName out) <.> "jar") out
7884 handle <- openBinaryFile out ReadMode
7985 contents <- TIO.hGetContents handle
@@ -99,21 +105,40 @@ jarHeader =
99105 ++ "exec \"$java\" $java_args -jar $MYSELF \"$@\""
100106 ++ "exit 1\n"
101107
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+
102126mkCodeGenEnv :: [(Name, SExp)] -> CodeGenerationEnv
103127mkCodeGenEnv globalInit =
104128 CodeGenerationEnv $ zipWith (\ (name, _) pos -> (name, pos)) globalInit [0..]
105129
106−mkCompilationUnit :: [(Name, SExp)] -> [(Name, SDecl)] -> FilePath -> CodeGeneration CompilationUnit
107−mkCompilationUnit globalInit defs out =
108− CompilationUnit Nothing [ ImportDecl False idrisRts True
109− , ImportDecl True idrisForeign True
110− , ImportDecl False bigInteger False
111− , ImportDecl False stringBuffer False
112− , ImportDecl False runtimeException False
113− , ImportDecl False scanner False
114− , ImportDecl False arrays False
115− ] <$>
116− mkTypeDecl globalInit defs out
130+mkCompilationUnit :: [(Name, SExp)] -> [(Name, SDecl)] -> [String] -> FilePath -> CodeGeneration CompilationUnit
131+mkCompilationUnit globalInit defs hdrs out =
132+ CompilationUnit Nothing ( [ ImportDecl False idrisRts True
133+ , ImportDecl True idrisForeign True
134+ , ImportDecl False bigInteger False
135+ , ImportDecl False stringBuffer False
136+ , ImportDecl False runtimeException False
137+ , ImportDecl False scanner False
138+ , ImportDecl False arrays False
139+ ] ++ otherHdrs
140+ )
141+ <$> mkTypeDecl globalInit defs out
117142 where
118143 idrisRts = J.Name $ map Ident ["org", "idris", "rts"]
119144 idrisForeign = J.Name $ map Ident ["org", "idris", "rts", "ForeignPrimitives"]
@@ -122,6 +147,12 @@ mkCompilationUnit globalInit defs out =
122147 runtimeException = J.Name $ map Ident ["java", "lang", "RuntimeException"]
123148 scanner = J.Name $ map Ident ["java", "util", "Scanner"]
124149 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
125156
126157flatIndent :: String -> String
127158flatIndent (' ' : ' ' : xs) = flatIndent xs
@@ -337,6 +368,7 @@ mkIdentifier (UN name) =
337368 cleanReserved "volatile" = "_volatile"
338369 cleanReserved "transient" = "_transient"
339370 cleanReserved "native" = "_native"
371+ cleanReserved "const" = "_const"
340372
341373 cleanReserved "import" = "_import"
342374 cleanReserved "package" = "_package"
@@ -410,9 +442,6 @@ idrisClosureType = ClassType [(Ident "Closure", [])]
410442idrisTailCallClosureType :: ClassType
411443idrisTailCallClosureType = ClassType [(Ident "TailCallClosure", [])]
412444
413−--idrisFunctionType :: ClassType
414−--idrisFunctionType = ClassType [(Ident "IdrisFunction", [])]
415−
416445idrisObjectType :: ClassType
417446idrisObjectType = ClassType [(Ident "IdrisObject", [])]
418447
src/IRTS/CodegenJavaScript.hs+2−2
@@ -385,11 +385,11 @@ translateExpression (SForeign _ _ fun args)
385385 , (obj:as) <- args =
386386 concat [object obj, method, arguments as]
387387
388− | "[]=" == fun
388+ | "[]=" `isSuffixOf` fun
389389 , (idx:val:[]) <- args =
390390 concat [array, index idx, assign val]
391391
392− | "[]" == fun
392+ | "[]" `isSuffixOf` fun
393393 , (idx:[]) <- args =
394394 array ++ index idx
395395
src/IRTS/Compiler.hs+14−11
@@ -71,7 +71,7 @@ compile target f tm
7171 (concatMap mkObj objs)
7272 (concatMap mkLib libs) NONE
7373 ViaJava ->
74− codegenJava [] c f outty
74+ codegenJava [] c f hdrs libs outty
7575 ViaJavaScript ->
7676 codegenJavaScript JavaScript c f outty
7777 ViaNode ->
@@ -264,21 +264,24 @@ instance ToIR (TT Name) where
264264 doForeign :: [Name] -> [TT Name] -> Idris LExp
265265 doForeign env (_ : fgn : args)
266266 | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
267− = let tys = getFTypes fgnArgTys
267+ = let maybeTys = getFTypes fgnArgTys
268268 rty = mkIty' ret in
269− do args' <- mapM (ir' env) args
270− -- wrap it in a prim__IO
271− -- return $ con_ 0 @@ impossible @@
272− return $ -- LLazyExp $
273− LForeign LANG_C rty fgnName (zip tys args')
269+ case maybeTys of
270+ Nothing -> fail $ "Foreign type specification is not a constant list: " ++ show (fgn:args)
271+ Just tys -> do
272+ args' <- mapM (ir' env) args
273+ -- wrap it in a prim__IO
274+ -- return $ con_ 0 @@ impossible @@
275+ return $ -- LLazyExp $
276+ LForeign LANG_C rty fgnName (zip tys args')
274277 | otherwise = fail "Badly formed foreign function call"
275278
276−getFTypes :: TT Name -> [FType]
279+getFTypes :: TT Name -> Maybe [FType]
277280getFTypes tm = case unApply tm of
278− (nil, []) -> []
281+ (nil, []) -> Just []
279282 (cons, [ty, xs]) ->
280− let rest = getFTypes xs in
281− mkIty' ty : rest
283+ fmap (mkIty' ty :) (getFTypes xs)
284+ _ -> Nothing
282285
283286mkIty' (P _ (UN ty) _) = mkIty ty
284287mkIty' _ = FAny
src/IRTS/LParser.hs+1−1
@@ -61,7 +61,7 @@ fovm tgt outty f
6161 case checked of
6262 OK c -> case tgt of
6363 ViaC -> codegenC c "a.out" outty ["math.h"] "" "" TRACE
64− ViaJava -> codegenJava [] c "a.out" outty
64+ ViaJava -> codegenJava [] c "a.out" [] [] outty
6565 Error e -> fail $ show e
6666
6767parseFOVM :: FilePath -> IO [(Name, LDecl)]
src/Idris/AbsSyntax.hs+21
@@ -288,6 +288,12 @@ setREPL t = do i <- getIState
288288 let opt' = opts { opt_repl = t }
289289 putIState $ i { idris_options = opt' }
290290
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+
291297setTarget :: Target -> Idris ()
292298setTarget t = do i <- getIState
293299 let opts = idris_options i
@@ -506,6 +512,7 @@ expandParams dec ps ns infs tm = en tm
506512 PLet n' (en ty) (en v) (en (shadow n n' s))
507513 | otherwise = PLet n (en ty) (en v) (en s)
508514 en (PEq f l r) = PEq f (en l) (en r)
515+ en (PRewrite f l r) = PRewrite f (en l) (en r)
509516 en (PTyped l r) = PTyped (en l) (en r)
510517 en (PPair f l r) = PPair f (en l) (en r)
511518 en (PDPair f l t r) = PDPair f (en l) (en t) (en r)
@@ -641,6 +648,7 @@ getPriority i tm = 1 -- pri tm
641648 pri (PFalse _) = 0
642649 pri (PRefl _ _) = 1
643650 pri (PEq _ l r) = max 1 (max (pri l) (pri r))
651+ pri (PRewrite _ l r) = max 1 (max (pri l) (pri r))
644652 pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as)))
645653 pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as)))
646654 pri (PTyped l r) = pri l
@@ -751,6 +759,10 @@ implicitise syn ignore ist tm
751759 = do (decls, ns) <- get
752760 let isn = namesIn uvars ist l ++ namesIn uvars ist r
753761 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)))))
754766 imps top env (PTyped l r)
755767 = imps top env l
756768 imps top env (PPair _ l r)
@@ -810,6 +822,9 @@ addImpl' inpat env infns ist ptm = ai (zip env (repeat Nothing)) ptm
810822 ai env (PEq fc l r) = let l' = ai env l
811823 r' = ai env r in
812824 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'
813828 ai env (PTyped l r) = let l' = ai env l
814829 r' = ai env r in
815830 PTyped l' r'
@@ -1065,6 +1080,10 @@ matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where
10651080 match (PEq _ l r) (PEq _ l' r') = do ml <- match' l l'
10661081 mr <- match' r r'
10671082 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)
10681087 match (PTyped l r) (PTyped l' r') = do ml <- match l l'
10691088 mr <- match r r'
10701089 return (ml ++ mr)
@@ -1146,6 +1165,7 @@ substMatchShadow n shs tm t = sm shs t where
11461165 sm xs (PApp f x as) = PApp f (sm xs x) (map (fmap (sm xs)) as)
11471166 sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)
11481167 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)
11491169 sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y)
11501170 sm xs (PPair f x y) = PPair f (sm xs x) (sm xs y)
11511171 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
11611181 sm (PApp f x as) = PApp f (sm x) (map (fmap sm) as)
11621182 sm (PCase f x as) = PCase f (sm x) (map (pmap sm) as)
11631183 sm (PEq f x y) = PEq f (sm x) (sm y)
1184+ sm (PRewrite f x y) = PRewrite f (sm x) (sm y)
11641185 sm (PTyped x y) = PTyped (sm x) (sm y)
11651186 sm (PPair f x y) = PPair f (sm x) (sm y)
11661187 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
2424
2525import Debug.Trace
2626
27−data IOption = IOption { opt_logLevel :: Int,
28− opt_typecase :: Bool,
27+data IOption = IOption { opt_logLevel :: Int,
28+ opt_typecase :: Bool,
2929 opt_typeintype :: Bool,
30− opt_coverage :: Bool,
31− opt_showimp :: Bool,
30+ opt_coverage :: Bool,
31+ opt_showimp :: Bool,
3232 opt_errContext :: Bool,
33− opt_repl :: Bool,
34− opt_verbose :: Bool,
35− opt_target :: Target,
36− opt_outputTy :: OutputType,
37− opt_ibcsubdir :: FilePath,
33+ opt_repl :: Bool,
34+ opt_verbose :: Bool,
35+ opt_quiet :: Bool,
36+ opt_target :: Target,
37+ opt_outputTy :: OutputType,
38+ opt_ibcsubdir :: FilePath,
3839 opt_importdirs :: [FilePath],
39− opt_cmdline :: [Opt] -- remember whole command line
40+ opt_cmdline :: [Opt] -- remember whole command line
4041 }
4142 deriving (Show, Eq)
4243
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 "" [] []
4445
4546-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
4647-- without typechecking).
@@ -195,6 +196,7 @@ data Command = Quit
195196data Opt = Filename String
196197 | Ver
197198 | Usage
199+ | Quiet
198200 | ShowLibs
199201 | ShowLibdir
200202 | ShowIncs
@@ -386,12 +388,19 @@ declared (PFix _ _ _) = []
386388declared (PTy _ _ _ _ n t) = [n]
387389declared (PPostulate _ _ _ _ n t) = [n]
388390declared (PClauses _ _ n _) = [] -- not a declaration
389−declared (PRecord _ _ _ n _ _ c _) = [n, c]
391+declared (PCAF _ n _) = [n]
390392declared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
391393 where fstt (_, a, _, _) = a
394+declared (PData _ _ _ _ (PLaterdecl n _)) = [n]
392395declared (PParams _ _ ds) = concatMap declared ds
393−declared (PMutual _ ds) = concatMap declared ds
394396declared (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 _) = []
395404
396405-- get the names declared, not counting nested parameter blocks
397406tldeclared :: PDecl -> [Name]
@@ -405,20 +414,27 @@ tldeclared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
405414tldeclared (PParams _ _ ds) = []
406415tldeclared (PMutual _ ds) = concatMap tldeclared ds
407416tldeclared (PNamespace _ ds) = concatMap tldeclared ds
408−-- declared (PImport _) = []
417+
409418
410419defined :: PDecl -> [Name]
411420defined (PFix _ _ _) = []
412421defined (PTy _ _ _ _ n t) = []
413422defined (PPostulate _ _ _ _ n t) = []
414423defined (PClauses _ _ n _) = [n] -- not a declaration
415−defined (PRecord _ _ _ n _ _ c _) = [n, c]
424+defined (PCAF _ n _) = [n]
416425defined (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
417426 where fstt (_, a, _, _) = a
427+defined (PData _ _ _ _ (PLaterdecl n _)) = []
418428defined (PParams _ _ ds) = concatMap defined ds
419−defined (PMutual _ ds) = concatMap defined ds
420429defined (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 _ = []
422438
423439updateN :: [(Name, Name)] -> Name -> Name
424440updateN ns n | Just n' <- lookup n ns = n'
@@ -457,6 +473,7 @@ data PTerm = PQuote Raw
457473 | PRefl FC PTerm
458474 | PResolveTC FC
459475 | PEq FC PTerm PTerm
476+ | PRewrite FC PTerm PTerm
460477 | PPair FC PTerm PTerm
461478 | PDPair FC PTerm PTerm PTerm
462479 | PAlternative Bool [PTerm] -- True if only one may work
@@ -483,6 +500,7 @@ mapPT f t = f (mpt t) where
483500 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
484501 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
485502 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)
486504 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
487505 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
488506 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
@@ -893,6 +911,12 @@ prettyImp impl = prettySe 10
893911 prettySe 10 l <+> text "=" $$ nest nestingSize (prettySe 10 r)
894912 else
895913 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
896920 prettySe p (PTyped l r) =
897921 lparen <> prettySe 10 l <+> colon <+> prettySe 10 r <> rparen
898922 prettySe p (PPair _ l r) =
@@ -1000,6 +1024,7 @@ showImp impl tm = se 10 tm where
10001024 se p (PTrue _) = "()"
10011025 se p (PFalse _) = "_|_"
10021026 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
10031028 se p (PTyped l r) = "(" ++ se 10 l ++ " : " ++ se 10 r ++ ")"
10041029 se p (PPair _ l r) = "(" ++ se 10 l ++ ", " ++ se 10 r ++ ")"
10051030 se p (PDPair _ l t r) = "(" ++ se 10 l ++ " ** " ++ se 10 r ++ ")"
@@ -1045,6 +1070,7 @@ instance Sized PTerm where
10451070 size (PRefl fc _) = 1
10461071 size (PResolveTC fc) = 1
10471072 size (PEq fc left right) = 1 + size left + size right
1073+ size (PRewrite fc left right) = 1 + size left + size right
10481074 size (PPair fc left right) = 1 + size left + size right
10491075 size (PDPair fs left ty right) = 1 + size left + size ty + size right
10501076 size (PAlternative a alts) = 1 + size alts
@@ -1077,6 +1103,7 @@ allNamesIn tm = nub $ ni [] tm
10771103 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
10781104 ni env (PHidden tm) = ni env tm
10791105 ni env (PEq _ l r) = ni env l ++ ni env r
1106+ ni env (PRewrite _ l r) = ni env l ++ ni env r
10801107 ni env (PTyped l r) = ni env l ++ ni env r
10811108 ni env (PPair _ l r) = ni env l ++ ni env r
10821109 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
10991126 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
11001127 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
11011128 ni env (PEq _ l r) = ni env l ++ ni env r
1129+ ni env (PRewrite _ l r) = ni env l ++ ni env r
11021130 ni env (PTyped l r) = ni env l ++ ni env r
11031131 ni env (PPair _ l r) = ni env l ++ ni env r
11041132 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
11221150 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
11231151 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
11241152 ni env (PEq _ l r) = ni env l ++ ni env r
1153+ ni env (PRewrite _ l r) = ni env l ++ ni env r
11251154 ni env (PTyped l r) = ni env l ++ ni env r
11261155 ni env (PPair _ l r) = ni env l ++ ni env r
11271156 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)
109109 = "The return type of postulate " ++ show n ++ " is not collapsible"
110110pshow i (AlreadyDefined n) = show n ++ " is already defined"
111111pshow i (ProofSearchFail e) = pshow i e
112+pshow i (NoRewriting tm) = "rewrite did not change type " ++ show (delab i tm)
112113pshow i (At f e) = show f ++ ":" ++ pshow i e
113114
114115showSc i [] = ""
src/Idris/ElabTerm.hs+17
@@ -407,6 +407,23 @@ elab ist info pattern tcgen fn tm
407407 | not pattern = do mapM_ (runTac False ist) ts
408408 | otherwise = elab' ina Placeholder
409409 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
410427 elab' ina@(_, a) c@(PCase fc scr opts)
411428 = do attack
412429 tyn <- unique_hole (MN 0 "scty")
src/Idris/IBC.hs+8
@@ -1265,6 +1265,10 @@ instance Binary PTerm where
12651265 PInferRef x1 x2 -> do putWord8 29
12661266 put x1
12671267 put x2
1268+ PRewrite x1 x2 x3 -> do putWord8 30
1269+ put x1
1270+ put x2
1271+ put x3
12681272 get
12691273 = do i <- getWord8
12701274 case i of
@@ -1349,6 +1353,10 @@ instance Binary PTerm where
13491353 29 -> do x1 <- get
13501354 x2 <- get
13511355 return (PInferRef x1 x2)
1356+ 30 -> do x1 <- get
1357+ x2 <- get
1358+ x3 <- get
1359+ return (PRewrite x1 x2 x3)
13521360 _ -> error "Corrupted binary data for PTerm"
13531361
13541362instance (Binary t) => Binary (PTactic' t) where
src/Idris/Parser.hs+9
@@ -610,6 +610,7 @@ pNoExtExpr syn =
610610 <|> try (pSimpleExpr syn)
611611 <|> pLambda syn
612612 <|> pLet syn
613+ <|> pRewriteTerm syn
613614 <|> pPi syn
614615 <|> pDoBlock syn
615616 <|> pComprehension syn
@@ -940,6 +941,14 @@ pLambda syn = do lchar '\\'
940941 (PCase fc (PRef fc (MN i "lamp"))
941942 [(x, pmList xs sc)])
942943
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+
943952pLet syn = try (do reserved "let"; n <- pName;
944953 ty <- option Placeholder (do lchar ':'; pExpr' syn)
945954 lchar '='
src/Idris/REPL.hs+13−5
@@ -61,10 +61,13 @@ repl :: IState -- ^ The initial state
6161 -> InputT Idris ()
6262repl orig mods
6363 = H.catch
64− (do let prompt = mkPrompt mods
65− x <- getInputLine (prompt ++ "> ")
64+ (do let quiet = opt_quiet (idris_options orig)
65+ let prompt = if quiet
66+ then ""
67+ else mkPrompt mods ++ "> "
68+ x <- getInputLine prompt
6669 case x of
67− Nothing -> do lift $ iputStrLn "Bye bye"
70+ Nothing -> do lift $ when (not quiet) (iputStrLn "Bye bye")
6871 return ()
6972 Just input -> H.catch
7073 (do ms <- lift $ processInput input orig mods
@@ -90,6 +93,8 @@ lit f = case splitExtension f of
9093processInput :: String -> IState -> [FilePath] -> Idris (Maybe [FilePath])
9194processInput cmd orig inputs
9295 = do i <- getIState
96+ let opts = idris_options i
97+ let quiet = opt_quiet opts
9398 let fn = case inputs of
9499 (f:_) -> f
95100 _ -> ""
@@ -114,7 +119,7 @@ processInput cmd orig inputs
114119 return (Just inputs)
115120 Right Proofs -> do proofs orig
116121 return (Just inputs)
117− Right Quit -> do iputStrLn "Bye bye"
122+ Right Quit -> do when (not quiet) (iputStrLn "Bye bye")
118123 return Nothing
119124 Right cmd -> do idrisCatch (process fn cmd)
120125 (\e -> iputStrLn (show e))
@@ -453,6 +458,7 @@ parseTarget _ = error "unknown target" -- FIXME: partial function
453458
454459parseArgs :: [String] -> [Opt]
455460parseArgs [] = []
461+parseArgs ("--quiet":ns) = Quiet : (parseArgs ns)
456462parseArgs ("--log":lvl:ns) = OLogging (read lvl) : (parseArgs ns)
457463parseArgs ("--noprelude":ns) = NoPrelude : (parseArgs ns)
458464parseArgs ("--check":ns) = NoREPL : (parseArgs ns)
@@ -504,6 +510,7 @@ idris opts = execStateT (idrisMain opts) idrisInit
504510idrisMain :: [Opt] -> Idris ()
505511idrisMain opts =
506512 do let inputs = opt getFile opts
513+ let quiet = Quiet `elem` opts
507514 let runrepl = not (NoREPL `elem` opts)
508515 let output = opt getOutput opts
509516 let newoutput = opt getNewOutput opts
@@ -521,6 +528,7 @@ idrisMain opts =
521528 when (DefaultTotal `elem` opts) $ do i <- getIState
522529 putIState (i { default_total = True })
523530 setREPL runrepl
531+ setQuiet quiet
524532 setVerbose runrepl
525533 setCmdLine opts
526534 setOutputTy outty
@@ -544,7 +552,7 @@ idrisMain opts =
544552 elabPrims
545553 when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude"
546554 return ()
547− when runrepl $ iputStrLn banner
555+ when (runrepl && not quiet) $ iputStrLn banner
548556 ist <- getIState
549557 mods <- mapM loadModule inputs
550558 ok <- noErrors
src/Main.hs+1
@@ -78,6 +78,7 @@ usagemsg = "Idris version " ++ ver ++ "\n" ++
7878 "--------------" ++ map (\x -> '-') ver ++ "\n" ++
7979 "Usage: idris [input file] [options]\n" ++
8080 "Options:\n" ++
81+ "\t--quiet Quiet mode (for editors)\n" ++
8182 "\t--check Type check only\n" ++
8283 "\t-o [file] Specify output filename\n" ++
8384 "\t-i [dir] Add directory to the list of import paths\n" ++
test/reg012/reg012.lidr+4−2
@@ -28,5 +28,7 @@
2828> (ab : (alpha, beta)) ->
2929> modifyFun f ab (fst ab) = snd ab
3030> modifyFunLemma f (a,b) =
31−> replace {P = \ z => boolElim (a == a) b (f a) = boolElim z b (f a)}
32−> (soTrue (reflexive_eqeq a)) refl
31+> rewrite soTrue (reflexive_eqeq a) in refl
32+
33+ replace {P = \ z => boolElim (a == a) b (f a) = boolElim z b (f a)}
34+ (soTrue (reflexive_eqeq a)) refl