diff options
author | Rich Hickey <richhickey@gmail.com> | 2007-07-02 18:41:27 +0000 |
---|---|---|
committer | Rich Hickey <richhickey@gmail.com> | 2007-07-02 18:41:27 +0000 |
commit | c8f2340902b1c3efd66dec3071f93b82eb5632e4 (patch) | |
tree | be135451dc3fc14bee7e0b30026bc566829c0f54 /src | |
parent | e4bbdb0c9af57495d16c8b4f97248c0137030da9 (diff) |
interim checkin
Diffstat (limited to 'src')
-rw-r--r-- | src/jvm/clojure/lang/APersistentArray.java | 167 | ||||
-rw-r--r-- | src/jvm/clojure/lang/APersistentMap.java | 143 | ||||
-rw-r--r-- | src/jvm/clojure/lang/Associative.java | 6 | ||||
-rw-r--r-- | src/jvm/clojure/lang/Compiler.java | 3347 | ||||
-rw-r--r-- | src/jvm/clojure/lang/Iter.java | 6 | ||||
-rw-r--r-- | src/jvm/clojure/lang/Keyword.java | 102 | ||||
-rw-r--r-- | src/jvm/clojure/lang/MapEntry.java | 133 | ||||
-rw-r--r-- | src/jvm/clojure/lang/Module.java | 39 | ||||
-rw-r--r-- | src/jvm/clojure/lang/PersistentArrayMap.java | 374 | ||||
-rw-r--r-- | src/jvm/clojure/lang/PersistentHashMap.java | 8 | ||||
-rw-r--r-- | src/jvm/clojure/lang/PersistentHashtableMap.java | 391 | ||||
-rw-r--r-- | src/jvm/clojure/lang/PersistentTreeMap.java | 354 | ||||
-rw-r--r-- | src/jvm/clojure/lang/RT.java | 1025 | ||||
-rw-r--r-- | src/jvm/clojure/lang/TRef.java | 32 | ||||
-rw-r--r-- | src/jvm/clojure/lang/ThreadLocalData.java | 32 | ||||
-rw-r--r-- | src/jvm/clojure/lang/Transaction.java | 8 | ||||
-rw-r--r-- | src/jvm/clojure/lang/Var.java | 206 |
17 files changed, 3187 insertions, 3186 deletions
diff --git a/src/jvm/clojure/lang/APersistentArray.java b/src/jvm/clojure/lang/APersistentArray.java index ae2e6602..e479255a 100644 --- a/src/jvm/clojure/lang/APersistentArray.java +++ b/src/jvm/clojure/lang/APersistentArray.java @@ -10,106 +10,107 @@ package clojure.lang;
-public abstract class APersistentArray extends Obj implements IPersistentArray, Cloneable {
+public abstract class APersistentArray extends Obj implements IPersistentArray, Cloneable{
int _hash = -1;
-public IPersistentCollection cons(Object o) {
- PersistentArrayList ret = new PersistentArrayList(this, this.count() + 10);
- ret = ret.cons(o);
- ret._meta = _meta;
- return ret;
+public IPersistentCollection cons(Object o){
+ PersistentArrayList ret = new PersistentArrayList(this, this.count() + 10);
+ ret = ret.cons(o);
+ ret._meta = _meta;
+ return ret;
}
-public Obj withMeta(IPersistentMap meta) {
- if(_meta == meta)
- return this;
- try{
- Obj ret = (Obj) clone();
- ret._meta = meta;
- return ret;
- }
- catch(CloneNotSupportedException ignore)
- {
- return null;
- }
+public Obj withMeta(IPersistentMap meta){
+ if(_meta == meta)
+ return this;
+ try
+ {
+ Obj ret = (Obj) clone();
+ ret._meta = meta;
+ return ret;
+ }
+ catch(CloneNotSupportedException ignore)
+ {
+ return null;
+ }
}
-public boolean equals(Object obj) {
- if(obj instanceof IPersistentArray)
- {
- IPersistentArray ma = (IPersistentArray) obj;
- if(ma.count() != count() || ma.hashCode() != hashCode())
- return false;
- for(int i=0;i<count();i++)
- {
- if(!RT.equal(nth(i),ma.nth(i)))
- return false;
- }
- }
- else
- {
- if(!(obj instanceof Sequential))
- return false;
- ISeq ms = ((IPersistentCollection)obj).seq();
- for(int i=0;i<count();i++, ms = ms.rest())
- {
- if(ms == null || !RT.equal(nth(i),ms.first()))
- return false;
- }
- if(ms.rest() != null)
- return false;
- }
+public boolean equals(Object obj){
+ if(obj instanceof IPersistentArray)
+ {
+ IPersistentArray ma = (IPersistentArray) obj;
+ if(ma.count() != count() || ma.hashCode() != hashCode())
+ return false;
+ for(int i = 0; i < count(); i++)
+ {
+ if(!RT.equal(nth(i), ma.nth(i)))
+ return false;
+ }
+ }
+ else
+ {
+ if(!(obj instanceof Sequential))
+ return false;
+ ISeq ms = ((IPersistentCollection) obj).seq();
+ for(int i = 0; i < count(); i++, ms = ms.rest())
+ {
+ if(ms == null || !RT.equal(nth(i), ms.first()))
+ return false;
+ }
+ if(ms.rest() != null)
+ return false;
+ }
- return true;
+ return true;
}
-public int hashCode() {
- if(_hash == -1)
- {
- int hash = 0;
- for(int i=0;i<count();i++)
- {
- hash = RT.hashCombine(hash, RT.hash(nth(i)));
- }
- this._hash = hash;
- }
- return _hash;
+public int hashCode(){
+ if(_hash == -1)
+ {
+ int hash = 0;
+ for(int i = 0; i < count(); i++)
+ {
+ hash = RT.hashCombine(hash, RT.hash(nth(i)));
+ }
+ this._hash = hash;
+ }
+ return _hash;
}
-public boolean contains(Object key) {
- if(!(key instanceof Number))
- return false;
- int i = ((Number)key).intValue();
- return i >= 0 && i < count();
+public boolean contains(Object key){
+ if(!(key instanceof Number))
+ return false;
+ int i = ((Number) key).intValue();
+ return i >= 0 && i < count();
}
-public IMapEntry find(Object key) {
- if(key instanceof Number)
- {
- int i = ((Number)key).intValue();
- if(i >= 0 && i < count())
- return new MapEntry(key,nth(i));
- }
- return null;
+public IMapEntry entryAt(Object key){
+ if(key instanceof Number)
+ {
+ int i = ((Number) key).intValue();
+ if(i >= 0 && i < count())
+ return new MapEntry(key, nth(i));
+ }
+ return null;
}
-public Associative assoc(Object key, Object val) {
- if(key instanceof Number)
- {
- int i = ((Number)key).intValue();
- return (Associative) assocN(i,val);
- }
- throw new IllegalAccessError("Key must be integer");
+public Associative assoc(Object key, Object val){
+ if(key instanceof Number)
+ {
+ int i = ((Number) key).intValue();
+ return (Associative) assocN(i, val);
+ }
+ throw new IllegalAccessError("Key must be integer");
}
-public Object get(Object key) {
- if(key instanceof Number)
- {
- int i = ((Number)key).intValue();
- if(i >= 0 && i < count())
- return nth(i);
- }
- return null;
+public Object valAt(Object key){
+ if(key instanceof Number)
+ {
+ int i = ((Number) key).intValue();
+ if(i >= 0 && i < count())
+ return nth(i);
+ }
+ return null;
}
}
diff --git a/src/jvm/clojure/lang/APersistentMap.java b/src/jvm/clojure/lang/APersistentMap.java index 4b5805fd..bde64c2d 100644 --- a/src/jvm/clojure/lang/APersistentMap.java +++ b/src/jvm/clojure/lang/APersistentMap.java @@ -13,101 +13,102 @@ package clojure.lang; public abstract class APersistentMap extends Obj implements IPersistentMap, Cloneable{
int _hash = -1;
-public Obj withMeta(IPersistentMap meta) {
- if(_meta == meta)
- return this;
- try{
- Obj ret = (Obj) clone();
- ret._meta = meta;
- return ret;
- }
- catch(CloneNotSupportedException ignore)
- {
- return null;
- }
+public Obj withMeta(IPersistentMap meta){
+ if(_meta == meta)
+ return this;
+ try
+ {
+ Obj ret = (Obj) clone();
+ ret._meta = meta;
+ return ret;
+ }
+ catch(CloneNotSupportedException ignore)
+ {
+ return null;
+ }
}
-public IPersistentCollection cons(Object o) {
- IMapEntry e = (IMapEntry)o;
- return assoc(e.key(), e.val());
+public IPersistentCollection cons(Object o){
+ IMapEntry e = (IMapEntry) o;
+ return assoc(e.key(), e.val());
}
-public boolean equals(Object obj) {
- if(!(obj instanceof IPersistentMap))
- return false;
- IPersistentMap m = (IPersistentMap)obj;
+public boolean equals(Object obj){
+ if(!(obj instanceof IPersistentMap))
+ return false;
+ IPersistentMap m = (IPersistentMap) obj;
- if(m.count() != count() || m.hashCode() != hashCode())
- return false;
+ if(m.count() != count() || m.hashCode() != hashCode())
+ return false;
- for(ISeq s = seq();s!=null;s = s.rest())
- {
- IMapEntry e = (IMapEntry) s.first();
- IMapEntry me = m.find(e.key());
+ for(ISeq s = seq(); s != null; s = s.rest())
+ {
+ IMapEntry e = (IMapEntry) s.first();
+ IMapEntry me = m.entryAt(e.key());
- if(me == null || !RT.equal(e.val(),me.val()))
- return false;
- }
+ if(me == null || !RT.equal(e.val(), me.val()))
+ return false;
+ }
- return true;
+ return true;
}
-public int hashCode() {
- if(_hash == -1)
- {
- int hash = count();
- for(ISeq s = seq();s!=null;s = s.rest())
- {
- IMapEntry e = (IMapEntry) s.first();
- hash ^= RT.hashCombine(RT.hash(e.key()), RT.hash(e.val()));
- }
- this._hash = hash;
- }
- return _hash;
+public int hashCode(){
+ if(_hash == -1)
+ {
+ int hash = count();
+ for(ISeq s = seq(); s != null; s = s.rest())
+ {
+ IMapEntry e = (IMapEntry) s.first();
+ hash ^= RT.hashCombine(RT.hash(e.key()), RT.hash(e.val()));
+ }
+ this._hash = hash;
+ }
+ return _hash;
}
static public class KeySeq extends ASeq{
- ISeq seq;
+ ISeq seq;
- static public KeySeq create(ISeq seq){
- if(seq == null)
- return null;
- return new KeySeq(seq);
- }
+ static public KeySeq create(ISeq seq){
+ if(seq == null)
+ return null;
+ return new KeySeq(seq);
+ }
- private KeySeq(ISeq seq) {
- this.seq = seq;
- }
+ private KeySeq(ISeq seq){
+ this.seq = seq;
+ }
- public Object first() {
- return ((IMapEntry)seq.first()).key();
- }
+ public Object first(){
+ return ((IMapEntry) seq.first()).key();
+ }
- public ISeq rest() {
- return create(seq.rest());
- }
+ public ISeq rest(){
+ return create(seq.rest());
+ }
}
static public class ValSeq extends ASeq{
- ISeq seq;
+ ISeq seq;
- static public ValSeq create(ISeq seq){
- if(seq == null)
- return null;
- return new ValSeq(seq);
- }
+ static public ValSeq create(ISeq seq){
+ if(seq == null)
+ return null;
+ return new ValSeq(seq);
+ }
- private ValSeq(ISeq seq) {
- this.seq = seq;
- }
+ private ValSeq(ISeq seq){
+ this.seq = seq;
+ }
- public Object first() {
- return ((IMapEntry)seq.first()).val();
- }
+ public Object first(){
+ return ((IMapEntry) seq.first()).val();
+ }
- public ISeq rest() {
- return create(seq.rest());
- }
+ public ISeq rest(){
+ return create(seq.rest());
+ }
}
}
diff --git a/src/jvm/clojure/lang/Associative.java b/src/jvm/clojure/lang/Associative.java index eea67e59..1de849d0 100644 --- a/src/jvm/clojure/lang/Associative.java +++ b/src/jvm/clojure/lang/Associative.java @@ -9,12 +9,12 @@ package clojure.lang; * the terms of this license.
* You must not remove this notice, or any other, from this software.
*/
-public interface Associative extends IPersistentCollection {
+public interface Associative extends IPersistentCollection{
boolean contains(Object key);
-IMapEntry find(Object key);
+IMapEntry entryAt(Object key);
Associative assoc(Object key, Object val);
-Object get(Object key);
+Object valAt(Object key);
}
diff --git a/src/jvm/clojure/lang/Compiler.java b/src/jvm/clojure/lang/Compiler.java index 63bb0500..9317bcc6 100644 --- a/src/jvm/clojure/lang/Compiler.java +++ b/src/jvm/clojure/lang/Compiler.java @@ -20,7 +20,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -public class Compiler { +public class Compiler{ //* static Symbol DEF = Symbol.intern("def"); static Symbol FN = Symbol.intern("fn"); @@ -86,617 +86,618 @@ static public Var USES; static public Var FNS; static public IPersistentMap CHAR_MAP = - new PersistentArrayMap('-', "_DSH_", - '.', "_DOT_", - ':', "_CLN_", - '+', "_PLS_", - '>', "_GT_", - '<', "_LT_", - '=', "_EQ_", - '~', "_TLD_", - '!', "_EXC_", - '@', "_AT_", - '#', "_SHP_", - '$', "_DS_", - '%', "_PCT_", - '^', "_CRT_", - '&', "_AMP_", - '*', "_STAR_", - '{', "_LBC_", - '}', "_RBC_", - '[', "_LBK_", - ']', "_RBK_", - '/', "_FSL_", - '\\', "_BSL_", - '?', "_QM_"); + new PersistentArrayMap('-', "_DSH_", + '.', "_DOT_", + ':', "_CLN_", + '+', "_PLS_", + '>', "_GT_", + '<', "_LT_", + '=', "_EQ_", + '~', "_TLD_", + '!', "_EXC_", + '@', "_AT_", + '#', "_SHP_", + '$', "_DS_", + '%', "_PCT_", + '^', "_CRT_", + '&', "_AMP_", + '*', "_STAR_", + '{', "_LBC_", + '}', "_RBC_", + '[', "_LBK_", + ']', "_RBK_", + '/', "_FSL_", + '\\', "_BSL_", + '?', "_QM_"); private static final int MAX_POSITIONAL_ARITY = 20; -static String compile(String ns, String className, LineNumberingPushbackReader... files) throws Exception { - StringWriter w = new StringWriter(); - try - { - _CRT_OUT.pushThreadBinding(w); - KEYWORDS.pushThreadBinding(null); - VARS.pushThreadBinding(null); - METHOD.pushThreadBinding(null); - LOCAL_ENV.pushThreadBinding(null); - FNS.pushThreadBinding(new PersistentArrayList(4)); - - format("/* Generated by Clojure */~%~%"); - format("package ~A;~%", ns); - format("import clojure.lang.*;~%~%"); - format("public class ~A{~%", className); - - PersistentArrayList forms = new PersistentArrayList(20); - for (LineNumberingPushbackReader reader : files) - { - try - { - IMPORTS.pushThreadBinding(null); - USES.pushThreadBinding(null); - - Object eof = new Object(); - Object form = null; - - while ((form = LispReader.read(reader, false, eof, false)) != eof) - { - form = macroexpand(form); - if (!(form instanceof ISeq)) - throw new Exception("No atoms allowed at top level"); - Object op = RT.first(form); - - //enact import and use at compile-time - if (op == IMPORT) - { - //(import org.package ThisClass ThatClass ...) - //makes entries in IMPORTS for: - //"ThisClass"->"org.package.ThisClass" - //"ThatClass"->"org.package.ThatClass" - IPersistentMap importMap = (IPersistentMap) IMPORTS.getValue(); - String pkg = RT.second(form).toString(); - for (ISeq classes = RT.rest(RT.rest(form)); classes != null; classes = classes.rest()) - { - String iclassName = classes.first().toString(); - importMap = (IPersistentMap) RT.assoc(iclassName, pkg + "." + iclassName, importMap); - } - IMPORTS.setValue(importMap); - } - else if (op == USE) - { - //todo implement use - } - else - forms = forms.cons(analyze(C.STATEMENT, form)); - } - } - finally - { - IMPORTS.popThreadBinding(); - USES.popThreadBinding(); - } - } - //declare static members for keywords, vars - for (ISeq keys = RT.seq(KEYWORDS.getValue()); keys != null; keys = keys.rest()) - { - KeywordExpr k = (KeywordExpr) ((IMapEntry) keys.first()).val(); - format("static Keyword ~A;~%", k.emitExpressionString()); - } - for (ISeq vars = RT.seq(VARS.getValue()); vars != null; vars = vars.rest()) - { - Var v = (Var) ((IMapEntry) vars.first()).val(); - format("static Var ~A;~%", munge(v.toString())); - } - - //todo declare static members for syms, quoted aggregates - - //emit nested static class/method declarations for nested fns - PersistentArrayList fns = (PersistentArrayList) FNS.getValue(); - for (int f = 0; f < fns.count(); f++) - { - FnExpr fn = (FnExpr) fns.nth(f); - fn.emitDeclaration(); - } - - //define the load function - format("public void load() throws Exception{~%"); - //init the keywords and vars - for (ISeq keys = RT.seq(KEYWORDS.getValue()); keys != null; keys = keys.rest()) - { - KeywordExpr k = (KeywordExpr) ((IMapEntry) keys.first()).val(); - format("~A = (Keyword)Symbol.intern(~S);~%", k.emitExpressionString(), k.sym.name); - } - for (ISeq vars = RT.seq(VARS.getValue()); vars != null; vars = vars.rest()) - { - Var v = (Var) ((IMapEntry) vars.first()).val(); - format("~A = Module.intern(~S,~S);~%", munge(v.toString()), v.module.name, v.name.name); - } - //todo init syms and quoted aggregates - //emit the top level forms - for (int i = 0; i < forms.count(); i++) - { - Expr e = (Expr) forms.nth(i); - e.emitStatement(); - } - //close load function - format("}~%"); - - //close class def - format("}~%"); - } - catch (Exception e) - { - e.printStackTrace(); - } - finally - { - _CRT_OUT.popThreadBinding(); - KEYWORDS.popThreadBinding(); - VARS.popThreadBinding(); - METHOD.popThreadBinding(); - LOCAL_ENV.popThreadBinding(); - FNS.popThreadBinding(); - } - return w.toString(); -} - -static String munge(String name) { - StringBuilder sb = new StringBuilder(); - for (char c : name.toCharArray()) - { - String sub = (String) CHAR_MAP.get(c); - if (sub != null) - sb.append(sub); - else - sb.append(c); - } - return sb.toString(); -} - -enum C { - STATEMENT,EXPRESSION,RETURN,FN} - -interface Expr { - - void emitReturn() throws Exception; - - void emitStatement() throws Exception; - - void emitExpression() throws Exception; - - String emitExpressionString() throws Exception; - - // may return null if clojure expression with no type hint, or host expression with unknown type - //cannot be used to distinguish host expr vs not - Class getHostType() throws Exception; - - boolean canEmitHostExpr(); - - void emitHostExpr() throws Exception; - -} - -static void format(String str, Object... args) throws Exception { - RT.format(RT.T, str, args); -} - -static class AnExpr implements Expr { - - public void emitReturn() throws Exception { - format("return "); - emitExpression(); - format(";~%"); - } +static String compile(String ns, String className, LineNumberingPushbackReader... files) throws Exception{ + StringWriter w = new StringWriter(); + try + { + _CRT_OUT.pushThreadBinding(w); + KEYWORDS.pushThreadBinding(null); + VARS.pushThreadBinding(null); + METHOD.pushThreadBinding(null); + LOCAL_ENV.pushThreadBinding(null); + FNS.pushThreadBinding(new PersistentArrayList(4)); + + format("/* Generated by Clojure */~%~%"); + format("package ~A;~%", ns); + format("import clojure.lang.*;~%~%"); + format("public class ~A{~%", className); + + PersistentArrayList forms = new PersistentArrayList(20); + for(LineNumberingPushbackReader reader : files) + { + try + { + IMPORTS.pushThreadBinding(null); + USES.pushThreadBinding(null); + + Object eof = new Object(); + Object form = null; + + while((form = LispReader.read(reader, false, eof, false)) != eof) + { + form = macroexpand(form); + if(!(form instanceof ISeq)) + throw new Exception("No atoms allowed at top level"); + Object op = RT.first(form); + + //enact import and use at compile-time + if(op == IMPORT) + { + //(import org.package ThisClass ThatClass ...) + //makes entries in IMPORTS for: + //"ThisClass"->"org.package.ThisClass" + //"ThatClass"->"org.package.ThatClass" + IPersistentMap importMap = (IPersistentMap) IMPORTS.getValue(); + String pkg = RT.second(form).toString(); + for(ISeq classes = RT.rest(RT.rest(form)); classes != null; classes = classes.rest()) + { + String iclassName = classes.first().toString(); + importMap = (IPersistentMap) RT.assoc(iclassName, pkg + "." + iclassName, importMap); + } + IMPORTS.setValue(importMap); + } + else if(op == USE) + { + //todo implement use + } + else + forms = forms.cons(analyze(C.STATEMENT, form)); + } + } + finally + { + IMPORTS.popThreadBinding(); + USES.popThreadBinding(); + } + } + //declare static members for keywords, vars + for(ISeq keys = RT.seq(KEYWORDS.getValue()); keys != null; keys = keys.rest()) + { + KeywordExpr k = (KeywordExpr) ((IMapEntry) keys.first()).val(); + format("static Keyword ~A;~%", k.emitExpressionString()); + } + for(ISeq vars = RT.seq(VARS.getValue()); vars != null; vars = vars.rest()) + { + Var v = (Var) ((IMapEntry) vars.first()).val(); + format("static Var ~A;~%", munge(v.toString())); + } + + //todo declare static members for syms, quoted aggregates + + //emit nested static class/method declarations for nested fns + PersistentArrayList fns = (PersistentArrayList) FNS.getValue(); + for(int f = 0; f < fns.count(); f++) + { + FnExpr fn = (FnExpr) fns.nth(f); + fn.emitDeclaration(); + } + + //define the load function + format("public void load() throws Exception{~%"); + //init the keywords and vars + for(ISeq keys = RT.seq(KEYWORDS.getValue()); keys != null; keys = keys.rest()) + { + KeywordExpr k = (KeywordExpr) ((IMapEntry) keys.first()).val(); + format("~A = (Keyword)Symbol.intern(~S);~%", k.emitExpressionString(), k.sym.name); + } + for(ISeq vars = RT.seq(VARS.getValue()); vars != null; vars = vars.rest()) + { + Var v = (Var) ((IMapEntry) vars.first()).val(); + format("~A = Module.intern(~S,~S);~%", munge(v.toString()), v.module.name, v.name.name); + } + //todo init syms and quoted aggregates + //emit the top level forms + for(int i = 0; i < forms.count(); i++) + { + Expr e = (Expr) forms.nth(i); + e.emitStatement(); + } + //close load function + format("}~%"); + + //close class def + format("}~%"); + } + catch(Exception e) + { + e.printStackTrace(); + } + finally + { + _CRT_OUT.popThreadBinding(); + KEYWORDS.popThreadBinding(); + VARS.popThreadBinding(); + METHOD.popThreadBinding(); + LOCAL_ENV.popThreadBinding(); + FNS.popThreadBinding(); + } + return w.toString(); +} - public void emitStatement() throws Exception { - emitExpression(); - format(";~%"); - } +static String munge(String name){ + StringBuilder sb = new StringBuilder(); + for(char c : name.toCharArray()) + { + String sub = (String) CHAR_MAP.valAt(c); + if(sub != null) + sb.append(sub); + else + sb.append(c); + } + return sb.toString(); +} - public void emitExpression() throws Exception { - throw new UnsupportedOperationException(); - } +enum C{ + STATEMENT, EXPRESSION, RETURN, FN +} - public String emitExpressionString() throws Exception { - StringWriter w = new StringWriter(); - try - { - _CRT_OUT.pushThreadBinding(w); - emitExpression(); - return w.toString(); - } - finally - { - _CRT_OUT.popThreadBinding(); - } - } +interface Expr{ - public Class getHostType() throws Exception { - return null; - } + void emitReturn() throws Exception; - public boolean canEmitHostExpr() { - return false; - } + void emitStatement() throws Exception; - public void emitHostExpr() throws Exception { - throw new Exception("Can't emit as host expr"); - } + void emitExpression() throws Exception; + String emitExpressionString() throws Exception; + + // may return null if clojure expression with no type hint, or host expression with unknown type + //cannot be used to distinguish host expr vs not + Class getHostType() throws Exception; + + boolean canEmitHostExpr(); + + void emitHostExpr() throws Exception; - public String toString() { - try - { - return emitExpressionString(); - } - catch (Exception e) - { - //declared exceptions are an incredibly bad idea !!! - e.printStackTrace(); - return e.toString(); - } - } } -static abstract class AHostExpr extends AnExpr { +static void format(String str, Object... args) throws Exception{ + RT.format(RT.T, str, args); +} - public boolean isHostExpr() { - return false; - } +static class AnExpr implements Expr{ - public void emitExpression() throws Exception { - Class hostType = getHostType(); - boolean needsBox = hostType == null - || hostType.isPrimitive() - || hostType == Boolean.class; - if (needsBox) - format("RT.box("); - emitHostExpr(); - if (needsBox) - format(")"); - } + public void emitReturn() throws Exception{ + format("return "); + emitExpression(); + format(";~%"); + } - public boolean canEmitHostExpr() { - return true; - } + public void emitStatement() throws Exception{ + emitExpression(); + format(";~%"); + } + public void emitExpression() throws Exception{ + throw new UnsupportedOperationException(); + } + + public String emitExpressionString() throws Exception{ + StringWriter w = new StringWriter(); + try + { + _CRT_OUT.pushThreadBinding(w); + emitExpression(); + return w.toString(); + } + finally + { + _CRT_OUT.popThreadBinding(); + } + } + + public Class getHostType() throws Exception{ + return null; + } + + public boolean canEmitHostExpr(){ + return false; + } + + public void emitHostExpr() throws Exception{ + throw new Exception("Can't emit as host expr"); + } + + + public String toString(){ + try + { + return emitExpressionString(); + } + catch(Exception e) + { + //declared exceptions are an incredibly bad idea !!! + e.printStackTrace(); + return e.toString(); + } + } } -public static void processForm(Object form) throws Exception { - if (RT.first(form) == DEF) - { - convert(form); - } - else - throw new UnsupportedOperationException(); -} - -private static void convert(Object form) throws Exception { - Expr e = analyze(C.STATEMENT, form); -} - -private static Expr analyze(C context, Object form) throws Exception { - if (form == null) - return NIL_EXPR; - else if (form instanceof Symbol) - return analyzeSymbol((Symbol) form, false); - else if (form instanceof ISeq) - return analyzeSeq(context, (ISeq) form); - else if (form instanceof Num || form instanceof String) - return new LiteralExpr(form); - else if (form instanceof Character) - return new CharExpr((Character) form); - else - throw new UnsupportedOperationException(); -} - -private static Expr analyzeSeq(C context, ISeq form) throws Exception { - Object op = RT.first(form); - if (op == DEF) - return analyzeDef(context, form); - else if (op == FN) - return analyzeFn(context, form); - else if (op == DO) - return analyzeDo(context, form); - else if (op == IF) - return analyzeIf(context, form); - else if (op == OR) - return analyzeOr(context, form); - else if (op == AND) - return analyzeAnd(context, form); - else if (op == LET) - return analyzeLet(context, form); - else if (op == LET_STAR_) - return analyzeLetStar(context, form); - else if (op == LETFN) - return analyzeLetFn(context, form); - else if (op == NOT || op == NULL_QM_) - return analyzeNot(context, form); - else - { - PersistentArrayList args = new PersistentArrayList(4); - for (ISeq s = op instanceof InstanceMemberSymbol ? RT.rrest(form) : RT.rest(form); s != null; s = s.rest()) - args = args.cons(analyze(C.EXPRESSION, macroexpand(s.first()))); - - if (op instanceof ClassSymbol) - return new InvokeConstructorExpr((ClassSymbol) op, args); - else if (op instanceof StaticMemberSymbol) - return new InvokeStaticMethodExpr((StaticMemberSymbol) op, args); - else if (op instanceof InstanceMemberSymbol) - return analyzeInstanceInvoke((InstanceMemberSymbol) op, - analyze(C.EXPRESSION, macroexpand(RT.second(form))), - args); - - - Expr fexpr = (op instanceof Symbol) ? analyzeSymbol((Symbol) op, true) : analyze(C.EXPRESSION, op); - if (fexpr instanceof FnExpr) - ((FnExpr) fexpr).isCalledDirectly = true; - return new InvokeExpr(fexpr, args); - } +static abstract class AHostExpr extends AnExpr{ + + public boolean isHostExpr(){ + return false; + } + + public void emitExpression() throws Exception{ + Class hostType = getHostType(); + boolean needsBox = hostType == null + || hostType.isPrimitive() + || hostType == Boolean.class; + if(needsBox) + format("RT.box("); + emitHostExpr(); + if(needsBox) + format(")"); + } + + public boolean canEmitHostExpr(){ + return true; + } + +} + +public static void processForm(Object form) throws Exception{ + if(RT.first(form) == DEF) + { + convert(form); + } + else + throw new UnsupportedOperationException(); +} + +private static void convert(Object form) throws Exception{ + Expr e = analyze(C.STATEMENT, form); +} + +private static Expr analyze(C context, Object form) throws Exception{ + if(form == null) + return NIL_EXPR; + else if(form instanceof Symbol) + return analyzeSymbol((Symbol) form, false); + else if(form instanceof ISeq) + return analyzeSeq(context, (ISeq) form); + else if(form instanceof Num || form instanceof String) + return new LiteralExpr(form); + else if(form instanceof Character) + return new CharExpr((Character) form); + else + throw new UnsupportedOperationException(); +} + +private static Expr analyzeSeq(C context, ISeq form) throws Exception{ + Object op = RT.first(form); + if(op == DEF) + return analyzeDef(context, form); + else if(op == FN) + return analyzeFn(context, form); + else if(op == DO) + return analyzeDo(context, form); + else if(op == IF) + return analyzeIf(context, form); + else if(op == OR) + return analyzeOr(context, form); + else if(op == AND) + return analyzeAnd(context, form); + else if(op == LET) + return analyzeLet(context, form); + else if(op == LET_STAR_) + return analyzeLetStar(context, form); + else if(op == LETFN) + return analyzeLetFn(context, form); + else if(op == NOT || op == NULL_QM_) + return analyzeNot(context, form); + else + { + PersistentArrayList args = new PersistentArrayList(4); + for(ISeq s = op instanceof InstanceMemberSymbol ? RT.rrest(form) : RT.rest(form); s != null; s = s.rest()) + args = args.cons(analyze(C.EXPRESSION, macroexpand(s.first()))); + + if(op instanceof ClassSymbol) + return new InvokeConstructorExpr((ClassSymbol) op, args); + else if(op instanceof StaticMemberSymbol) + return new InvokeStaticMethodExpr((StaticMemberSymbol) op, args); + else if(op instanceof InstanceMemberSymbol) + return analyzeInstanceInvoke((InstanceMemberSymbol) op, + analyze(C.EXPRESSION, macroexpand(RT.second(form))), + args); + + + Expr fexpr = (op instanceof Symbol) ? analyzeSymbol((Symbol) op, true) : analyze(C.EXPRESSION, op); + if(fexpr instanceof FnExpr) + ((FnExpr) fexpr).isCalledDirectly = true; + return new InvokeExpr(fexpr, args); + } } private static Expr analyzeInstanceInvoke(InstanceMemberSymbol sym, Expr target, PersistentArrayList args) - throws Exception { - Class targetClass = null; - if (sym.className != null) - targetClass = getTypeNamed(resolveHostClassname(sym.className)); - else if (target.getHostType() != null) - targetClass = target.getHostType(); - else //must make reflection-based call - return new InvokeUntypedInstanceMemberExpr(sym.memberName, target, args); - return new InvokeInstanceMemberExpr(targetClass, sym.memberName, target, args); -} - -static class InvokeExpr extends AnExpr { - Expr fexpr; - PersistentArrayList args; - - public InvokeExpr(Expr fexpr, PersistentArrayList args) { - this.fexpr = fexpr; - this.args = args; - } + throws Exception{ + Class targetClass = null; + if(sym.className != null) + targetClass = getTypeNamed(resolveHostClassname(sym.className)); + else if(target.getHostType() != null) + targetClass = target.getHostType(); + else //must make reflection-based call + return new InvokeUntypedInstanceMemberExpr(sym.memberName, target, args); + return new InvokeInstanceMemberExpr(targetClass, sym.memberName, target, args); +} + +static class InvokeExpr extends AnExpr{ + Expr fexpr; + PersistentArrayList args; + + public InvokeExpr(Expr fexpr, PersistentArrayList args){ + this.fexpr = fexpr; + this.args = args; + } - public void emitExpression() throws Exception { - FnExpr staticMethod = null; - ISeq argseq = RT.seq(args); - if (fexpr instanceof FnExpr && ((FnExpr) fexpr).willBeStaticMethod()) - staticMethod = (FnExpr) fexpr; - else if (fexpr instanceof LocalBindingExpr && ((LocalBindingExpr) fexpr).b.bindsToStaticFn()) - staticMethod = ((LocalBindingExpr) fexpr).b.letfn; - if (staticMethod != null) - { - ISeq closes = RT.keys(staticMethod.closes); - format("~A(~{~A~^, ~}", staticMethod.getName(), closes); - if (closes != null && argseq != null) - format(","); - format("~{~A~^, ~})", argseq); - } - else - { - format("((IFn)~A).invoke(~{~A~^, ~})", fexpr, argseq); - } - } + public void emitExpression() throws Exception{ + FnExpr staticMethod = null; + ISeq argseq = RT.seq(args); + if(fexpr instanceof FnExpr && ((FnExpr) fexpr).willBeStaticMethod()) + staticMethod = (FnExpr) fexpr; + else if(fexpr instanceof LocalBindingExpr && ((LocalBindingExpr) fexpr).b.bindsToStaticFn()) + staticMethod = ((LocalBindingExpr) fexpr).b.letfn; + if(staticMethod != null) + { + ISeq closes = RT.keys(staticMethod.closes); + format("~A(~{~A~^, ~}", staticMethod.getName(), closes); + if(closes != null && argseq != null) + format(","); + format("~{~A~^, ~})", argseq); + } + else + { + format("((IFn)~A).invoke(~{~A~^, ~})", fexpr, argseq); + } + } } -static class InvokeConstructorExpr extends AHostExpr { - HostClassExpr fexpr; - PersistentArrayList args; +static class InvokeConstructorExpr extends AHostExpr{ + HostClassExpr fexpr; + PersistentArrayList args; - public InvokeConstructorExpr(ClassSymbol fexpr, PersistentArrayList args) throws Exception { - this.fexpr = new HostClassExpr(fexpr); - this.args = args; - } + public InvokeConstructorExpr(ClassSymbol fexpr, PersistentArrayList args) throws Exception{ + this.fexpr = new HostClassExpr(fexpr); + this.args = args; + } - public Class getHostType() throws Exception { - return fexpr.type; - } + public Class getHostType() throws Exception{ + return fexpr.type; + } - public void emitHostExpr() throws Exception { - Constructor ctor = findSingleConstructor(fexpr.type, args); + public void emitHostExpr() throws Exception{ + Constructor ctor = findSingleConstructor(fexpr.type, args); - format("(new ~A(", fexpr.resolvedClassName); - if (ctor != null) - emitTypedArgs(ctor.getParameterTypes(), args, ctor.isVarArgs()); - else - emitHostArgs(args); - format("))"); - } + format("(new ~A(", fexpr.resolvedClassName); + if(ctor != null) + emitTypedArgs(ctor.getParameterTypes(), args, ctor.isVarArgs()); + else + emitHostArgs(args); + format("))"); + } } -static class InvokeStaticMethodExpr extends AHostExpr { - final StaticMemberSymbol sym; - final String resolvedClassName; - final Class type; - PersistentArrayList args; - final Method method; - final Class returnType; +static class InvokeStaticMethodExpr extends AHostExpr{ + final StaticMemberSymbol sym; + final String resolvedClassName; + final Class type; + PersistentArrayList args; + final Method method; + final Class returnType; + + public InvokeStaticMethodExpr(StaticMemberSymbol sym, PersistentArrayList args) throws Exception{ + this.sym = sym; + this.args = args; + this.resolvedClassName = resolveHostClassname(sym.className); + this.type = getTypeNamed(resolvedClassName); + Object sm = findSingleMethod(type, sym.memberName, args, true); + if(sm instanceof Method) + { + method = (Method) sm; + returnType = method.getReturnType(); + } + else if(sm instanceof Class) + { + method = null; + returnType = (Class) sm; + } + else + { + method = null; + returnType = null; + } + } - public InvokeStaticMethodExpr(StaticMemberSymbol sym, PersistentArrayList args) throws Exception { - this.sym = sym; - this.args = args; - this.resolvedClassName = resolveHostClassname(sym.className); - this.type = getTypeNamed(resolvedClassName); - Object sm = findSingleMethod(type, sym.memberName, args, true); - if(sm instanceof Method) - { - method = (Method) sm; - returnType = method.getReturnType(); - } - else if(sm instanceof Class) - { - method = null; - returnType = (Class) sm; - } - else - { - method = null; - returnType = null; - } - } + public Class getHostType() throws Exception{ + return returnType; + } - public Class getHostType() throws Exception { - return returnType; - } + public void emitHostExpr() throws Exception{ + format("~A.~A(", resolvedClassName, sym.memberName); + if(method != null) + emitTypedArgs(method.getParameterTypes(), args, method.isVarArgs()); + else + emitHostArgs(args); + format(")"); + } +} + +static class InvokeUntypedInstanceMemberExpr extends AnExpr{ + final String name; + final Expr target; + PersistentArrayList args; + + public InvokeUntypedInstanceMemberExpr(String name, Expr target, PersistentArrayList args) throws Exception{ + this.name = name; + this.args = args; + this.target = target; + } + + public void emitExpression() throws Exception{ + format("Reflector.invokeInstanceMember(~S,~A~{,~A~})", name, target, RT.seq(args)); + } - public void emitHostExpr() throws Exception { - format("~A.~A(", resolvedClassName, sym.memberName); - if (method != null) - emitTypedArgs(method.getParameterTypes(), args, method.isVarArgs()); - else - emitHostArgs(args); - format(")"); - } } -static class InvokeUntypedInstanceMemberExpr extends AnExpr { - final String name; - final Expr target; - PersistentArrayList args; +static class InvokeInstanceMemberExpr extends AHostExpr{ + final String name; + final Expr target; + PersistentArrayList args; + final Class targetType; + final Field field; + final Method method; + final Class returnType; + + public InvokeInstanceMemberExpr(Class targetClass, String name, Expr target, PersistentArrayList args) + throws Exception{ + this.name = name; + this.args = args; + this.target = target; + this.targetType = targetClass; + field = Reflector.getField(targetClass, name, false); + if(field != null) + { + method = null; + returnType = field.getType(); + } + else + { + Object sm = findSingleMethod(targetClass, name, args, false); + if(sm instanceof Method) + { + method = (Method) sm; + returnType = method.getReturnType(); + } + else if(sm instanceof Class) + { + method = null; + returnType = (Class) sm; + } + else + { + method = null; + returnType = null; + } + } + } - public InvokeUntypedInstanceMemberExpr(String name, Expr target, PersistentArrayList args) throws Exception { - this.name = name; - this.args = args; - this.target = target; - } + public Class getHostType() throws Exception{ + return returnType; + } - public void emitExpression() throws Exception { - format("Reflector.invokeInstanceMember(~S,~A~{,~A~})", name, target, RT.seq(args)); - } + public void emitHostExpr() throws Exception{ + if(target.canEmitHostExpr()) + target.emitHostExpr(); + else + emitConvert(targetType, target); + if(field != null) + { + format(".~A", name); + } + else + { + format(".~A(", name); + if(method != null) + emitTypedArgs(method.getParameterTypes(), args, method.isVarArgs()); + else + emitHostArgs(args); + format(")"); + } + } } -static class InvokeInstanceMemberExpr extends AHostExpr { - final String name; - final Expr target; - PersistentArrayList args; - final Class targetType; - final Field field; - final Method method; - final Class returnType; - - public InvokeInstanceMemberExpr(Class targetClass, String name, Expr target, PersistentArrayList args) - throws Exception { - this.name = name; - this.args = args; - this.target = target; - this.targetType = targetClass; - field = Reflector.getField(targetClass, name, false); - if (field != null) - { - method = null; - returnType = field.getType(); - } - else - { - Object sm = findSingleMethod(targetClass, name, args, false); - if(sm instanceof Method) - { - method = (Method) sm; - returnType = method.getReturnType(); - } - else if(sm instanceof Class) - { - method = null; - returnType = (Class) sm; - } - else - { - method = null; - returnType = null; - } - } - } +static void emitHostArgs(PersistentArrayList args) throws Exception{ + for(int i = 0; i < args.count(); i++) + { + Expr arg = (Expr) args.nth(i); + if(arg.canEmitHostExpr()) + arg.emitHostExpr(); + else if(arg.getHostType() != null) + emitConvert(arg.getHostType(), arg); + else + arg.emitExpression(); + if(i < args.count() - 1) + format(","); + } - public Class getHostType() throws Exception { - return returnType; - } +} - public void emitHostExpr() throws Exception { - if(target.canEmitHostExpr()) - target.emitHostExpr(); - else - emitConvert(targetType, target); - if(field != null) - { - format(".~A", name); - } - else - { - format(".~A(", name); - if (method != null) - emitTypedArgs(method.getParameterTypes(), args, method.isVarArgs()); - else - emitHostArgs(args); - format(")"); - } - } +static void emitTypedArgs(Class[] parameterTypes, PersistentArrayList args, boolean isVariadic) throws Exception{ + for(int i = 0; i < (isVariadic ? parameterTypes.length - 1 : args.count()); i++) + { + Expr arg = (Expr) args.nth(i); + if(arg.canEmitHostExpr()) + arg.emitHostExpr(); + else + emitConvert(parameterTypes[i], arg); + if(i < args.count() - 1) + format(","); + } + if(isVariadic) + { + Class vtype = parameterTypes[parameterTypes.length - 1].getComponentType(); + for(int i = parameterTypes.length - 1; i < args.count(); i++) + { + Expr arg = (Expr) args.nth(i); + if(arg.canEmitHostExpr()) + arg.emitHostExpr(); + else + emitConvert(vtype, arg); + if(i < args.count() - 1) + format(","); + } + } } -static void emitHostArgs(PersistentArrayList args) throws Exception { - for (int i = 0; i < args.count(); i++) - { - Expr arg = (Expr) args.nth(i); - if (arg.canEmitHostExpr()) - arg.emitHostExpr(); - else if (arg.getHostType() != null) - emitConvert(arg.getHostType(), arg); - else - arg.emitExpression(); - if (i < args.count() - 1) - format(","); - } - -} - -static void emitTypedArgs(Class[] parameterTypes, PersistentArrayList args, boolean isVariadic) throws Exception { - for (int i = 0; i < (isVariadic ? parameterTypes.length - 1 : args.count()); i++) - { - Expr arg = (Expr) args.nth(i); - if (arg.canEmitHostExpr()) - arg.emitHostExpr(); - else - emitConvert(parameterTypes[i], arg); - if (i < args.count() - 1) - format(","); - } - - if (isVariadic) - { - Class vtype = parameterTypes[parameterTypes.length - 1].getComponentType(); - for (int i = parameterTypes.length - 1; i < args.count(); i++) - { - Expr arg = (Expr) args.nth(i); - if (arg.canEmitHostExpr()) - arg.emitHostExpr(); - else - emitConvert(vtype, arg); - if (i < args.count() - 1) - format(","); - } - } -} - -static void emitConvert(Class parameterType, Expr arg) throws Exception { - if (parameterType == Object.class) - arg.emitExpression(); - else if (parameterType == boolean.class || parameterType == Boolean.class) - format("(~A!=null)", arg); - else if (parameterType == int.class || parameterType == Integer.class) - format("((Number)~A).intValue()", arg); - else if (parameterType == double.class || parameterType == Double.class) - format("((Number)~A).doubleValue()", arg); - else if (parameterType == float.class || parameterType == Float.class) - format("((Number)~A).floatValue()", arg); - else if (parameterType == long.class || parameterType == Long.class) - format("((Number)~A).longValue()", arg); - else if (parameterType == short.class || parameterType == Short.class) - format("((Number)~A).shortValue()", arg); - else if (parameterType == byte.class || parameterType == Byte.class) - format("((Number)~A).byteValue()", arg); - else - format("((~A)~A)", parameterType.getName(), arg); +static void emitConvert(Class parameterType, Expr arg) throws Exception{ + if(parameterType == Object.class) + arg.emitExpression(); + else if(parameterType == boolean.class || parameterType == Boolean.class) + format("(~A!=null)", arg); + else if(parameterType == int.class || parameterType == Integer.class) + format("((Number)~A).intValue()", arg); + else if(parameterType == double.class || parameterType == Double.class) + format("((Number)~A).doubleValue()", arg); + else if(parameterType == float.class || parameterType == Float.class) + format("((Number)~A).floatValue()", arg); + else if(parameterType == long.class || parameterType == Long.class) + format("((Number)~A).longValue()", arg); + else if(parameterType == short.class || parameterType == Short.class) + format("((Number)~A).shortValue()", arg); + else if(parameterType == byte.class || parameterType == Byte.class) + format("((Number)~A).byteValue()", arg); + else + format("((~A)~A)", parameterType.getName(), arg); } /* @@ -714,25 +715,25 @@ static void emitCast(Class parameterType, Expr arg) throws Exception { /*returns null unless single ctor with matching arity, throws if no ctor can handle arity*/ -public static Constructor findSingleConstructor(Class c, PersistentArrayList args) throws Exception { - Constructor[] allctors = c.getConstructors(); - Constructor found = null; - for (int i = 0; i < allctors.length; i++) - { - Constructor ctor = allctors[i]; - if (ctor.getParameterTypes().length == args.count() - || (ctor.isVarArgs() && ctor.getParameterTypes().length <= args.count())) - { - if (found == null) - found = ctor; - else - return null; //more than one matching - } - } - //verify that at least one ctor can handle arity (requires variadic detection) - if (found == null) - throw new Exception("No constructor that can handle arity"); - return found; +public static Constructor findSingleConstructor(Class c, PersistentArrayList args) throws Exception{ + Constructor[] allctors = c.getConstructors(); + Constructor found = null; + for(int i = 0; i < allctors.length; i++) + { + Constructor ctor = allctors[i]; + if(ctor.getParameterTypes().length == args.count() + || (ctor.isVarArgs() && ctor.getParameterTypes().length <= args.count())) + { + if(found == null) + found = ctor; + else + return null; //more than one matching + } + } + //verify that at least one ctor can handle arity (requires variadic detection) + if(found == null) + throw new Exception("No constructor that can handle arity"); + return found; } /*returns Method if single method with matching arity, @@ -740,887 +741,889 @@ public static Constructor findSingleConstructor(Class c, PersistentArrayList arg else returns null throws if no method can handle arity*/ -public static Object findSingleMethod(Class c, String methodName, PersistentArrayList args, boolean isStatic) throws Exception { - Method[] allmethods = c.getMethods(); - Method found = null; - int foundCount = 0; - boolean returnsMatch = true; - for (int i = 0; i < allmethods.length; i++) - { - Method method = allmethods[i]; - if (Modifier.isStatic(method.getModifiers()) == isStatic - && method.getName().equals(methodName) - && (method.getParameterTypes().length == args.count() - || (method.isVarArgs() && method.getParameterTypes().length <= args.count()))) - { - if (found == null) - { - found = method; - foundCount = 1; - } - else - { - ++foundCount; - if (method.getReturnType() != found.getReturnType()) - returnsMatch = false; - } - } - } - //verify that at least one method can handle arity (requires variadic detection) - if (foundCount == 0) - throw new Exception("No method that can handle arity"); - else if(foundCount == 1) - return found; - else if(returnsMatch) - return found.getReturnType(); - return null; -} - -private static Expr analyzeLet(C context, ISeq form) throws Exception { - //(let (var val var2 val2 ...) body...) - ISeq bindings = (ISeq) RT.second(form); - //special case (let () expr) ==> expr - if (bindings == null && form.count() < 4) - return analyze(context, macroexpand(RT.third(form))); - ISeq body = RT.rest(RT.rest(form)); - - if (context == C.EXPRESSION) - { - //(let (a b) c) -> ((fn (a) c) b) - PersistentArrayList parms = new PersistentArrayList(4); - PersistentArrayList args = new PersistentArrayList(4); - for (ISeq bs = bindings; bs != null; bs = RT.rest(RT.rest(bs))) - { - parms = parms.cons(RT.first(bs)); - args = args.cons(RT.second(bs)); - } - return analyze(context, RT.cons(RT.listStar(FN, RT.seq(parms), body), RT.seq(args))); - } - - PersistentArrayList bindingInits = new PersistentArrayList(4); - //analyze inits before adding bindings to env - for (ISeq bs = bindings; bs != null; bs = RT.rest(RT.rest(bs))) - { - LocalBinding lb = new LocalBinding(baseSymbol((Symbol) RT.first(bs))); - lb.typeHint = typeHint((Symbol) RT.first(bs)); - bindingInits = bindingInits.cons(new BindingInit(lb, analyze(C.EXPRESSION, RT.second(bs)))); - } - try - { - LOCAL_ENV.pushThreadBinding(LOCAL_ENV.getValue()); - for (int i = 0; i < bindingInits.count(); i++) - { - BindingInit bi = (BindingInit) bindingInits.nth(i); - if (bi.init instanceof FnExpr) - { - bi.binding.letfn = (FnExpr) bi.init; - ((FnExpr) bi.init).binding = bi.binding; - } - registerLocal(bi.binding); - } - return new LetExpr(bindingInits, analyzeBody(context, body)); - } - finally - { - LOCAL_ENV.popThreadBinding(); - } - -} - -private static Expr analyzeLetFn(C context, ISeq form) throws Exception { - //(letfn ((foo [what can occur after fn]) (bar [what can occur after fn])) body ...) - if (context == C.EXPRESSION) - return analyze(context, RT.list(RT.list(FN, null, form))); - try - { - LOCAL_ENV.pushThreadBinding(LOCAL_ENV.getValue()); - ISeq bindings = (ISeq) RT.second(form); - ISeq body = RT.rest(RT.rest(form)); - PersistentArrayList bindingPairs = new PersistentArrayList(4); - //add all fn names to env before analyzing bodies - for (ISeq bs = bindings; bs != null; bs = RT.rest(bs)) - { - Object bform = RT.first(bs); - Symbol fsym = (Symbol) RT.first(bform); - LocalBinding lb = new LocalBinding(baseSymbol(fsym)); - lb.typeHint = typeHint(fsym); - registerLocal(lb); - bindingPairs = bindingPairs.cons(new Tuple(lb, RT.cons(FN, RT.rest(bform)))); - } - - PersistentArrayList bindingInits = new PersistentArrayList(4); - for (int i = 0; i < bindingPairs.count(); i++) - { - Tuple bpair = (Tuple) bindingPairs.nth(i); - LocalBinding lb = (LocalBinding) bpair.nth(0); - FnExpr fexpr = (FnExpr) analyze(C.EXPRESSION, bpair.nth(1)); - fexpr.binding = lb; - lb.letfn = fexpr; - bindingInits = bindingInits.cons(new BindingInit(lb, fexpr)); - } - return new LetExpr(bindingInits, analyzeBody(context, body)); - } - finally - { - LOCAL_ENV.popThreadBinding(); - } - -} - -private static Expr analyzeLetStar(C context, ISeq form) throws Exception { - //(let* (var val var2 val2 ...) body...) - ISeq bindings = (ISeq) RT.second(form); - //special case (let* () expr) ==> expr - if (bindings == null && form.count() < 4) - return analyze(context, macroexpand(RT.third(form))); - ISeq body = RT.rest(RT.rest(form)); - - if (context == C.EXPRESSION) - return analyze(context, RT.list(RT.list(FN, null, form))); - - try - { - LOCAL_ENV.pushThreadBinding(LOCAL_ENV.getValue()); - PersistentArrayList bindingInits = new PersistentArrayList(4); - for (ISeq bs = bindings; bs != null; bs = RT.rest(RT.rest(bs))) - { - LocalBinding lb = new LocalBinding(baseSymbol((Symbol) RT.first(bs))); - lb.typeHint = typeHint((Symbol) RT.first(bs)); - BindingInit bi = new BindingInit(lb, analyze(C.EXPRESSION, RT.second(bs))); - bindingInits = bindingInits.cons(bi); - if (bi.init instanceof FnExpr) - { - bi.binding.letfn = (FnExpr) bi.init; - ((FnExpr) bi.init).binding = bi.binding; - } - //sequential enhancement of env - registerLocal(lb); - } - - return new LetExpr(bindingInits, analyzeBody(context, body)); - } - finally - { - LOCAL_ENV.popThreadBinding(); - } - -} - -static class LetExpr extends AnExpr { - PersistentArrayList bindingInits; - Expr body; - - public LetExpr(PersistentArrayList bindingInits, Expr body) { - this.bindingInits = bindingInits; - this.body = body; - } +public static Object findSingleMethod(Class c, String methodName, PersistentArrayList args, boolean isStatic) + throws Exception{ + Method[] allmethods = c.getMethods(); + Method found = null; + int foundCount = 0; + boolean returnsMatch = true; + for(int i = 0; i < allmethods.length; i++) + { + Method method = allmethods[i]; + if(Modifier.isStatic(method.getModifiers()) == isStatic + && method.getName().equals(methodName) + && (method.getParameterTypes().length == args.count() + || (method.isVarArgs() && method.getParameterTypes().length <= args.count()))) + { + if(found == null) + { + found = method; + foundCount = 1; + } + else + { + ++foundCount; + if(method.getReturnType() != found.getReturnType()) + returnsMatch = false; + } + } + } + //verify that at least one method can handle arity (requires variadic detection) + if(foundCount == 0) + throw new Exception("No method that can handle arity"); + else if(foundCount == 1) + return found; + else if(returnsMatch) + return found.getReturnType(); + return null; +} + +private static Expr analyzeLet(C context, ISeq form) throws Exception{ + //(let (var val var2 val2 ...) body...) + ISeq bindings = (ISeq) RT.second(form); + //special case (let () expr) ==> expr + if(bindings == null && form.count() < 4) + return analyze(context, macroexpand(RT.third(form))); + ISeq body = RT.rest(RT.rest(form)); + + if(context == C.EXPRESSION) + { + //(let (a b) c) -> ((fn (a) c) b) + PersistentArrayList parms = new PersistentArrayList(4); + PersistentArrayList args = new PersistentArrayList(4); + for(ISeq bs = bindings; bs != null; bs = RT.rest(RT.rest(bs))) + { + parms = parms.cons(RT.first(bs)); + args = args.cons(RT.second(bs)); + } + return analyze(context, RT.cons(RT.listStar(FN, RT.seq(parms), body), RT.seq(args))); + } - public void emitStatement() throws Exception { - emitBindings(); - body.emitStatement(); - } + PersistentArrayList bindingInits = new PersistentArrayList(4); + //analyze inits before adding bindings to env + for(ISeq bs = bindings; bs != null; bs = RT.rest(RT.rest(bs))) + { + LocalBinding lb = new LocalBinding(baseSymbol((Symbol) RT.first(bs))); + lb.typeHint = typeHint((Symbol) RT.first(bs)); + bindingInits = bindingInits.cons(new BindingInit(lb, analyze(C.EXPRESSION, RT.second(bs)))); + } + try + { + LOCAL_ENV.pushThreadBinding(LOCAL_ENV.getValue()); + for(int i = 0; i < bindingInits.count(); i++) + { + BindingInit bi = (BindingInit) bindingInits.nth(i); + if(bi.init instanceof FnExpr) + { + bi.binding.letfn = (FnExpr) bi.init; + ((FnExpr) bi.init).binding = bi.binding; + } + registerLocal(bi.binding); + } + return new LetExpr(bindingInits, analyzeBody(context, body)); + } + finally + { + LOCAL_ENV.popThreadBinding(); + } - private void emitBindings() throws Exception { - for (int i = 0; i < bindingInits.count(); i++) - { - BindingInit bi = (BindingInit) bindingInits.nth(i); - if (!(bi.init instanceof FnExpr && ((FnExpr) bi.init).willBeStaticMethod())) - format("~A = ~A;~%", bi.binding.getExpr(), bi.init.emitExpressionString()); - } - } +} - public void emitReturn() throws Exception { - emitBindings(); - body.emitReturn(); - } +private static Expr analyzeLetFn(C context, ISeq form) throws Exception{ + //(letfn ((foo [what can occur after fn]) (bar [what can occur after fn])) body ...) + if(context == C.EXPRESSION) + return analyze(context, RT.list(RT.list(FN, null, form))); + try + { + LOCAL_ENV.pushThreadBinding(LOCAL_ENV.getValue()); + ISeq bindings = (ISeq) RT.second(form); + ISeq body = RT.rest(RT.rest(form)); + PersistentArrayList bindingPairs = new PersistentArrayList(4); + //add all fn names to env before analyzing bodies + for(ISeq bs = bindings; bs != null; bs = RT.rest(bs)) + { + Object bform = RT.first(bs); + Symbol fsym = (Symbol) RT.first(bform); + LocalBinding lb = new LocalBinding(baseSymbol(fsym)); + lb.typeHint = typeHint(fsym); + registerLocal(lb); + bindingPairs = bindingPairs.cons(new Tuple(lb, RT.cons(FN, RT.rest(bform)))); + } + + PersistentArrayList bindingInits = new PersistentArrayList(4); + for(int i = 0; i < bindingPairs.count(); i++) + { + Tuple bpair = (Tuple) bindingPairs.nth(i); + LocalBinding lb = (LocalBinding) bpair.nth(0); + FnExpr fexpr = (FnExpr) analyze(C.EXPRESSION, bpair.nth(1)); + fexpr.binding = lb; + lb.letfn = fexpr; + bindingInits = bindingInits.cons(new BindingInit(lb, fexpr)); + } + return new LetExpr(bindingInits, analyzeBody(context, body)); + } + finally + { + LOCAL_ENV.popThreadBinding(); + } } -static class BindingInit { - LocalBinding binding; - Expr init; +private static Expr analyzeLetStar(C context, ISeq form) throws Exception{ + //(let* (var val var2 val2 ...) body...) + ISeq bindings = (ISeq) RT.second(form); + //special case (let* () expr) ==> expr + if(bindings == null && form.count() < 4) + return analyze(context, macroexpand(RT.third(form))); + ISeq body = RT.rest(RT.rest(form)); + + if(context == C.EXPRESSION) + return analyze(context, RT.list(RT.list(FN, null, form))); + + try + { + LOCAL_ENV.pushThreadBinding(LOCAL_ENV.getValue()); + PersistentArrayList bindingInits = new PersistentArrayList(4); + for(ISeq bs = bindings; bs != null; bs = RT.rest(RT.rest(bs))) + { + LocalBinding lb = new LocalBinding(baseSymbol((Symbol) RT.first(bs))); + lb.typeHint = typeHint((Symbol) RT.first(bs)); + BindingInit bi = new BindingInit(lb, analyze(C.EXPRESSION, RT.second(bs))); + bindingInits = bindingInits.cons(bi); + if(bi.init instanceof FnExpr) + { + bi.binding.letfn = (FnExpr) bi.init; + ((FnExpr) bi.init).binding = bi.binding; + } + //sequential enhancement of env + registerLocal(lb); + } + + return new LetExpr(bindingInits, analyzeBody(context, body)); + } + finally + { + LOCAL_ENV.popThreadBinding(); + } - public BindingInit(LocalBinding binding, Expr init) { - this.binding = binding; - this.init = init; - } } -private static Expr analyzeAnd(C context, ISeq form) throws Exception { - //(and) (and x) (and x y ...) - //(or) (or X) (or x y ...) - if (RT.count(form) == 1) - return analyze(context, RT.T); - else if (RT.count(form) == 2) - return analyze(context, macroexpand(RT.second(form))); +static class LetExpr extends AnExpr{ + PersistentArrayList bindingInits; + Expr body; + + public LetExpr(PersistentArrayList bindingInits, Expr body){ + this.bindingInits = bindingInits; + this.body = body; + } + + public void emitStatement() throws Exception{ + emitBindings(); + body.emitStatement(); + } + + private void emitBindings() throws Exception{ + for(int i = 0; i < bindingInits.count(); i++) + { + BindingInit bi = (BindingInit) bindingInits.nth(i); + if(!(bi.init instanceof FnExpr && ((FnExpr) bi.init).willBeStaticMethod())) + format("~A = ~A;~%", bi.binding.getExpr(), bi.init.emitExpressionString()); + } + } + + public void emitReturn() throws Exception{ + emitBindings(); + body.emitReturn(); + } - PersistentArrayList exprs = new PersistentArrayList(2); - for (ISeq es = RT.rest(form); es != null; es = es.rest()) - exprs = exprs.cons(analyze(C.EXPRESSION, macroexpand(es.first()))); - return new AndExpr(exprs); } -static class AndExpr extends AnExpr { - final PersistentArrayList exprs; +static class BindingInit{ + LocalBinding binding; + Expr init; - public AndExpr(PersistentArrayList exprs) { - this.exprs = exprs; - } + public BindingInit(LocalBinding binding, Expr init){ + this.binding = binding; + this.init = init; + } +} - public void emitStatement() throws Exception { - format("if("); - for (int i = 0; i < exprs.count(); i++) - { - format("~A != null", ((Expr) exprs.nth(i)).emitExpressionString()); - if (i < exprs.count() - 1) - format(" && "); - } - format(")~%;~%"); - } +private static Expr analyzeAnd(C context, ISeq form) throws Exception{ + //(and) (and x) (and x y ...) + //(or) (or X) (or x y ...) + if(RT.count(form) == 1) + return analyze(context, RT.T); + else if(RT.count(form) == 2) + return analyze(context, macroexpand(RT.second(form))); - public void emitExpression() throws Exception { - format("(("); - for (int i = 0; i < exprs.count(); i++) - { - if (i < exprs.count() - 1) - format("~A != null", ((Expr) exprs.nth(i)).emitExpressionString()); - if (i < exprs.count() - 2) - format(" && "); - if (i == exprs.count() - 1) - format(")?~A:null)", ((Expr) exprs.nth(i)).emitExpressionString()); - } - } + PersistentArrayList exprs = new PersistentArrayList(2); + for(ISeq es = RT.rest(form); es != null; es = es.rest()) + exprs = exprs.cons(analyze(C.EXPRESSION, macroexpand(es.first()))); + return new AndExpr(exprs); } -private static Expr analyzeOr(C context, ISeq form) throws Exception { - //(or) (or X) (or x y ...) - if (RT.count(form) == 1) - return NIL_EXPR; - else if (RT.count(form) == 2) - return analyze(context, macroexpand(RT.second(form))); +static class AndExpr extends AnExpr{ + final PersistentArrayList exprs; + + public AndExpr(PersistentArrayList exprs){ + this.exprs = exprs; + } - LocalBinding tb = null; - if (context != C.STATEMENT) - { - //we'll need a temp var - tb = new LocalBinding(Symbol.intern("OR_TEMP")); - registerLocal(tb); - } + public void emitStatement() throws Exception{ + format("if("); + for(int i = 0; i < exprs.count(); i++) + { + format("~A != null", ((Expr) exprs.nth(i)).emitExpressionString()); + if(i < exprs.count() - 1) + format(" && "); + } + format(")~%;~%"); + } - PersistentArrayList exprs = new PersistentArrayList(2); - for (ISeq es = RT.rest(form); es != null; es = es.rest()) - exprs = exprs.cons(analyze(C.EXPRESSION, macroexpand(es.first()))); - return new OrExpr(exprs, tb); + public void emitExpression() throws Exception{ + format("(("); + for(int i = 0; i < exprs.count(); i++) + { + if(i < exprs.count() - 1) + format("~A != null", ((Expr) exprs.nth(i)).emitExpressionString()); + if(i < exprs.count() - 2) + format(" && "); + if(i == exprs.count() - 1) + format(")?~A:null)", ((Expr) exprs.nth(i)).emitExpressionString()); + } + } } -static class OrExpr extends AnExpr { - final PersistentArrayList exprs; - final LocalBinding tb; +private static Expr analyzeOr(C context, ISeq form) throws Exception{ + //(or) (or X) (or x y ...) + if(RT.count(form) == 1) + return NIL_EXPR; + else if(RT.count(form) == 2) + return analyze(context, macroexpand(RT.second(form))); - public OrExpr(PersistentArrayList exprs, LocalBinding tb) { - this.exprs = exprs; - this.tb = tb; - } + LocalBinding tb = null; + if(context != C.STATEMENT) + { + //we'll need a temp var + tb = new LocalBinding(Symbol.intern("OR_TEMP")); + registerLocal(tb); + } - public void emitStatement() throws Exception { - format("if("); - for (int i = 0; i < exprs.count(); i++) - { - format("~A != null", ((Expr) exprs.nth(i)).emitExpressionString()); - if (i < exprs.count() - 1) - format(" || "); - } - format(")~%;~%"); - } + PersistentArrayList exprs = new PersistentArrayList(2); + for(ISeq es = RT.rest(form); es != null; es = es.rest()) + exprs = exprs.cons(analyze(C.EXPRESSION, macroexpand(es.first()))); + return new OrExpr(exprs, tb); +} - public void emitExpression() throws Exception { - format("(("); - for (int i = 0; i < exprs.count(); i++) - { - format("(~A = ~A) != null", tb.getName(), ((Expr) exprs.nth(i)).emitExpressionString()); - if (i < exprs.count() - 1) - format(" || "); - } - format(")?~A:null)", tb.getName()); - } +static class OrExpr extends AnExpr{ + final PersistentArrayList exprs; + final LocalBinding tb; + + public OrExpr(PersistentArrayList exprs, LocalBinding tb){ + this.exprs = exprs; + this.tb = tb; + } + + public void emitStatement() throws Exception{ + format("if("); + for(int i = 0; i < exprs.count(); i++) + { + format("~A != null", ((Expr) exprs.nth(i)).emitExpressionString()); + if(i < exprs.count() - 1) + format(" || "); + } + format(")~%;~%"); + } + + public void emitExpression() throws Exception{ + format("(("); + for(int i = 0; i < exprs.count(); i++) + { + format("(~A = ~A) != null", tb.getName(), ((Expr) exprs.nth(i)).emitExpressionString()); + if(i < exprs.count() - 1) + format(" || "); + } + format(")?~A:null)", tb.getName()); + } } -private static Expr analyzeNot(C context, ISeq form) throws Exception { - //(not x) or (null? x) - //hmmm - will these be the same with host boolean arg? - return new NotExpr(analyze(C.EXPRESSION, macroexpand(RT.second(form)))); - -} - -private static Expr analyzeIf(C context, ISeq form) throws Exception { - //(if test then) or (if test then else) - if (RT.second(form) == RT.T) //optimize macro-generated (if :t ...) forms - return analyze(context, macroexpand(RT.third(form))); - else if (RT.second(form) == null) - return analyze(context, macroexpand(RT.fourth(form))); - Expr testExpr = analyze(C.EXPRESSION, macroexpand(RT.second(form))); - String compare = "!="; - //lift tests that are not exprs by taking value as test and inverting compare - if (testExpr instanceof NotExpr) - { - testExpr = ((NotExpr) testExpr).expr; - compare = "=="; - } - return new IfExpr(testExpr, compare, analyze(context, macroexpand(RT.third(form))), - analyze(context, macroexpand(RT.fourth(form)))); -} - -private static Expr analyzeDo(C context, ISeq form) throws Exception { - //(do ...) - //(do) == null - if (RT.rest(form) == null) - return NIL_EXPR; - else if (RT.rest(RT.rest(form)) == null) //(do x) == x - return analyze(context, macroexpand(RT.second(form))); - else if (context == C.EXPRESSION) - return analyze(context, RT.list(RT.cons(FN, RT.cons(null, RT.rest(form))))); - else - return analyzeBody(context, RT.rest(form)); - -} - -static class IfExpr extends AnExpr { - final Expr testExpr; - final String compare; - final Expr thenExpr; - final Expr elseExpr; - - public IfExpr(Expr testExpr, String compare, Expr thenExpr, Expr elseExpr) { - this.testExpr = testExpr; - this.compare = compare; - this.thenExpr = thenExpr; - this.elseExpr = elseExpr; - } +private static Expr analyzeNot(C context, ISeq form) throws Exception{ + //(not x) or (null? x) + //hmmm - will these be the same with host boolean arg? + return new NotExpr(analyze(C.EXPRESSION, macroexpand(RT.second(form)))); - public void emitReturn() throws Exception { - format("if(~A ~A null)~%", testExpr.emitExpressionString(), compare); - format("{~%"); - thenExpr.emitReturn(); - format("}~%"); - format("else~%"); - format("{~%"); - elseExpr.emitReturn(); - format("}~%"); - } +} - public void emitStatement() throws Exception { - format("if(~A ~A null)~%", testExpr.emitExpressionString(), compare); - format("{~%"); - thenExpr.emitStatement(); - format("}~%"); - if (!(elseExpr instanceof NilExpr)) - { - format("else~%"); - format("{~%"); - elseExpr.emitStatement(); - format("}~%"); - } - } +private static Expr analyzeIf(C context, ISeq form) throws Exception{ + //(if test then) or (if test then else) + if(RT.second(form) == RT.T) //optimize macro-generated (if :t ...) forms + return analyze(context, macroexpand(RT.third(form))); + else if(RT.second(form) == null) + return analyze(context, macroexpand(RT.fourth(form))); + Expr testExpr = analyze(C.EXPRESSION, macroexpand(RT.second(form))); + String compare = "!="; + //lift tests that are not exprs by taking value as test and inverting compare + if(testExpr instanceof NotExpr) + { + testExpr = ((NotExpr) testExpr).expr; + compare = "=="; + } + return new IfExpr(testExpr, compare, analyze(context, macroexpand(RT.third(form))), + analyze(context, macroexpand(RT.fourth(form)))); +} + +private static Expr analyzeDo(C context, ISeq form) throws Exception{ + //(do ...) + //(do) == null + if(RT.rest(form) == null) + return NIL_EXPR; + else if(RT.rest(RT.rest(form)) == null) //(do x) == x + return analyze(context, macroexpand(RT.second(form))); + else if(context == C.EXPRESSION) + return analyze(context, RT.list(RT.cons(FN, RT.cons(null, RT.rest(form))))); + else + return analyzeBody(context, RT.rest(form)); + +} + +static class IfExpr extends AnExpr{ + final Expr testExpr; + final String compare; + final Expr thenExpr; + final Expr elseExpr; + + public IfExpr(Expr testExpr, String compare, Expr thenExpr, Expr elseExpr){ + this.testExpr = testExpr; + this.compare = compare; + this.thenExpr = thenExpr; + this.elseExpr = elseExpr; + } - public void emitExpression() throws Exception { - format("(~A ~A null?", testExpr.emitExpressionString(), compare); - thenExpr.emitExpression(); - format(":"); - elseExpr.emitExpression(); - format(")"); - } + public void emitReturn() throws Exception{ + format("if(~A ~A null)~%", testExpr.emitExpressionString(), compare); + format("{~%"); + thenExpr.emitReturn(); + format("}~%"); + format("else~%"); + format("{~%"); + elseExpr.emitReturn(); + format("}~%"); + } + + public void emitStatement() throws Exception{ + format("if(~A ~A null)~%", testExpr.emitExpressionString(), compare); + format("{~%"); + thenExpr.emitStatement(); + format("}~%"); + if(!(elseExpr instanceof NilExpr)) + { + format("else~%"); + format("{~%"); + elseExpr.emitStatement(); + format("}~%"); + } + } + + public void emitExpression() throws Exception{ + format("(~A ~A null?", testExpr.emitExpressionString(), compare); + thenExpr.emitExpression(); + format(":"); + elseExpr.emitExpression(); + format(")"); + } } -private static Expr analyzeBody(C context, ISeq forms) throws Exception { - PersistentArrayList exprs = new PersistentArrayList(4); - for (; forms != null; forms = forms.rest()) - { - Expr e = (context == C.STATEMENT || RT.rest(forms) != null) ? - analyze(C.STATEMENT, macroexpand(forms.first())) - : - analyze(C.RETURN, macroexpand(forms.first())); - exprs = exprs.cons(e); - } - return new BodyExpr(exprs); +private static Expr analyzeBody(C context, ISeq forms) throws Exception{ + PersistentArrayList exprs = new PersistentArrayList(4); + for(; forms != null; forms = forms.rest()) + { + Expr e = (context == C.STATEMENT || RT.rest(forms) != null) ? + analyze(C.STATEMENT, macroexpand(forms.first())) + : + analyze(C.RETURN, macroexpand(forms.first())); + exprs = exprs.cons(e); + } + return new BodyExpr(exprs); } -static class BodyExpr extends AnExpr { - PersistentArrayList exprs; +static class BodyExpr extends AnExpr{ + PersistentArrayList exprs; - public BodyExpr(PersistentArrayList exprs) { - this.exprs = exprs; - } + public BodyExpr(PersistentArrayList exprs){ + this.exprs = exprs; + } - public void emitStatement() throws Exception { - if (exprs.count() == 0) - return; - for (int i = 0; i < exprs.count(); i++) - ((Expr) exprs.nth(i)).emitStatement(); - } + public void emitStatement() throws Exception{ + if(exprs.count() == 0) + return; + for(int i = 0; i < exprs.count(); i++) + ((Expr) exprs.nth(i)).emitStatement(); + } - public void emitReturn() throws Exception { - if (exprs.count() == 0) - NIL_EXPR.emitReturn(); - else - { - for (int i = 0; i < exprs.count(); i++) - { - if (i < exprs.count() - 1) - ((Expr) exprs.nth(i)).emitStatement(); - else - ((Expr) exprs.nth(i)).emitReturn(); - } - } - } + public void emitReturn() throws Exception{ + if(exprs.count() == 0) + NIL_EXPR.emitReturn(); + else + { + for(int i = 0; i < exprs.count(); i++) + { + if(i < exprs.count() - 1) + ((Expr) exprs.nth(i)).emitStatement(); + else + ((Expr) exprs.nth(i)).emitReturn(); + } + } + } } -private static Expr analyzeFn(C context, ISeq form) throws Exception { - //(fn (args) body) or (fn ((args) body) ((args2) body2) ...) - //turn former into latter - if (RT.second(form) == null || - !(RT.first(RT.second(form)) == null || RT.first(RT.second(form)) instanceof ISeq)) - form = RT.list(FN, RT.rest(form)); - - FnMethod[] methodArray = new FnMethod[MAX_POSITIONAL_ARITY + 1]; - FnMethod variadicMethod = null; - FnExpr fn = new FnExpr(); - for (ISeq s = RT.rest(form); s != null; s = RT.rest(s)) - { - FnMethod f = analyzeMethod(fn, (ISeq) RT.first(s)); - if (f.isVariadic()) - { - if (variadicMethod == null) - variadicMethod = f; - else - throw new Exception("Can't have more than 1 variadic overload"); - } - else if (methodArray[f.reqParms.count()] == null) - methodArray[f.reqParms.count()] = f; - else - throw new Exception("Can't have 2 overloads with same arity"); - } - if (variadicMethod != null) - { - for (int i = variadicMethod.reqParms.count() + 1; i <= MAX_POSITIONAL_ARITY; i++) - if (methodArray[i] != null) - throw new Exception("Can't have fixed arity function with more params than variadic function"); - } - - IPersistentCollection methods = null; - for (int i = 0; i < methodArray.length; i++) - if (methodArray[i] != null) - methods = RT.cons(methodArray[i], methods); - if (variadicMethod != null) - methods = RT.cons(variadicMethod, methods); - - fn.methods = methods; - fn.variadicMethod = variadicMethod; - registerFn(fn); - return fn; -} - -static class FnExpr extends AnExpr { - IPersistentCollection methods; - FnMethod variadicMethod; - LocalBinding binding; - String name = null; - boolean isCalledDirectly = false; - //localbinding->itself - IPersistentMap closes = null; - - String getName() { - if (name == null) - { - if (binding != null) - name = "FN__" + binding.getName();//munge(binding.sym.name) + "__" + RT.nextID(); - else - name = "FN__" + RT.nextID(); - } - return name; - } +private static Expr analyzeFn(C context, ISeq form) throws Exception{ + //(fn (args) body) or (fn ((args) body) ((args2) body2) ...) + //turn former into latter + if(RT.second(form) == null || + !(RT.first(RT.second(form)) == null || RT.first(RT.second(form)) instanceof ISeq)) + form = RT.list(FN, RT.rest(form)); - public void emitExpression() throws Exception { - format("(new ~A(", getName()); - for (ISeq s = RT.seq(closes); s != null; s = s.rest()) - { - LocalBinding b = (LocalBinding) ((IMapEntry) s.first()).key(); - format("~A", b.getName()); - if (s.rest() != null) - format(","); - } - format("))"); - } + FnMethod[] methodArray = new FnMethod[MAX_POSITIONAL_ARITY + 1]; + FnMethod variadicMethod = null; + FnExpr fn = new FnExpr(); + for(ISeq s = RT.rest(form); s != null; s = RT.rest(s)) + { + FnMethod f = analyzeMethod(fn, (ISeq) RT.first(s)); + if(f.isVariadic()) + { + if(variadicMethod == null) + variadicMethod = f; + else + throw new Exception("Can't have more than 1 variadic overload"); + } + else if(methodArray[f.reqParms.count()] == null) + methodArray[f.reqParms.count()] = f; + else + throw new Exception("Can't have 2 overloads with same arity"); + } + if(variadicMethod != null) + { + for(int i = variadicMethod.reqParms.count() + 1; i <= MAX_POSITIONAL_ARITY; i++) + if(methodArray[i] != null) + throw new Exception("Can't have fixed arity function with more params than variadic function"); + } - public void emitDeclaration() throws Exception { - PersistentArrayList closesDecls = null; - if (closes != null) - { - closesDecls = new PersistentArrayList(closes.count() * 2); - for (ISeq s = RT.seq(closes); s != null; s = s.rest()) - { - LocalBinding b = (LocalBinding) ((IMapEntry) s.first()).key(); - if (!b.bindsToStaticFn()) - { - closesDecls = closesDecls.cons(b.typeDeclaration()); - closesDecls = closesDecls.cons(b.getName()); - } - } - } - if (!willBeStaticMethod()) - { - //emit class declaration - format("static public class ~A extends ~A{~%", - getName(), - variadicMethod != null ? "clojure.lang.RestFn" : "AFn"); - - if (closes != null) - { - //emit members and ctor if closure - format("~{~A ~A;~%~}", closesDecls); - format("public ~A (~{~A ~A~^, ~}){~%", getName(), closesDecls); - if (variadicMethod != null) //must call base ctor - format("super(~A);~%", variadicMethod.reqParms.count()); - for (ISeq s = RT.seq(closes); s != null; s = s.rest()) - { - LocalBinding b = (LocalBinding) ((IMapEntry) s.first()).key(); - if (!b.bindsToStaticFn()) - { - format("this.~A = ~A;~%", b.getName(), b.getName()); - if (s.rest() != null) - format(","); - } - } - format("}~%"); - } - else if (variadicMethod != null) //must create ctor in order to call base ctor - { - format("public ~A (){~%", getName()); - format("super(~A);~%", variadicMethod.reqParms.count()); - format("}~%"); - } - - } - else - { - format("static public Object ~A(~{~A ~A~^, ~}", - getName(), - closesDecls); - } - - for (ISeq methods = RT.seq(this.methods); methods != null; methods = methods.rest()) - { - //this will run once if static method - FnMethod m = (FnMethod) methods.first(); - if (!willBeStaticMethod()) - format("public Object ~A(", m.isVariadic() ? "doInvoke" : "invoke"); - for (ISeq reqs = RT.seq(m.reqParms); reqs != null; reqs = reqs.rest()) - { - LocalBindingExpr be = (LocalBindingExpr) reqs.first(); - format("Object ~A", be.b.getName()); - if (be.b.needsBox()) - format("__arg"); - if (reqs.rest() != null) - format(","); - } - if (m.isVariadic()) - { - if (m.reqParms.count() > 0) - format(","); - format("ISeq "); - if (m.restParm != null) - { - format("~A", m.restParm.b.getName()); - if (m.restParm.b.needsBox()) - format("__arg"); - } - else - format("__keys"); - } - format(") throws Exception{~%"); - - //emit declarations for any boxed args - for (ISeq reqs = RT.seq(m.reqParms); reqs != null; reqs = reqs.rest()) - { - LocalBindingExpr be = (LocalBindingExpr) reqs.first(); - if (be.b.needsBox()) - be.b.emitDeclaration(be.b.getName() + "__arg"); - } - //emit declaration for any boxed rest arg - if (m.restParm != null && m.restParm.b.needsBox()) - m.restParm.b.emitDeclaration(m.restParm.b.getName() + "__arg"); - //keys are locals, plucked out of rest arg - if (m.keyParms != null) - { - format("ISeq __valseq = null;~%"); - for (ISeq keys = RT.seq(m.keyParms); keys != null; keys = keys.rest()) - { - KeyParam key = (KeyParam) keys.first(); - KeywordExpr kw = registerKeyword((Keyword) Symbol.intern(":" + key.bindingExpression.b.sym.name)); - format("__valseq = RT.findKey(~A,__keys);~%", kw.emitExpressionString()); - key.bindingExpression.b.emitDeclaration( - (String) RT.format(null, "(__valseq!=null)?clojure.lang.RT.first(__valseq):~A" - , key.init.emitExpressionString())); - } - } - - //local variables - for (ISeq locals = RT.seq(m.locals); locals != null; locals = locals.rest()) - { - LocalBinding b = (LocalBinding) ((IMapEntry) locals.first()).key(); - if (!b.isParam && !b.bindsToStaticFn()) - b.emitDeclaration("null"); - } - - m.body.emitReturn(); - //end of function - format("}~%"); - } - - //end of class - if (!willBeStaticMethod()) - format("}~%"); - } + IPersistentCollection methods = null; + for(int i = 0; i < methodArray.length; i++) + if(methodArray[i] != null) + methods = RT.cons(methodArray[i], methods); + if(variadicMethod != null) + methods = RT.cons(variadicMethod, methods); + + fn.methods = methods; + fn.variadicMethod = variadicMethod; + registerFn(fn); + return fn; +} + +static class FnExpr extends AnExpr{ + IPersistentCollection methods; + FnMethod variadicMethod; + LocalBinding binding; + String name = null; + boolean isCalledDirectly = false; + //localbinding->itself + IPersistentMap closes = null; + + String getName(){ + if(name == null) + { + if(binding != null) + name = "FN__" + binding.getName();//munge(binding.sym.name) + "__" + RT.nextID(); + else + name = "FN__" + RT.nextID(); + } + return name; + } - boolean willBeStaticMethod() { - return variadicMethod == null - && methods.count() == 1 - && - ( - isCalledDirectly - || - (binding != null && !binding.isAssigned && !binding.valueTaken) - ); - } + public void emitExpression() throws Exception{ + format("(new ~A(", getName()); + for(ISeq s = RT.seq(closes); s != null; s = s.rest()) + { + LocalBinding b = (LocalBinding) ((IMapEntry) s.first()).key(); + format("~A", b.getName()); + if(s.rest() != null) + format(","); + } + format("))"); + } + + public void emitDeclaration() throws Exception{ + PersistentArrayList closesDecls = null; + if(closes != null) + { + closesDecls = new PersistentArrayList(closes.count() * 2); + for(ISeq s = RT.seq(closes); s != null; s = s.rest()) + { + LocalBinding b = (LocalBinding) ((IMapEntry) s.first()).key(); + if(!b.bindsToStaticFn()) + { + closesDecls = closesDecls.cons(b.typeDeclaration()); + closesDecls = closesDecls.cons(b.getName()); + } + } + } + if(!willBeStaticMethod()) + { + //emit class declaration + format("static public class ~A extends ~A{~%", + getName(), + variadicMethod != null ? "clojure.lang.RestFn" : "AFn"); + + if(closes != null) + { + //emit members and ctor if closure + format("~{~A ~A;~%~}", closesDecls); + format("public ~A (~{~A ~A~^, ~}){~%", getName(), closesDecls); + if(variadicMethod != null) //must call base ctor + format("super(~A);~%", variadicMethod.reqParms.count()); + for(ISeq s = RT.seq(closes); s != null; s = s.rest()) + { + LocalBinding b = (LocalBinding) ((IMapEntry) s.first()).key(); + if(!b.bindsToStaticFn()) + { + format("this.~A = ~A;~%", b.getName(), b.getName()); + if(s.rest() != null) + format(","); + } + } + format("}~%"); + } + else if(variadicMethod != null) //must create ctor in order to call base ctor + { + format("public ~A (){~%", getName()); + format("super(~A);~%", variadicMethod.reqParms.count()); + format("}~%"); + } + + } + else + { + format("static public Object ~A(~{~A ~A~^, ~}", + getName(), + closesDecls); + } + + for(ISeq methods = RT.seq(this.methods); methods != null; methods = methods.rest()) + { + //this will run once if static method + FnMethod m = (FnMethod) methods.first(); + if(!willBeStaticMethod()) + format("public Object ~A(", m.isVariadic() ? "doInvoke" : "invoke"); + for(ISeq reqs = RT.seq(m.reqParms); reqs != null; reqs = reqs.rest()) + { + LocalBindingExpr be = (LocalBindingExpr) reqs.first(); + format("Object ~A", be.b.getName()); + if(be.b.needsBox()) + format("__arg"); + if(reqs.rest() != null) + format(","); + } + if(m.isVariadic()) + { + if(m.reqParms.count() > 0) + format(","); + format("ISeq "); + if(m.restParm != null) + { + format("~A", m.restParm.b.getName()); + if(m.restParm.b.needsBox()) + format("__arg"); + } + else + format("__keys"); + } + format(") throws Exception{~%"); + + //emit declarations for any boxed args + for(ISeq reqs = RT.seq(m.reqParms); reqs != null; reqs = reqs.rest()) + { + LocalBindingExpr be = (LocalBindingExpr) reqs.first(); + if(be.b.needsBox()) + be.b.emitDeclaration(be.b.getName() + "__arg"); + } + //emit declaration for any boxed rest arg + if(m.restParm != null && m.restParm.b.needsBox()) + m.restParm.b.emitDeclaration(m.restParm.b.getName() + "__arg"); + //keys are locals, plucked out of rest arg + if(m.keyParms != null) + { + format("ISeq __valseq = null;~%"); + for(ISeq keys = RT.seq(m.keyParms); keys != null; keys = keys.rest()) + { + KeyParam key = (KeyParam) keys.first(); + KeywordExpr kw = registerKeyword((Keyword) Symbol.intern(":" + key.bindingExpression.b.sym.name)); + format("__valseq = RT.findKey(~A,__keys);~%", kw.emitExpressionString()); + key.bindingExpression.b.emitDeclaration( + (String) RT.format(null, "(__valseq!=null)?clojure.lang.RT.first(__valseq):~A" + , key.init.emitExpressionString())); + } + } + + //local variables + for(ISeq locals = RT.seq(m.locals); locals != null; locals = locals.rest()) + { + LocalBinding b = (LocalBinding) ((IMapEntry) locals.first()).key(); + if(!b.isParam && !b.bindsToStaticFn()) + b.emitDeclaration("null"); + } + + m.body.emitReturn(); + //end of function + format("}~%"); + } + + //end of class + if(!willBeStaticMethod()) + format("}~%"); + } + + boolean willBeStaticMethod(){ + return variadicMethod == null + && methods.count() == 1 + && + ( + isCalledDirectly + || + (binding != null && !binding.isAssigned && !binding.valueTaken) + ); + } } -static class FnMethod { - FnMethod parent = null; - //localbinding->localbinding - IPersistentMap locals = null; - //localbinding->localbinding - PersistentArrayList reqParms = new PersistentArrayList(4); - PersistentArrayList keyParms = null; - LocalBindingExpr restParm = null; - Expr body = null; - FnExpr fn; - - public FnMethod(FnExpr fn, FnMethod parent) { - this.parent = parent; - this.fn = fn; - } +static class FnMethod{ + FnMethod parent = null; + //localbinding->localbinding + IPersistentMap locals = null; + //localbinding->localbinding + PersistentArrayList reqParms = new PersistentArrayList(4); + PersistentArrayList keyParms = null; + LocalBindingExpr restParm = null; + Expr body = null; + FnExpr fn; + + public FnMethod(FnExpr fn, FnMethod parent){ + this.parent = parent; + this.fn = fn; + } - boolean isVariadic() { - return keyParms != null || restParm != null; - } + boolean isVariadic(){ + return keyParms != null || restParm != null; + } } -enum PSTATE { - REQ,REST,KEY,DONE} - -private static FnMethod analyzeMethod(FnExpr fn, ISeq form) throws Exception { - //((args) body) - ISeq parms = (ISeq) RT.first(form); - ISeq body = RT.rest(form); - try - { - FnMethod method = new FnMethod(fn, (FnMethod) METHOD.getValue()); - METHOD.pushThreadBinding(method); - LOCAL_ENV.pushThreadBinding(LOCAL_ENV.getValue()); - PSTATE state = PSTATE.REQ; - for (ISeq ps = parms; ps != null; ps = ps.rest()) - { - Object p = ps.first(); - if (p == _AMP_REST) - { - if (state == PSTATE.REQ) - state = PSTATE.REST; - else - throw new Exception("Invalid parameter list"); - } - else if (p == _AMP_KEY) - { - if (state == PSTATE.REQ) - { - state = PSTATE.KEY; - method.keyParms = new PersistentArrayList(4); - } - else - throw new Exception("Invalid parameter list"); - } - else - { - switch (state) - { - case REQ: - method.reqParms = method.reqParms.cons(createParamBinding((Symbol) p)); - break; - case REST: - method.restParm = createParamBinding((Symbol) p); - state = PSTATE.DONE; - break; - case KEY: - if (p instanceof ISeq) - method.keyParms = method.keyParms.cons( - new KeyParam(createParamBinding((Symbol) RT.first(p)), - analyze(C.EXPRESSION, RT.second(p)))); - else - method.keyParms = method.keyParms.cons( - new KeyParam(createParamBinding((Symbol) p))); - - break; - default: - throw new Exception("Unexpected parameter"); - } - } - } - if (method.reqParms.count() > MAX_POSITIONAL_ARITY) - throw new Exception("Sorry, can't specify more than " + MAX_POSITIONAL_ARITY + " params"); - method.body = analyze(C.RETURN, RT.cons(DO, body)); - return method; - } - finally - { - METHOD.popThreadBinding(); - LOCAL_ENV.popThreadBinding(); - } +enum PSTATE{ + REQ, REST, KEY, DONE +} + +private static FnMethod analyzeMethod(FnExpr fn, ISeq form) throws Exception{ + //((args) body) + ISeq parms = (ISeq) RT.first(form); + ISeq body = RT.rest(form); + try + { + FnMethod method = new FnMethod(fn, (FnMethod) METHOD.getValue()); + METHOD.pushThreadBinding(method); + LOCAL_ENV.pushThreadBinding(LOCAL_ENV.getValue()); + PSTATE state = PSTATE.REQ; + for(ISeq ps = parms; ps != null; ps = ps.rest()) + { + Object p = ps.first(); + if(p == _AMP_REST) + { + if(state == PSTATE.REQ) + state = PSTATE.REST; + else + throw new Exception("Invalid parameter list"); + } + else if(p == _AMP_KEY) + { + if(state == PSTATE.REQ) + { + state = PSTATE.KEY; + method.keyParms = new PersistentArrayList(4); + } + else + throw new Exception("Invalid parameter list"); + } + else + { + switch(state) + { + case REQ: + method.reqParms = method.reqParms.cons(createParamBinding((Symbol) p)); + break; + case REST: + method.restParm = createParamBinding((Symbol) p); + state = PSTATE.DONE; + break; + case KEY: + if(p instanceof ISeq) + method.keyParms = method.keyParms.cons( + new KeyParam(createParamBinding((Symbol) RT.first(p)), + analyze(C.EXPRESSION, RT.second(p)))); + else + method.keyParms = method.keyParms.cons( + new KeyParam(createParamBinding((Symbol) p))); + + break; + default: + throw new Exception("Unexpected parameter"); + } + } + } + if(method.reqParms.count() > MAX_POSITIONAL_ARITY) + throw new Exception("Sorry, can't specify more than " + MAX_POSITIONAL_ARITY + " params"); + method.body = analyze(C.RETURN, RT.cons(DO, body)); + return method; + } + finally + { + METHOD.popThreadBinding(); + LOCAL_ENV.popThreadBinding(); + } } static LocalBindingExpr createParamBinding(Symbol p) throws Exception{ - Symbol basep = baseSymbol(p); - LocalBinding b = new LocalBinding(basep); - b.isParam = true; - String typeHint = typeHint(p); - b.typeHint = typeHint; - registerLocal(b); - return new LocalBindingExpr(b, typeHint); -} - -private static Expr analyzeDef(C context, ISeq form) throws Exception { - //(def x) or (def x initexpr) - if (form.count() > 3) - throw new Exception("Too many arguments to def"); - Symbol sym = (Symbol) RT.second(form); - Module module = (Module) _CRT_MODULE.getValue(); - Var var = module.intern(baseSymbol(sym)); - registerVar(var); - VarExpr ve = new VarExpr(var, typeHint(sym)); - Expr init = analyze(C.EXPRESSION, macroexpand(RT.third(form))); - if (init instanceof FnExpr) - ((FnExpr) init).name = "FN__" + munge(var.name.toString()) + "__" + RT.nextID(); - - return new DefExpr(ve, init); -} - -static Symbol baseSymbol(Symbol sym) { - String base = baseName(sym); - - if (base == sym.name) //no typeHint - return sym; - - return Symbol.intern(base); -} - -static String baseName(Symbol sym) { - int slash = sym.name.indexOf('/'); - if (slash > 0) - return sym.name.substring(0, slash); - return sym.name; -} - -static String typeHint(Symbol sym) { - int slash = sym.name.indexOf('/'); - if (slash > 0) - return sym.name.substring(slash + 1); - return null; -} - -private static Expr analyzeSymbol(Symbol sym, boolean inFnPosition) throws Exception { - if (sym instanceof Keyword) - return registerKeyword((Keyword) sym); - else if (sym instanceof ClassSymbol) - return new HostClassExpr((ClassSymbol) sym); - else if (sym instanceof StaticMemberSymbol) - return new HostStaticFieldExpr((StaticMemberSymbol) sym); - //todo have InstanceMemberSymbol yield accessor when expression - else - { - String typeHint = typeHint(sym); - sym = baseSymbol(sym); - LocalBinding b = referenceLocal(sym); - if (b != null) - { - if (!inFnPosition) - b.valueTaken = true; - return new LocalBindingExpr(b, typeHint); - } - Var v = lookupVar(sym); - if (v != null) - return new VarExpr(v, typeHint); - throw new Exception("Unable to resolve symbol: " + sym.name + " in this context"); - } + Symbol basep = baseSymbol(p); + LocalBinding b = new LocalBinding(basep); + b.isParam = true; + String typeHint = typeHint(p); + b.typeHint = typeHint; + registerLocal(b); + return new LocalBindingExpr(b, typeHint); +} + +private static Expr analyzeDef(C context, ISeq form) throws Exception{ + //(def x) or (def x initexpr) + if(form.count() > 3) + throw new Exception("Too many arguments to def"); + Symbol sym = (Symbol) RT.second(form); + Module module = (Module) _CRT_MODULE.getValue(); + Var var = module.intern(baseSymbol(sym)); + registerVar(var); + VarExpr ve = new VarExpr(var, typeHint(sym)); + Expr init = analyze(C.EXPRESSION, macroexpand(RT.third(form))); + if(init instanceof FnExpr) + ((FnExpr) init).name = "FN__" + munge(var.name.toString()) + "__" + RT.nextID(); + + return new DefExpr(ve, init); +} + +static Symbol baseSymbol(Symbol sym){ + String base = baseName(sym); + + if(base == sym.name) //no typeHint + return sym; + + return Symbol.intern(base); +} + +static String baseName(Symbol sym){ + int slash = sym.name.indexOf('/'); + if(slash > 0) + return sym.name.substring(0, slash); + return sym.name; +} + +static String typeHint(Symbol sym){ + int slash = sym.name.indexOf('/'); + if(slash > 0) + return sym.name.substring(slash + 1); + return null; +} + +private static Expr analyzeSymbol(Symbol sym, boolean inFnPosition) throws Exception{ + if(sym instanceof Keyword) + return registerKeyword((Keyword) sym); + else if(sym instanceof ClassSymbol) + return new HostClassExpr((ClassSymbol) sym); + else if(sym instanceof StaticMemberSymbol) + return new HostStaticFieldExpr((StaticMemberSymbol) sym); + //todo have InstanceMemberSymbol yield accessor when expression + else + { + String typeHint = typeHint(sym); + sym = baseSymbol(sym); + LocalBinding b = referenceLocal(sym); + if(b != null) + { + if(!inFnPosition) + b.valueTaken = true; + return new LocalBindingExpr(b, typeHint); + } + Var v = lookupVar(sym); + if(v != null) + return new VarExpr(v, typeHint); + throw new Exception("Unable to resolve symbol: " + sym.name + " in this context"); + } } static Var lookupVar(Symbol sym) throws Exception{ - Module module = (Module) _CRT_MODULE.getValue(); - Var v = module.find(sym); - if (v != null) - return v; - for (ISeq seq = RT.seq(USES.getValue()); seq != null; seq = RT.rest(seq)) - { - module = (Module) ((IMapEntry) RT.first(seq)).key(); - v = module.find(sym); - if (v != null && !v.exported) - return v; - } - return null; + Module module = (Module) _CRT_MODULE.getValue(); + Var v = module.find(sym); + if(v != null) + return v; + for(ISeq seq = RT.seq(USES.getValue()); seq != null; seq = RT.rest(seq)) + { + module = (Module) ((IMapEntry) RT.first(seq)).key(); + v = module.find(sym); + if(v != null && !v.exported) + return v; + } + return null; } -static Object macroexpand(Object x) { - return x; //placeholder +static Object macroexpand(Object x){ + return x; //placeholder } private static KeywordExpr registerKeyword(Keyword keyword) throws Exception{ - IPersistentMap keywordsMap = (IPersistentMap) KEYWORDS.getValue(); - KeywordExpr ke = (KeywordExpr) RT.get(keyword, keywordsMap); - if (ke == null) - KEYWORDS.setValue(RT.assoc(keyword, ke = new KeywordExpr(keyword), keywordsMap)); - return ke; + IPersistentMap keywordsMap = (IPersistentMap) KEYWORDS.getValue(); + KeywordExpr ke = (KeywordExpr) RT.get(keyword, keywordsMap); + if(ke == null) + KEYWORDS.setValue(RT.assoc(keyword, ke = new KeywordExpr(keyword), keywordsMap)); + return ke; } private static void registerVar(Var var) throws Exception{ - IPersistentMap varsMap = (IPersistentMap) VARS.getValue(); - if (RT.get(var, varsMap) == null) - VARS.setValue(RT.assoc(var, var, varsMap)); + IPersistentMap varsMap = (IPersistentMap) VARS.getValue(); + if(RT.get(var, varsMap) == null) + VARS.setValue(RT.assoc(var, var, varsMap)); } private static void registerFn(FnExpr fn) throws Exception{ - FNS.setValue(RT.cons(fn, (IPersistentCollection) FNS.getValue())); + FNS.setValue(RT.cons(fn, (IPersistentCollection) FNS.getValue())); } -static void closeOver(LocalBinding b, FnMethod method) { - if (b != null && method != null && RT.get(b, method.locals) == null) - { - b.isClosed = true; - method.fn.closes = (IPersistentMap) RT.assoc(b, b, method.fn.closes); - closeOver(b, method.parent); - } +static void closeOver(LocalBinding b, FnMethod method){ + if(b != null && method != null && RT.get(b, method.locals) == null) + { + b.isClosed = true; + method.fn.closes = (IPersistentMap) RT.assoc(b, b, method.fn.closes); + closeOver(b, method.parent); + } } static LocalBinding referenceLocal(Symbol sym) throws Exception{ - LocalBinding b = (LocalBinding) RT.get(sym, LOCAL_ENV.getValue()); - if (b != null) - { - closeOver(b, (FnMethod) METHOD.getValue()); - } - return b; + LocalBinding b = (LocalBinding) RT.get(sym, LOCAL_ENV.getValue()); + if(b != null) + { + closeOver(b, (FnMethod) METHOD.getValue()); + } + return b; } private static void registerLocal(LocalBinding b) throws Exception{ - IPersistentMap localsMap = (IPersistentMap) LOCAL_ENV.getValue(); - LOCAL_ENV.setValue(RT.assoc(b.sym, b, localsMap)); - FnMethod method = (FnMethod) METHOD.getValue(); - method.locals = (IPersistentMap) RT.assoc(b, b, method.locals); + IPersistentMap localsMap = (IPersistentMap) LOCAL_ENV.getValue(); + LOCAL_ENV.setValue(RT.assoc(b.sym, b, localsMap)); + FnMethod method = (FnMethod) METHOD.getValue(); + method.locals = (IPersistentMap) RT.assoc(b, b, method.locals); } /* (defun reference-var (sym) @@ -1637,198 +1640,198 @@ private static void registerLocal(LocalBinding b) throws Exception{ b)) */ -static String resolveHostClassname(String classname) throws Exception { - if (classname.indexOf('.') != -1) //presume fully qualified if contains . - return classname; - if (isPrimitive(classname)) - return classname; - IPersistentMap importMap = (IPersistentMap) IMPORTS.getValue(); - String fullyQualifiedName = (String) RT.get(classname, importMap); - if (fullyQualifiedName == null) - throw new Exception("Can't resolve type name: " + classname); - return fullyQualifiedName; -} - -static boolean isPrimitive(String classname) { - return classname.equals("int") - || classname.equals("double") - || classname.equals("float") - || classname.equals("long") - || classname.equals("boolean") - || classname.equals("char") - || classname.equals("short") - || classname.equals("byte"); -} - -static Class getTypeNamed(String classname) throws ClassNotFoundException { - if (classname.equals("int")) - return int.class; - if (classname.equals("double")) - return double.class; - if (classname.equals("float")) - return float.class; - if (classname.equals("long")) - return long.class; - if (classname.equals("boolean")) - return boolean.class; - if (classname.equals("char")) - return char.class; - if (classname.equals("short")) - return short.class; - if (classname.equals("byte")) - return byte.class; - return Class.forName(classname); -} - - -static class KeyParam { - public KeyParam(LocalBindingExpr b, Expr init) throws Exception{ - this.bindingExpression = b; - this.init = init; - kw = registerKeyword((Keyword) Symbol.intern(":" + bindingExpression.b.sym.name)); - } +static String resolveHostClassname(String classname) throws Exception{ + if(classname.indexOf('.') != -1) //presume fully qualified if contains . + return classname; + if(isPrimitive(classname)) + return classname; + IPersistentMap importMap = (IPersistentMap) IMPORTS.getValue(); + String fullyQualifiedName = (String) RT.get(classname, importMap); + if(fullyQualifiedName == null) + throw new Exception("Can't resolve type name: " + classname); + return fullyQualifiedName; +} + +static boolean isPrimitive(String classname){ + return classname.equals("int") + || classname.equals("double") + || classname.equals("float") + || classname.equals("long") + || classname.equals("boolean") + || classname.equals("char") + || classname.equals("short") + || classname.equals("byte"); +} + +static Class getTypeNamed(String classname) throws ClassNotFoundException{ + if(classname.equals("int")) + return int.class; + if(classname.equals("double")) + return double.class; + if(classname.equals("float")) + return float.class; + if(classname.equals("long")) + return long.class; + if(classname.equals("boolean")) + return boolean.class; + if(classname.equals("char")) + return char.class; + if(classname.equals("short")) + return short.class; + if(classname.equals("byte")) + return byte.class; + return Class.forName(classname); +} + + +static class KeyParam{ + public KeyParam(LocalBindingExpr b, Expr init) throws Exception{ + this.bindingExpression = b; + this.init = init; + kw = registerKeyword((Keyword) Symbol.intern(":" + bindingExpression.b.sym.name)); + } - public KeyParam(LocalBindingExpr b) throws Exception{ - this(b, NIL_EXPR); - } + public KeyParam(LocalBindingExpr b) throws Exception{ + this(b, NIL_EXPR); + } - LocalBindingExpr bindingExpression; - Expr init; - KeywordExpr kw; + LocalBindingExpr bindingExpression; + Expr init; + KeywordExpr kw; } -static class NilExpr extends AnExpr { - public void emitExpression() throws Exception { - format("null"); - } +static class NilExpr extends AnExpr{ + public void emitExpression() throws Exception{ + format("null"); + } } -static class LiteralExpr extends AnExpr { - final Object val; +static class LiteralExpr extends AnExpr{ + final Object val; - public LiteralExpr(Object val) { - this.val = val; - } + public LiteralExpr(Object val){ + this.val = val; + } - public void emitExpression() throws Exception { - format("~S", val); - } + public void emitExpression() throws Exception{ + format("~S", val); + } - public Class getHostType() throws Exception { - if (val instanceof DoubleNum) - return double.class; - if (val instanceof FixNum) - return int.class; - return val.getClass(); - } + public Class getHostType() throws Exception{ + if(val instanceof DoubleNum) + return double.class; + if(val instanceof FixNum) + return int.class; + return val.getClass(); + } - public boolean canEmitHostExpr() { - return val instanceof FixNum || val instanceof String || val instanceof DoubleNum; - } + public boolean canEmitHostExpr(){ + return val instanceof FixNum || val instanceof String || val instanceof DoubleNum; + } - public void emitHostExpr() throws Exception { - if (val instanceof FixNum) - format("~A", ((FixNum) val).val); - else if (val instanceof String) - format("~S", val); - else if (val instanceof DoubleNum) - format("~A", ((DoubleNum) val).val); - else - super.emitHostExpr(); - } + public void emitHostExpr() throws Exception{ + if(val instanceof FixNum) + format("~A", ((FixNum) val).val); + else if(val instanceof String) + format("~S", val); + else if(val instanceof DoubleNum) + format("~A", ((DoubleNum) val).val); + else + super.emitHostExpr(); + } } -static class NotExpr extends AnExpr { - final Expr expr; +static class NotExpr extends AnExpr{ + final Expr expr; - public NotExpr(Expr expr) { - this.expr = expr; - } + public NotExpr(Expr expr){ + this.expr = expr; + } - public void emitStatement() throws Exception { - //just execute expr for side effects - no negation - expr.emitStatement(); - } + public void emitStatement() throws Exception{ + //just execute expr for side effects - no negation + expr.emitStatement(); + } - public void emitExpression() throws Exception { - format("(("); - expr.emitExpression(); - format("==null)?RT.T:null)"); - } + public void emitExpression() throws Exception{ + format("(("); + expr.emitExpression(); + format("==null)?RT.T:null)"); + } } -static class CharExpr extends AnExpr { - final Character val; +static class CharExpr extends AnExpr{ + final Character val; - public CharExpr(Character val) { - this.val = val; - } + public CharExpr(Character val){ + this.val = val; + } - public void emitExpression() throws Exception { - format("'~A'", val); - } + public void emitExpression() throws Exception{ + format("'~A'", val); + } - public Class getHostType() throws Exception { - return char.class; - } + public Class getHostType() throws Exception{ + return char.class; + } - public boolean canEmitHostExpr() { - return true; - } + public boolean canEmitHostExpr(){ + return true; + } - public void emitHostExpr() throws Exception { - emitExpression(); - } + public void emitHostExpr() throws Exception{ + emitExpression(); + } } -static class HostClassExpr extends AHostExpr { - final ClassSymbol sym; - final String resolvedClassName; - final Class type; +static class HostClassExpr extends AHostExpr{ + final ClassSymbol sym; + final String resolvedClassName; + final Class type; - public HostClassExpr(ClassSymbol sym) throws Exception { - this.sym = sym; - this.resolvedClassName = resolveHostClassname(sym.className); - this.type = getTypeNamed(resolvedClassName); - } + public HostClassExpr(ClassSymbol sym) throws Exception{ + this.sym = sym; + this.resolvedClassName = resolveHostClassname(sym.className); + this.type = getTypeNamed(resolvedClassName); + } - public void emitHostExpr() throws Exception { - format("~A.class", resolvedClassName); - } + public void emitHostExpr() throws Exception{ + format("~A.class", resolvedClassName); + } - public Class getHostType() throws Exception { - return type; - } + public Class getHostType() throws Exception{ + return type; + } } -static class HostStaticFieldExpr extends AHostExpr { - final StaticMemberSymbol sym; - final String resolvedClassName; - final Class type; - final Class fieldType; +static class HostStaticFieldExpr extends AHostExpr{ + final StaticMemberSymbol sym; + final String resolvedClassName; + final Class type; + final Class fieldType; - public HostStaticFieldExpr(StaticMemberSymbol sym) throws Exception { - this.sym = sym; - this.resolvedClassName = resolveHostClassname(sym.className); - this.type = getTypeNamed(resolvedClassName); - Field f = Reflector.getField(type, sym.memberName, true); - if (f == null) - throw new Exception(String.format("Can't find field %1$ in class %2$", - sym.memberName, resolvedClassName)); - fieldType = f.getType(); - } + public HostStaticFieldExpr(StaticMemberSymbol sym) throws Exception{ + this.sym = sym; + this.resolvedClassName = resolveHostClassname(sym.className); + this.type = getTypeNamed(resolvedClassName); + Field f = Reflector.getField(type, sym.memberName, true); + if(f == null) + throw new Exception(String.format("Can't find field %1$ in class %2$", + sym.memberName, resolvedClassName)); + fieldType = f.getType(); + } - public void emitHostExpr() throws Exception { - format("~A.~A", resolvedClassName, sym.memberName); - } + public void emitHostExpr() throws Exception{ + format("~A.~A", resolvedClassName, sym.memberName); + } - public Class getHostType() throws Exception { - return fieldType; - } + public Class getHostType() throws Exception{ + return fieldType; + } } /* @@ -1847,163 +1850,163 @@ static class SymExpr extends AnExpr{ } */ -static class KeywordExpr extends AnExpr { - final Symbol sym; +static class KeywordExpr extends AnExpr{ + final Symbol sym; - public KeywordExpr(Symbol sym) { - this.sym = sym; - } + public KeywordExpr(Symbol sym){ + this.sym = sym; + } - public void emitExpression() throws Exception { - format("~A", munge(sym.name)); - } + public void emitExpression() throws Exception{ + format("~A", munge(sym.name)); + } } -static class LocalBinding { - final Symbol sym; - boolean isClosed = false; - boolean isParam = false; - final int id = RT.nextID(); - String typeHint; - public boolean valueTaken = false; - boolean isAssigned = false; - FnExpr letfn = null; +static class LocalBinding{ + final Symbol sym; + boolean isClosed = false; + boolean isParam = false; + final int id = RT.nextID(); + String typeHint; + public boolean valueTaken = false; + boolean isAssigned = false; + FnExpr letfn = null; - public LocalBinding(Symbol sym) { - this.sym = sym; - } + public LocalBinding(Symbol sym){ + this.sym = sym; + } - public String getName() { - return munge(sym.name) + (isParam ? "" : ("__" + id)); - } + public String getName(){ + return munge(sym.name) + (isParam ? "" : ("__" + id)); + } - public String toString() { - return getName(); - } + public String toString(){ + return getName(); + } - boolean needsBox() { - return (isClosed && isAssigned) - || - letfn != null && isClosed && valueTaken; - } + boolean needsBox(){ + return (isClosed && isAssigned) + || + letfn != null && isClosed && valueTaken; + } - boolean bindsToStaticFn() { - return letfn != null && letfn.willBeStaticMethod(); - } + boolean bindsToStaticFn(){ + return letfn != null && letfn.willBeStaticMethod(); + } - String typeDeclaration() { - if (needsBox()) - return "clojure.lang.Box"; - return "Object"; - } + String typeDeclaration(){ + if(needsBox()) + return "clojure.lang.Box"; + return "Object"; + } - String getExpr() { - if (needsBox()) - return getName() + ".val"; - return getName(); - } + String getExpr(){ + if(needsBox()) + return getName() + ".val"; + return getName(); + } - void emitDeclaration(String init) throws Exception { - format("~A ~A = ", typeDeclaration(), getName()); - if (needsBox()) - format("new clojure.lang.Box(~A);~%", init); - else - format("~A;~%", init); - } + void emitDeclaration(String init) throws Exception{ + format("~A ~A = ", typeDeclaration(), getName()); + if(needsBox()) + format("new clojure.lang.Box(~A);~%", init); + else + format("~A;~%", init); + } } -static class LocalBindingExpr extends AnExpr { - final LocalBinding b; - final String typeHint; +static class LocalBindingExpr extends AnExpr{ + final LocalBinding b; + final String typeHint; - public LocalBindingExpr(LocalBinding b, String typeHint) { - this.b = b; - this.typeHint = typeHint; - } + public LocalBindingExpr(LocalBinding b, String typeHint){ + this.b = b; + this.typeHint = typeHint; + } - public void emitStatement() throws Exception { - //nop - } + public void emitStatement() throws Exception{ + //nop + } - public void emitExpression() throws Exception { - format("~A", b.getExpr()); - } + public void emitExpression() throws Exception{ + format("~A", b.getExpr()); + } - public Class getHostType() throws Exception { - String th = typeHint; - if (th == null) - th = b.typeHint; - if (th == null) - return null; - return getTypeNamed(resolveHostClassname(th)); - } + public Class getHostType() throws Exception{ + String th = typeHint; + if(th == null) + th = b.typeHint; + if(th == null) + return null; + return getTypeNamed(resolveHostClassname(th)); + } } -static class VarExpr extends AnExpr { - final Var var; - final String typeHint; +static class VarExpr extends AnExpr{ + final Var var; + final String typeHint; - public VarExpr(Var var, String typeHint) { - this.var = var; - this.typeHint = typeHint; - } + public VarExpr(Var var, String typeHint){ + this.var = var; + this.typeHint = typeHint; + } - public String getName() { - return munge(var.toString()); - } + public String getName(){ + return munge(var.toString()); + } - public void emitExpression() throws Exception { - format("~A.getValue()", getName()); - } + public void emitExpression() throws Exception{ + format("~A.getValue()", getName()); + } - public Class getHostType() throws Exception { - if (typeHint == null) - return null; - return getTypeNamed(resolveHostClassname(typeHint)); - } + public Class getHostType() throws Exception{ + if(typeHint == null) + return null; + return getTypeNamed(resolveHostClassname(typeHint)); + } } -static class DefExpr extends AnExpr { - final VarExpr var; - final Expr init; +static class DefExpr extends AnExpr{ + final VarExpr var; + final Expr init; - public DefExpr(VarExpr var, Expr init) { - this.var = var; - this.init = init; - } + public DefExpr(VarExpr var, Expr init){ + this.var = var; + this.init = init; + } - public void emitExpression() throws Exception { - format("~A.bind(~A)", var.getName(), init.emitExpressionString()); - } + public void emitExpression() throws Exception{ + format("~A.bind(~A)", var.getName(), init.emitExpressionString()); + } } -public static void main(String[] args) throws Exception { - if (!(args.length >= 3)) - System.err.println("Usage: clojure.lang.Compiler package class file1 [file2 ...]"); - String pkg = args[0]; - String classname = args[1]; - LineNumberingPushbackReader[] rs = new LineNumberingPushbackReader[args.length - 2]; - String ret; - try - { - for (int i = 0; i < rs.length; i++) - { - rs[i] = new LineNumberingPushbackReader(new InputStreamReader(new FileInputStream(args[i + 2]))); - } - ret = compile(pkg, classname, rs); - System.out.print(ret); - } - finally - { - for (LineNumberingPushbackReader r : rs) - { - if (r != null) - r.close(); - } - } +public static void main(String[] args) throws Exception{ + if(!(args.length >= 3)) + System.err.println("Usage: clojure.lang.Compiler package class file1 [file2 ...]"); + String pkg = args[0]; + String classname = args[1]; + LineNumberingPushbackReader[] rs = new LineNumberingPushbackReader[args.length - 2]; + String ret; + try + { + for(int i = 0; i < rs.length; i++) + { + rs[i] = new LineNumberingPushbackReader(new InputStreamReader(new FileInputStream(args[i + 2]))); + } + ret = compile(pkg, classname, rs); + System.out.print(ret); + } + finally + { + for(LineNumberingPushbackReader r : rs) + { + if(r != null) + r.close(); + } + } } } diff --git a/src/jvm/clojure/lang/Iter.java b/src/jvm/clojure/lang/Iter.java index 7f0a76d9..5433382e 100644 --- a/src/jvm/clojure/lang/Iter.java +++ b/src/jvm/clojure/lang/Iter.java @@ -18,20 +18,22 @@ package clojure.lang; * <pre> * for(Iter i = getAnIter();i!=null;i = i.iterate()) * { - * //use i.get() + * //use i.valAt() * } * </pre> */ public interface Iter{ /** * Multiple calls to get() are allowed prior to calling iterate() - * @return the currently referenced item/element/value + * + * @return the currently referenced item/element/value */ public Object get(); /** * This may destroy or otherwise invalidate the object it is called upon * so always capture and use the return value (even though sometimes you may find it is the same object) + * * @return The next iter to use, or null if at end of sequence */ public Iter iterate(); diff --git a/src/jvm/clojure/lang/Keyword.java b/src/jvm/clojure/lang/Keyword.java index c043b394..f9e4a7d5 100644 --- a/src/jvm/clojure/lang/Keyword.java +++ b/src/jvm/clojure/lang/Keyword.java @@ -13,7 +13,7 @@ package clojure.lang; -public class Keyword implements IFn { +public class Keyword implements IFn{ /** @@ -27,11 +27,11 @@ final int hash; public Keyword(Symbol sym){ this.sym = sym; - this.hash = RT.hashCombine(":".hashCode(), sym.hashCode()); + this.hash = RT.hashCombine(":".hashCode(), sym.hashCode()); } -public Keyword(String name,String ns){ - this(new Symbol(name,ns)); +public Keyword(String name, String ns){ + this(new Symbol(name, ns)); } public boolean equals(Object o){ @@ -55,8 +55,8 @@ public String toString(){ return ":" + sym; } -public Object invoke() throws Exception { - return AFn.throwArity(); +public Object invoke() throws Exception{ + return AFn.throwArity(); } /** @@ -66,121 +66,121 @@ public Object invoke() throws Exception { * @return the value at the key or nil if not found * @throws Exception */ -public Object invoke(Object obj) throws Exception { - if (obj == null) - return null; - return ((IPersistentMap) obj).get(this); +public Object invoke(Object obj) throws Exception{ + if(obj == null) + return null; + return ((IPersistentMap) obj).valAt(this); } -public Object invoke(Object obj, Object val) throws Exception { +public Object invoke(Object obj, Object val) throws Exception{ return AFn.throwArity(); } -public Object invoke(Object arg1, Object arg2, Object arg3) throws Exception { - return AFn.throwArity(); +public Object invoke(Object arg1, Object arg2, Object arg3) throws Exception{ + return AFn.throwArity(); } -public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4) throws Exception { - return AFn.throwArity(); +public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4) throws Exception{ + return AFn.throwArity(); } -public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) throws Exception { - return AFn.throwArity(); +public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) throws Exception{ + return AFn.throwArity(); } -public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6) throws Exception { - return AFn.throwArity(); +public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7) - throws Exception { - return AFn.throwArity(); + throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8) throws Exception { - return AFn.throwArity(); + Object arg8) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8, Object arg9) throws Exception { - return AFn.throwArity(); + Object arg8, Object arg9) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8, Object arg9, Object arg10) throws Exception { - return AFn.throwArity(); + Object arg8, Object arg9, Object arg10) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8, Object arg9, Object arg10, Object arg11) throws Exception { - return AFn.throwArity(); + Object arg8, Object arg9, Object arg10, Object arg11) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8, Object arg9, Object arg10, Object arg11, Object arg12) throws Exception { - return AFn.throwArity(); + Object arg8, Object arg9, Object arg10, Object arg11, Object arg12) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13) - throws Exception { - return AFn.throwArity(); + throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14) - throws Exception { - return AFn.throwArity(); + throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15) throws Exception { - return AFn.throwArity(); + Object arg15) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15, Object arg16) throws Exception { - return AFn.throwArity(); + Object arg15, Object arg16) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15, Object arg16, Object arg17) throws Exception { - return AFn.throwArity(); + Object arg15, Object arg16, Object arg17) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15, Object arg16, Object arg17, Object arg18) throws Exception { - return AFn.throwArity(); + Object arg15, Object arg16, Object arg17, Object arg18) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15, Object arg16, Object arg17, Object arg18, Object arg19) throws Exception { - return AFn.throwArity(); + Object arg15, Object arg16, Object arg17, Object arg18, Object arg19) throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20) - throws Exception { - return AFn.throwArity(); + throws Exception{ + return AFn.throwArity(); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object... args) - throws Exception { - return AFn.throwArity(); + throws Exception{ + return AFn.throwArity(); } -public Object applyTo(ISeq arglist) throws Exception { - return AFn.applyToHelper(this, arglist); +public Object applyTo(ISeq arglist) throws Exception{ + return AFn.applyToHelper(this, arglist); } } diff --git a/src/jvm/clojure/lang/MapEntry.java b/src/jvm/clojure/lang/MapEntry.java index f4dace75..6edaeafd 100644 --- a/src/jvm/clojure/lang/MapEntry.java +++ b/src/jvm/clojure/lang/MapEntry.java @@ -16,104 +16,105 @@ public class MapEntry extends APersistentMap implements IMapEntry{ final Object _key;
final Object _val;
-public MapEntry(Object key, Object val) {
- this._key = key;
- this._val = val;
+public MapEntry(Object key, Object val){
+ this._key = key;
+ this._val = val;
}
-public Object key() {
- return _key;
+public Object key(){
+ return _key;
}
-public Object val() {
- return _val;
+public Object val(){
+ return _val;
}
-public boolean contains(Object key) {
- return RT.equal(_key, key);
+public boolean contains(Object key){
+ return RT.equal(_key, key);
}
-public IMapEntry find(Object key) {
- return RT.equal(_key, key)?this:null;
+public IMapEntry entryAt(Object key){
+ return RT.equal(_key, key) ? this : null;
}
-public IPersistentMap assoc(Object key, Object val) {
- if(RT.equal(_key, key))
- {
- if(_val == val)
- return this;
- return (MapEntry) new MapEntry(key, val).withMeta(_meta);
- }
- return (IPersistentMap) new PersistentArrayMap(_key,_val,key,val).withMeta(_meta);
+public IPersistentMap assoc(Object key, Object val){
+ if(RT.equal(_key, key))
+ {
+ if(_val == val)
+ return this;
+ return (MapEntry) new MapEntry(key, val).withMeta(_meta);
+ }
+ return (IPersistentMap) new PersistentArrayMap(_key, _val, key, val).withMeta(_meta);
}
-public Object get(Object key) {
- return RT.equal(_key, key)?_val:null;
+public Object valAt(Object key){
+ return RT.equal(_key, key) ? _val : null;
}
-public IPersistentMap assocEx(Object key, Object val) throws Exception {
- if(RT.equal(_key, key))
- throw new Exception("Key already present");
- return assoc(key, val);
+public IPersistentMap assocEx(Object key, Object val) throws Exception{
+ if(RT.equal(_key, key))
+ throw new Exception("Key already present");
+ return assoc(key, val);
}
-public IPersistentMap without(Object key) {
- if(RT.equal(_key, key))
- return (IPersistentMap) PersistentArrayMap.EMPTY.withMeta(_meta);
- return this;
+public IPersistentMap without(Object key){
+ if(RT.equal(_key, key))
+ return (IPersistentMap) PersistentArrayMap.EMPTY.withMeta(_meta);
+ return this;
}
-public int count() {
- return 1;
+public int count(){
+ return 1;
}
-public Iterator iterator() {
- return new Iter(this);
+public Iterator iterator(){
+ return new Iter(this);
}
static class Iter implements Iterator{
- MapEntry e;
+ MapEntry e;
- public Iter(MapEntry e) {
- this.e = e;
- }
+ public Iter(MapEntry e){
+ this.e = e;
+ }
- public boolean hasNext() {
- return e != null;
- }
+ public boolean hasNext(){
+ return e != null;
+ }
- public Object next() {
- Object ret = e;
- e = null;
- return ret;
- }
+ public Object next(){
+ Object ret = e;
+ e = null;
+ return ret;
+ }
- public void remove() {
- throw new UnsupportedOperationException();
- }
+ public void remove(){
+ throw new UnsupportedOperationException();
+ }
}
-public ISeq seq() {
- return new Seq(this);
+public ISeq seq(){
+ return new Seq(this);
}
static class Seq extends ASeq{
- final MapEntry e;
-
- public Seq(MapEntry e) {
- this.e = e;
- }
-
- public Object first() {
- return e;
- }
-
- public ISeq rest() {
- return null;
- }
- public int count() {
- return 1;
- }
+ final MapEntry e;
+
+ public Seq(MapEntry e){
+ this.e = e;
+ }
+
+ public Object first(){
+ return e;
+ }
+
+ public ISeq rest(){
+ return null;
+ }
+
+ public int count(){
+ return 1;
+ }
}
}
diff --git a/src/jvm/clojure/lang/Module.java b/src/jvm/clojure/lang/Module.java index c33e57a5..85d7a1cd 100644 --- a/src/jvm/clojure/lang/Module.java +++ b/src/jvm/clojure/lang/Module.java @@ -12,15 +12,14 @@ package clojure.lang; -import java.util.HashMap; -import java.util.IdentityHashMap; +import java.util.concurrent.ConcurrentHashMap; public class Module{ /** * String->Module */ -static final public TRef<IPersistentMap> table = new TRef(PersistentHashMap.EMPTY); +static final public ConcurrentHashMap<String, Module> table = new ConcurrentHashMap(); /** * Symbol->Var @@ -32,32 +31,34 @@ Module(String name){ this.name = name; } -static public Module find(String name) throws Exception{ - return (Module) table.get().get(name); +static public Module findModule(String name) throws Exception{ + return table.get(name); } -static public Module findOrCreate(String name) throws Exception{ - //must be called in transaction - Module ns = find(name); - if(ns == null) - table.set(table.get().assoc(name, ns = new Module(name))); - return ns; +static public Module findOrCreateModule(String name) throws Exception{ + Module module = findModule(name); + if(module == null) + module = table.putIfAbsent(name, new Module(name)); + return module; } -static public Var intern(String ns, String name) throws Exception{ - return findOrCreate(ns).intern(new Symbol(name)); +public TRef findRef(String name) throws Exception{ + return (TRef) vars.val().valAt(name); } -public Var find(Symbol sym) throws Exception{ - return (Var) vars.get().get(sym); +public static TRef intern(String moduleName, String name) throws Exception{ + Module module = findModule(name); + if(module == null) + throw new Exception(String.format("Module %s not found", moduleName)); + return module.intern(name); } -public Var intern(Symbol sym) throws Exception{ +public TRef intern(String name) throws Exception{ //must be called in transaction - IPersistentMap varmap = vars.get(); - Var var = (Var) varmap.get(sym); + IPersistentMap varmap = vars.val(); + TRef var = (TRef) varmap.valAt(name); if(var == null) - vars.set(varmap.assoc(sym, var = new Var(sym, this))); + vars.set(varmap.assoc(name, var = new TRef())); return var; } diff --git a/src/jvm/clojure/lang/PersistentArrayMap.java b/src/jvm/clojure/lang/PersistentArrayMap.java index acfacab5..a7308248 100644 --- a/src/jvm/clojure/lang/PersistentArrayMap.java +++ b/src/jvm/clojure/lang/PersistentArrayMap.java @@ -14,16 +14,16 @@ import java.util.Iterator; /**
* Simple implementation of persistent map on an array
-
+ * <p/>
* Note that instances of this class are constant values
* i.e. add/remove etc return new values
- *
+ * <p/>
* Copies array on every change, so only appropriate for _very_small_ maps
- *
- * null keys and values are ok, but you won't be able to distinguish a null value via get - use contains/find
+ * <p/>
+ * null keys and values are ok, but you won't be able to distinguish a null value via valAt - use contains/entryAt
*/
-public class PersistentArrayMap extends APersistentMap {
+public class PersistentArrayMap extends APersistentMap{
final Object[] array;
static final int HASHTABLE_THRESHOLD = 42;
@@ -31,219 +31,221 @@ static final int HASHTABLE_THRESHOLD = 42; public static PersistentArrayMap EMPTY = new PersistentArrayMap();
protected PersistentArrayMap(){
- this.array = new Object[]{};
+ this.array = new Object[]{};
}
PersistentArrayMap create(Object... init){
- PersistentArrayMap ret = new PersistentArrayMap(init);
- ret._meta = _meta;
- return ret;
+ PersistentArrayMap ret = new PersistentArrayMap(init);
+ ret._meta = _meta;
+ return ret;
}
IPersistentMap createHT(Object[] init){
- PersistentHashtableMap ret = new PersistentHashtableMap(init);
- ret._meta = _meta;
- return ret;
+ PersistentHashtableMap ret = new PersistentHashtableMap(init);
+ ret._meta = _meta;
+ return ret;
}
/**
* This ctor captures/aliases the passed array, so do not modify later
+ *
* @param init {key1,val1,key2,val2,...}
*/
public PersistentArrayMap(Object... init){
- this.array = init;
+ this.array = init;
}
-public int count() {
- return array.length/2;
+public int count(){
+ return array.length / 2;
}
public boolean contains(Object key){
return indexOf(key) >= 0;
}
-public IMapEntry find(Object key) {
- int i = indexOf(key);
- if(i >= 0)
- return new Iter(array,i);
- return null;
-}
-
-public IPersistentMap assocEx(Object key, Object val) throws Exception {
- int i = indexOf(key);
- Object[] newArray;
- if(i >= 0)
- {
- throw new Exception("Key already present");
- }
- else //didn't have key, grow
- {
- if(array.length > HASHTABLE_THRESHOLD)
- return createHT(array).assocEx(key, val);
- newArray = new Object[array.length + 2];
- if(array.length > 0)
- System.arraycopy(array,0,newArray,2,array.length);
- newArray[0] = key;
- newArray[1] = val;
- }
- return create(newArray);
-}
-
-public IPersistentMap assoc(Object key, Object val) {
- int i = indexOf(key);
- Object[] newArray;
- if(i >= 0) //already have key, same-sized replacement
- {
- if(array[i+1] == val) //no change, no op
- return this;
- newArray = array.clone();
- newArray[i+1] = val;
- }
- else //didn't have key, grow
- {
- if(array.length > HASHTABLE_THRESHOLD)
- return createHT(array).assoc(key, val);
- newArray = new Object[array.length + 2];
- if(array.length > 0)
- System.arraycopy(array,0,newArray,2,array.length);
- newArray[0] = key;
- newArray[1] = val;
- }
- return create(newArray);
-}
-
-public IPersistentMap without(Object key) {
- int i = indexOf(key);
- if(i >= 0) //have key, will remove
- {
- int newlen = array.length - 2;
- if(newlen == 0)
- return empty();
- Object[] newArray = new Object[newlen];
- for(int s=0,d=0;s<array.length;s += 2)
- {
- if(!equalKey(array[s],key)) //skip removal key
- {
- newArray[d] = array[s];
- newArray[d+1] = array[s+1];
- d += 2;
- }
- }
- return create(newArray);
- }
- //don't have key, no op
- return this;
-}
-
-IPersistentMap empty() {
- if(_meta == null)
- return EMPTY;
- PersistentArrayMap ret = new PersistentArrayMap();
- ret._meta = _meta;
- return ret;
-}
-
-final public Object get(Object key) {
- int i = indexOf(key);
- if(i >= 0)
- return array[i + 1];
- return null;
-}
-
-public int capacity() {
- return count();
+public IMapEntry entryAt(Object key){
+ int i = indexOf(key);
+ if(i >= 0)
+ return new Iter(array, i);
+ return null;
+}
+
+public IPersistentMap assocEx(Object key, Object val) throws Exception{
+ int i = indexOf(key);
+ Object[] newArray;
+ if(i >= 0)
+ {
+ throw new Exception("Key already present");
+ }
+ else //didn't have key, grow
+ {
+ if(array.length > HASHTABLE_THRESHOLD)
+ return createHT(array).assocEx(key, val);
+ newArray = new Object[array.length + 2];
+ if(array.length > 0)
+ System.arraycopy(array, 0, newArray, 2, array.length);
+ newArray[0] = key;
+ newArray[1] = val;
+ }
+ return create(newArray);
+}
+
+public IPersistentMap assoc(Object key, Object val){
+ int i = indexOf(key);
+ Object[] newArray;
+ if(i >= 0) //already have key, same-sized replacement
+ {
+ if(array[i + 1] == val) //no change, no op
+ return this;
+ newArray = array.clone();
+ newArray[i + 1] = val;
+ }
+ else //didn't have key, grow
+ {
+ if(array.length > HASHTABLE_THRESHOLD)
+ return createHT(array).assoc(key, val);
+ newArray = new Object[array.length + 2];
+ if(array.length > 0)
+ System.arraycopy(array, 0, newArray, 2, array.length);
+ newArray[0] = key;
+ newArray[1] = val;
+ }
+ return create(newArray);
+}
+
+public IPersistentMap without(Object key){
+ int i = indexOf(key);
+ if(i >= 0) //have key, will remove
+ {
+ int newlen = array.length - 2;
+ if(newlen == 0)
+ return empty();
+ Object[] newArray = new Object[newlen];
+ for(int s = 0, d = 0; s < array.length; s += 2)
+ {
+ if(!equalKey(array[s], key)) //skip removal key
+ {
+ newArray[d] = array[s];
+ newArray[d + 1] = array[s + 1];
+ d += 2;
+ }
+ }
+ return create(newArray);
+ }
+ //don't have key, no op
+ return this;
+}
+
+IPersistentMap empty(){
+ if(_meta == null)
+ return EMPTY;
+ PersistentArrayMap ret = new PersistentArrayMap();
+ ret._meta = _meta;
+ return ret;
+}
+
+final public Object valAt(Object key){
+ int i = indexOf(key);
+ if(i >= 0)
+ return array[i + 1];
+ return null;
+}
+
+public int capacity(){
+ return count();
}
private int indexOf(Object key){
- for(int i=0;i<array.length;i+=2)
- {
- if(equalKey(array[i],key))
- return i;
- }
- return -1;
+ for(int i = 0; i < array.length; i += 2)
+ {
+ if(equalKey(array[i], key))
+ return i;
+ }
+ return -1;
}
-boolean equalKey(Object k1,Object k2){
- if(k1 == null)
- return k2 == null;
- return k1.equals(k2);
+boolean equalKey(Object k1, Object k2){
+ if(k1 == null)
+ return k2 == null;
+ return k1.equals(k2);
}
-public Iterator iterator() {
- return new Iter(array);
+public Iterator iterator(){
+ return new Iter(array);
}
-public ISeq seq() {
- if(array.length > 0)
- return new Seq(array,0);
- return null;
+public ISeq seq(){
+ if(array.length > 0)
+ return new Seq(array, 0);
+ return null;
}
static class Seq extends ASeq implements IMapEntry{
- final Object[] array;
- final int i;
-
- Seq(Object[] array, int i){
- this.array = array;
- this.i = i;
- }
-
- public Object key() {
- return array[i];
- }
-
- public Object val() {
- return array[i+1];
- }
-
- public Object first() {
- return this;
- }
-
- public ISeq rest() {
- if(i+2 < array.length)
- return new Seq(array, i + 2);
- return null;
- }
- public int count() {
- return (array.length - i)/2;
- }
-}
-
-static class Iter implements Iterator,IMapEntry{
- Object[] array;
- int i;
-
- //for iterator
- Iter(Object[] array){
- this(array,-2);
- }
-
- //for find
- Iter(Object[] array, int i){
- this.array = array;
- this.i = i;
- }
-
- public boolean hasNext() {
- return i < array.length - 2;
- }
-
- public Object next() {
- i+=2;
- return this;
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- public Object key() {
- return array[i];
- }
-
- public Object val() {
- return array[i+1];
- }
+ final Object[] array;
+ final int i;
+
+ Seq(Object[] array, int i){
+ this.array = array;
+ this.i = i;
+ }
+
+ public Object key(){
+ return array[i];
+ }
+
+ public Object val(){
+ return array[i + 1];
+ }
+
+ public Object first(){
+ return this;
+ }
+
+ public ISeq rest(){
+ if(i + 2 < array.length)
+ return new Seq(array, i + 2);
+ return null;
+ }
+
+ public int count(){
+ return (array.length - i) / 2;
+ }
+}
+
+static class Iter implements Iterator, IMapEntry{
+ Object[] array;
+ int i;
+
+ //for iterator
+ Iter(Object[] array){
+ this(array, -2);
+ }
+
+ //for entryAt
+ Iter(Object[] array, int i){
+ this.array = array;
+ this.i = i;
+ }
+
+ public boolean hasNext(){
+ return i < array.length - 2;
+ }
+
+ public Object next(){
+ i += 2;
+ return this;
+ }
+
+ public void remove(){
+ throw new UnsupportedOperationException();
+ }
+
+ public Object key(){
+ return array[i];
+ }
+
+ public Object val(){
+ return array[i + 1];
+ }
}
}
diff --git a/src/jvm/clojure/lang/PersistentHashMap.java b/src/jvm/clojure/lang/PersistentHashMap.java index 1b6f23f9..027eee5d 100644 --- a/src/jvm/clojure/lang/PersistentHashMap.java +++ b/src/jvm/clojure/lang/PersistentHashMap.java @@ -41,10 +41,10 @@ PersistentHashMap(int count, INode root){ } public boolean contains(Object key){ - return find(key) != null; + return entryAt(key) != null; } -public IMapEntry find(Object key){ +public IMapEntry entryAt(Object key){ return root.find(RT.hash(key), key); } @@ -58,8 +58,8 @@ public IPersistentMap assoc(Object key, Object val){ return ret; } -public Object get(Object key){ - IMapEntry e = find(key); +public Object valAt(Object key){ + IMapEntry e = entryAt(key); if(e != null) return e.val(); return null; diff --git a/src/jvm/clojure/lang/PersistentHashtableMap.java b/src/jvm/clojure/lang/PersistentHashtableMap.java index 8c28c09a..5f9c6a51 100644 --- a/src/jvm/clojure/lang/PersistentHashtableMap.java +++ b/src/jvm/clojure/lang/PersistentHashtableMap.java @@ -13,7 +13,7 @@ package clojure.lang; import java.util.Iterator;
import java.math.BigInteger;
-public class PersistentHashtableMap extends APersistentMap {
+public class PersistentHashtableMap extends APersistentMap{
static final float FILL_FACTOR = 0.75f;
@@ -21,266 +21,267 @@ final PersistentArray array; final int _count;
final int growAtCount;
-public PersistentHashtableMap(int initialCapacity) {
- array = new PersistentArray(calcPrimeCapacity(initialCapacity));
- _count = 0;
- this.growAtCount = (int) (this.array.length()*FILL_FACTOR);
+public PersistentHashtableMap(int initialCapacity){
+ array = new PersistentArray(calcPrimeCapacity(initialCapacity));
+ _count = 0;
+ this.growAtCount = (int) (this.array.length() * FILL_FACTOR);
}
/**
* @param init {key1,val1,key2,val2,...}
*/
public PersistentHashtableMap(Object[] init){
- //start halfway to a rehash
- PersistentArray narray = new PersistentArray(calcPrimeCapacity(init.length));
- for(int i=0;i<init.length;i+=2)
- {
- narray = doPut(bucketFor(init[i],narray),init[i], init[i + 1],narray);
- }
- this.array = narray;
- this._count = init.length/2; //hmmm... presumes no dupe keys in init
- this.growAtCount = (int) (this.array.length()*FILL_FACTOR);
+ //start halfway to a rehash
+ PersistentArray narray = new PersistentArray(calcPrimeCapacity(init.length));
+ for(int i = 0; i < init.length; i += 2)
+ {
+ narray = doPut(bucketFor(init[i], narray), init[i], init[i + 1], narray);
+ }
+ this.array = narray;
+ this._count = init.length / 2; //hmmm... presumes no dupe keys in init
+ this.growAtCount = (int) (this.array.length() * FILL_FACTOR);
}
-PersistentHashtableMap(int count,PersistentArray array) {
- this._count = count;
- this.array = array;
- this.growAtCount = (int) (this.array.length()*FILL_FACTOR);
+PersistentHashtableMap(int count, PersistentArray array){
+ this._count = count;
+ this.array = array;
+ this.growAtCount = (int) (this.array.length() * FILL_FACTOR);
}
-PersistentHashtableMap(int count,PersistentArray array,int growAt) {
- this._count = count;
- this.array = array;
- this.growAtCount = growAt;
+PersistentHashtableMap(int count, PersistentArray array, int growAt){
+ this._count = count;
+ this.array = array;
+ this.growAtCount = growAt;
}
-int calcPrimeCapacity(int capacity) {
- return BigInteger.valueOf((long) (capacity/FILL_FACTOR)).nextProbablePrime().intValue();
+int calcPrimeCapacity(int capacity){
+ return BigInteger.valueOf((long) (capacity / FILL_FACTOR)).nextProbablePrime().intValue();
}
-public int count() {
- return _count;
+public int count(){
+ return _count;
}
-public boolean contains(Object key) {
- IPersistentMap entries = entriesFor(key);
- return entries != null && entries.contains(key);
+public boolean contains(Object key){
+ IPersistentMap entries = entriesFor(key);
+ return entries != null && entries.contains(key);
}
-public IMapEntry find(Object key) {
- IPersistentMap entries = entriesFor(key);
- if(entries != null)
- return entries.find(key);
- return null;
+public IMapEntry entryAt(Object key){
+ IPersistentMap entries = entriesFor(key);
+ if(entries != null)
+ return entries.entryAt(key);
+ return null;
}
-public IPersistentMap assocEx(Object key, Object val) throws Exception {
- if(_count > growAtCount)
- return grow().assocEx(key, val);
- int i = bucketFor(key,array);
- int incr = 1;
- PersistentArray newArray = doAdd(i, key, val, array);
- return create(_count + incr, newArray, growAtCount);
+public IPersistentMap assocEx(Object key, Object val) throws Exception{
+ if(_count > growAtCount)
+ return grow().assocEx(key, val);
+ int i = bucketFor(key, array);
+ int incr = 1;
+ PersistentArray newArray = doAdd(i, key, val, array);
+ return create(_count + incr, newArray, growAtCount);
}
-public IPersistentMap assoc(Object key, Object val) {
- if(_count > growAtCount)
- return grow().assoc(key, val);
- int i = bucketFor(key,array);
- int incr = 1;
- PersistentArray newArray = doPut(i, key, val, array);
- if(newArray == array)
- return this;
- if(array.nth(i) != null && ((IPersistentMap)newArray.nth(i)).count() == ((IPersistentMap)array.nth(i)).count()) //key already there, no growth
- incr = 0;
- return create(_count + incr, newArray, growAtCount);
+public IPersistentMap assoc(Object key, Object val){
+ if(_count > growAtCount)
+ return grow().assoc(key, val);
+ int i = bucketFor(key, array);
+ int incr = 1;
+ PersistentArray newArray = doPut(i, key, val, array);
+ if(newArray == array)
+ return this;
+ if(array.nth(i) != null && ((IPersistentMap) newArray.nth(i)).count() ==
+ ((IPersistentMap) array.nth(i)).count()) //key already there, no growth
+ incr = 0;
+ return create(_count + incr, newArray, growAtCount);
}
-PersistentArray doPut(int i,Object key,Object val,PersistentArray array){
- IPersistentMap entries = (IPersistentMap) array.nth(i);
- IPersistentMap newEntries;
- if (entries != null)
- {
- newEntries = entries.assoc(key, val);
- if(newEntries == entries) //already there with same value, no op
- return array;
- }
- else
- newEntries = createEntryMap(key, val);
-
- return array.assocN(i, newEntries);
+PersistentArray doPut(int i, Object key, Object val, PersistentArray array){
+ IPersistentMap entries = (IPersistentMap) array.nth(i);
+ IPersistentMap newEntries;
+ if(entries != null)
+ {
+ newEntries = entries.assoc(key, val);
+ if(newEntries == entries) //already there with same value, no op
+ return array;
+ }
+ else
+ newEntries = createEntryMap(key, val);
+
+ return array.assocN(i, newEntries);
}
-PersistentArray doAdd(int i,Object key,Object val,PersistentArray array) throws Exception{
- IPersistentMap entries = (IPersistentMap) array.nth(i);
- IPersistentMap newEntries;
- if (entries != null)
- {
- newEntries = entries.assocEx(key, val);
- }
- else
- newEntries = createEntryMap(key, val);
-
- return array.assocN(i, newEntries);
+PersistentArray doAdd(int i, Object key, Object val, PersistentArray array) throws Exception{
+ IPersistentMap entries = (IPersistentMap) array.nth(i);
+ IPersistentMap newEntries;
+ if(entries != null)
+ {
+ newEntries = entries.assocEx(key, val);
+ }
+ else
+ newEntries = createEntryMap(key, val);
+
+ return array.assocN(i, newEntries);
}
-public IPersistentMap without(Object key) {
- int i = bucketFor(key,array);
- IPersistentMap entries = (IPersistentMap) array.nth(i);
- if (entries != null)
- {
- IPersistentMap newEntries = entries.without(key);
- if (newEntries != entries)
- return create(_count - 1, array.assocN(i, newEntries));
- }
- //not there, no op
- return this;
+public IPersistentMap without(Object key){
+ int i = bucketFor(key, array);
+ IPersistentMap entries = (IPersistentMap) array.nth(i);
+ if(entries != null)
+ {
+ IPersistentMap newEntries = entries.without(key);
+ if(newEntries != entries)
+ return create(_count - 1, array.assocN(i, newEntries));
+ }
+ //not there, no op
+ return this;
}
-public Object get(Object key) {
- IPersistentMap entries = entriesFor(key);
- if(entries != null)
- return entries.get(key);
- return null;
+public Object valAt(Object key){
+ IPersistentMap entries = entriesFor(key);
+ if(entries != null)
+ return entries.valAt(key);
+ return null;
}
-public int capacity() {
- return array.length();
+public int capacity(){
+ return array.length();
}
IPersistentMap grow(){
- PersistentArray newArray = new PersistentArray(calcPrimeCapacity(_count * 2));
- for (Object o : this)
- {
- IMapEntry e = (IMapEntry) o;
- newArray = doPut(bucketFor(e.key(),newArray),e.key(), e.val(),newArray);
- }
- return create(_count,newArray);
+ PersistentArray newArray = new PersistentArray(calcPrimeCapacity(_count * 2));
+ for(Object o : this)
+ {
+ IMapEntry e = (IMapEntry) o;
+ newArray = doPut(bucketFor(e.key(), newArray), e.key(), e.val(), newArray);
+ }
+ return create(_count, newArray);
}
-public Iterator iterator() {
- return new Iter(array);
+public Iterator iterator(){
+ return new Iter(array);
}
-public ISeq seq() {
- if(count() == 0)
- return null;
- return Seq.create(array,count());
+public ISeq seq(){
+ if(count() == 0)
+ return null;
+ return Seq.create(array, count());
}
static class Seq extends ASeq{
- final PersistentArray buckets;
- final int b;
- final ISeq e;
- final int cnt;
-
-
- static public Seq create(PersistentArray buckets, int cnt) {
- return next(buckets, -1, null,cnt);
- }
-
- static Seq next(PersistentArray buckets, int b, ISeq e,int cnt) {
- if(e != null && e.rest() != null)
- return new Seq(buckets,b,e.rest(),cnt);
- for(b = b+1;b<buckets.length();b++)
- {
- IPersistentCollection a = (IPersistentCollection) buckets.nth(b);
- if(a != null && a.seq() != null)
- return new Seq(buckets,b,a.seq(),cnt);
- }
- return null;
- }
-
- Seq(PersistentArray buckets, int b, ISeq e, int cnt) {
- this.buckets = buckets;
- this.b = b;
- this.e = e;
- this.cnt = cnt;
- }
-
- public Object first() {
- return e.first();
- }
-
- public ISeq rest() {
- return next(buckets,b,e,cnt-1);
- }
-
- public int count() {
- return cnt;
- }
+ final PersistentArray buckets;
+ final int b;
+ final ISeq e;
+ final int cnt;
+
+
+ static public Seq create(PersistentArray buckets, int cnt){
+ return next(buckets, -1, null, cnt);
+ }
+
+ static Seq next(PersistentArray buckets, int b, ISeq e, int cnt){
+ if(e != null && e.rest() != null)
+ return new Seq(buckets, b, e.rest(), cnt);
+ for(b = b + 1; b < buckets.length(); b++)
+ {
+ IPersistentCollection a = (IPersistentCollection) buckets.nth(b);
+ if(a != null && a.seq() != null)
+ return new Seq(buckets, b, a.seq(), cnt);
+ }
+ return null;
+ }
+
+ Seq(PersistentArray buckets, int b, ISeq e, int cnt){
+ this.buckets = buckets;
+ this.b = b;
+ this.e = e;
+ this.cnt = cnt;
+ }
+
+ public Object first(){
+ return e.first();
+ }
+
+ public ISeq rest(){
+ return next(buckets, b, e, cnt - 1);
+ }
+
+ public int count(){
+ return cnt;
+ }
}
static class Iter implements Iterator{
PersistentArray buckets;
int b;
- ISeq e;
+ ISeq e;
Iter(PersistentArray buckets){
- this.buckets = buckets;
- this.b = -1;
- nextBucket();
- }
-
- private void nextBucket() {
- e = null;
- for(b = b+1;b<buckets.length();b++)
- {
- IPersistentCollection a = (IPersistentCollection) buckets.nth(b);
- if(a != null && a.seq() != null)
- {
- e = a.seq();
- break;
- }
- }
- }
-
- public boolean hasNext() {
- return e != null;
- }
-
- public Object next() {
+ this.buckets = buckets;
+ this.b = -1;
+ nextBucket();
+ }
+
+ private void nextBucket(){
+ e = null;
+ for(b = b + 1; b < buckets.length(); b++)
+ {
+ IPersistentCollection a = (IPersistentCollection) buckets.nth(b);
+ if(a != null && a.seq() != null)
+ {
+ e = a.seq();
+ break;
+ }
+ }
+ }
+
+ public boolean hasNext(){
+ return e != null;
+ }
+
+ public Object next(){
ISeq ret = e;
- e = e.rest();
- if(e == null)
- nextBucket();
- return ret.first();
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
+ e = e.rest();
+ if(e == null)
+ nextBucket();
+ return ret.first();
+ }
+
+ public void remove(){
+ throw new UnsupportedOperationException();
+ }
}
final IPersistentMap entriesFor(Object key){
- return (IPersistentMap) array.nth(bucketFor(key,array));
+ return (IPersistentMap) array.nth(bucketFor(key, array));
}
-static int bucketFor(Object key, PersistentArray array) {
- return (RT.hash(key) & 0x7fffffff)%array.length();
+static int bucketFor(Object key, PersistentArray array){
+ return (RT.hash(key) & 0x7fffffff) % array.length();
}
-IPersistentMap create(int capacity) {
- PersistentHashtableMap ret = new PersistentHashtableMap(capacity);
- ret._meta = _meta;
- return ret;
+IPersistentMap create(int capacity){
+ PersistentHashtableMap ret = new PersistentHashtableMap(capacity);
+ ret._meta = _meta;
+ return ret;
}
-IPersistentMap create(int count,PersistentArray array) {
- PersistentHashtableMap ret = new PersistentHashtableMap(count, array);
- ret._meta = _meta;
- return ret;
+IPersistentMap create(int count, PersistentArray array){
+ PersistentHashtableMap ret = new PersistentHashtableMap(count, array);
+ ret._meta = _meta;
+ return ret;
}
IPersistentMap create(int i, PersistentArray newArray, int growAtCount){
- PersistentHashtableMap ret = new PersistentHashtableMap(i, newArray, growAtCount);
- ret._meta = _meta;
- return ret;
+ PersistentHashtableMap ret = new PersistentHashtableMap(i, newArray, growAtCount);
+ ret._meta = _meta;
+ return ret;
}
IPersistentMap createEntryMap(Object key, Object val){
- return new MapEntry(key,val);
+ return new MapEntry(key, val);
// return PersistentListMap.create(key,val);
// return new PersistentArrayMap(key,val);
}
diff --git a/src/jvm/clojure/lang/PersistentTreeMap.java b/src/jvm/clojure/lang/PersistentTreeMap.java index 6ad0c6ca..5544d69b 100644 --- a/src/jvm/clojure/lang/PersistentTreeMap.java +++ b/src/jvm/clojure/lang/PersistentTreeMap.java @@ -22,7 +22,7 @@ import java.util.*; * See Okasaki, Kahrs, Larsen et al */ -public class PersistentTreeMap extends APersistentMap { +public class PersistentTreeMap extends APersistentMap{ public final Comparator comp; public final Node tree; @@ -40,17 +40,17 @@ public PersistentTreeMap(Comparator comp){ public boolean contains(Object key){ - return find(key) != null; + return entryAt(key) != null; } -public PersistentTreeMap assocEx(Object key, Object val) throws Exception { - Box found = new Box(null); - Node t = add(tree, key, val, found); - if(t == null) //null == already contains key - { - throw new Exception("Key already present"); - } - return new PersistentTreeMap(comp, t.blacken(), _count + 1, _meta); +public PersistentTreeMap assocEx(Object key, Object val) throws Exception{ + Box found = new Box(null); + Node t = add(tree, key, val, found); + if(t == null) //null == already contains key + { + throw new Exception("Key already present"); + } + return new PersistentTreeMap(comp, t.blacken(), _count + 1, _meta); } public PersistentTreeMap assoc(Object key, Object val){ @@ -61,9 +61,9 @@ public PersistentTreeMap assoc(Object key, Object val){ Node foundNode = (Node) found.val; if(foundNode.val() == val) //note only get same collection on identity of val, not equals() return this; - return new PersistentTreeMap(comp, replace(tree, key, val), _count,_meta); + return new PersistentTreeMap(comp, replace(tree, key, val), _count, _meta); } - return new PersistentTreeMap(comp, t.blacken(), _count + 1,_meta); + return new PersistentTreeMap(comp, t.blacken(), _count + 1, _meta); } @@ -75,23 +75,23 @@ public PersistentTreeMap without(Object key){ if(found.val == null)//null == doesn't contain key return this; //empty - PersistentTreeMap ret = new PersistentTreeMap(comp); - ret._meta = _meta; - return ret; - } - return new PersistentTreeMap(comp, t.blacken(), _count - 1,_meta); + PersistentTreeMap ret = new PersistentTreeMap(comp); + ret._meta = _meta; + return ret; + } + return new PersistentTreeMap(comp, t.blacken(), _count - 1, _meta); } -public ISeq seq() { - if(_count > 0) - return Seq.create(tree, true,_count); - return null; +public ISeq seq(){ + if(_count > 0) + return Seq.create(tree, true, _count); + return null; } -public ISeq rseq() throws Exception { - if(_count > 0) - return Seq.create(tree, false,_count); - return null; +public ISeq rseq() throws Exception{ + if(_count > 0) + return Seq.create(tree, false, _count); + return null; } @@ -121,7 +121,7 @@ public Iterator vals(NodeIterator it){ public Object minKey(){ Node t = min(); - return t!=null?t.key:null; + return t != null ? t.key : null; } public Node min(){ @@ -136,7 +136,7 @@ public Node min(){ public Object maxKey(){ Node t = max(); - return t!=null?t.key:null; + return t != null ? t.key : null; } public Node max(){ @@ -159,32 +159,32 @@ int depth(Node t){ return 1 + Math.max(depth(t.left()), depth(t.right())); } -public Object get(Object key){ - Node n = find(key); +public Object valAt(Object key){ + Node n = entryAt(key); return (n != null) ? n.val() : null; } -public int capacity() { - return _count; +public int capacity(){ + return _count; } -public int count() { - return _count; +public int count(){ + return _count; } -public Node find(Object key){ - Node t = tree; - while(t != null) - { - int c = compare(key, t.key); - if(c == 0) - return t; - else if(c < 0) - t = t.left(); - else - t = t.right(); - } - return t; +public Node entryAt(Object key){ + Node t = tree; + while(t != null) + { + int c = compare(key, t.key); + if(c == 0) + return t; + else if(c < 0) + t = t.left(); + else + t = t.right(); + } + return t; } int compare(Object k1, Object k2){ @@ -335,7 +335,7 @@ PersistentTreeMap(Comparator comp, Node tree, int count, IPersistentMap meta){ this.comp = comp; this.tree = tree; this._count = count; - this._meta = meta; + this._meta = meta; } static Red red(Object key, Object val, Node left, Node right){ @@ -362,215 +362,222 @@ static Black black(Object key, Object val, Node left, Node right){ return new BlackBranchVal(key, val, left, right); } -static abstract class Node implements IMapEntry { - final Object key; +static abstract class Node implements IMapEntry{ + final Object key; - Node(Object key){ - this.key = key; - } + Node(Object key){ + this.key = key; + } - public Object key(){ - return key; - } + public Object key(){ + return key; + } - public Object val(){ - return null; - } + public Object val(){ + return null; + } - Node left(){ - return null; - } + Node left(){ + return null; + } - Node right(){ - return null; - } + Node right(){ + return null; + } - abstract Node addLeft(Node ins); + abstract Node addLeft(Node ins); - abstract Node addRight(Node ins); + abstract Node addRight(Node ins); - abstract Node removeLeft(Node del); + abstract Node removeLeft(Node del); - abstract Node removeRight(Node del); + abstract Node removeRight(Node del); - abstract Node blacken(); + abstract Node blacken(); - abstract Node redden(); + abstract Node redden(); - Node balanceLeft(Node parent){ - return black(parent.key, parent.val(), this, parent.right()); - } + Node balanceLeft(Node parent){ + return black(parent.key, parent.val(), this, parent.right()); + } - Node balanceRight(Node parent){ - return black(parent.key, parent.val(), parent.left(), this); - } + Node balanceRight(Node parent){ + return black(parent.key, parent.val(), parent.left(), this); + } - abstract Node replace(Object key, Object val, Node left, Node right); + abstract Node replace(Object key, Object val, Node left, Node right); } + static class Black extends Node{ - public Black(Object key){ + public Black(Object key){ super(key); } - Node addLeft(Node ins){ + Node addLeft(Node ins){ return ins.balanceLeft(this); } - Node addRight(Node ins){ + Node addRight(Node ins){ return ins.balanceRight(this); } - Node removeLeft(Node del){ + Node removeLeft(Node del){ return balanceLeftDel(key, val(), del, right()); } - Node removeRight(Node del){ + Node removeRight(Node del){ return balanceRightDel(key, val(), left(), del); } - Node blacken(){ + Node blacken(){ return this; } - Node redden(){ + Node redden(){ return new Red(key); } - Node replace(Object key, Object val, Node left, Node right){ + Node replace(Object key, Object val, Node left, Node right){ return black(key, val, left, right); } } + static class BlackVal extends Black{ - final Object val; + final Object val; - public BlackVal(Object key, Object val){ + public BlackVal(Object key, Object val){ super(key); this.val = val; } - public Object val(){ + public Object val(){ return val; } - Node redden(){ + Node redden(){ return new RedVal(key, val); } } + static class BlackBranch extends Black{ - final Node left; + final Node left; - final Node right; + final Node right; - public BlackBranch(Object key, Node left, Node right){ + public BlackBranch(Object key, Node left, Node right){ super(key); this.left = left; this.right = right; } - public Node left(){ + public Node left(){ return left; } - public Node right(){ + public Node right(){ return right; } - Node redden(){ + Node redden(){ return new RedBranch(key, left, right); } } + static class BlackBranchVal extends BlackBranch{ - final Object val; + final Object val; - public BlackBranchVal(Object key, Object val, Node left, Node right){ + public BlackBranchVal(Object key, Object val, Node left, Node right){ super(key, left, right); this.val = val; } - public Object val(){ + public Object val(){ return val; } - Node redden(){ + Node redden(){ return new RedBranchVal(key, val, left, right); } } + static class Red extends Node{ - public Red(Object key){ + public Red(Object key){ super(key); } - Node addLeft(Node ins){ + Node addLeft(Node ins){ return red(key, val(), ins, right()); } - Node addRight(Node ins){ + Node addRight(Node ins){ return red(key, val(), left(), ins); } - Node removeLeft(Node del){ + Node removeLeft(Node del){ return red(key, val(), del, right()); } - Node removeRight(Node del){ + Node removeRight(Node del){ return red(key, val(), left(), del); } - Node blacken(){ + Node blacken(){ return new Black(key); } - Node redden(){ + Node redden(){ throw new UnsupportedOperationException("Invariant violation"); } - Node replace(Object key, Object val, Node left, Node right){ + Node replace(Object key, Object val, Node left, Node right){ return red(key, val, left, right); } } + static class RedVal extends Red{ - final Object val; + final Object val; - public RedVal(Object key, Object val){ + public RedVal(Object key, Object val){ super(key); this.val = val; } - public Object val(){ + public Object val(){ return val; } - Node blacken(){ + Node blacken(){ return new BlackVal(key, val); } } + static class RedBranch extends Red{ - final Node left; + final Node left; - final Node right; + final Node right; - public RedBranch(Object key, Node left, Node right){ + public RedBranch(Object key, Node left, Node right){ super(key); this.left = left; this.right = right; } - public Node left(){ + public Node left(){ return left; } - public Node right(){ + public Node right(){ return right; } - Node balanceLeft(Node parent){ + Node balanceLeft(Node parent){ if(left instanceof Red) return red(key, val(), left.blacken(), black(parent.key, parent.val(), right, parent.right())); else if(right instanceof Red) @@ -581,7 +588,7 @@ static class RedBranch extends Red{ } - Node balanceRight(Node parent){ + Node balanceRight(Node parent){ if(right instanceof Red) return red(key, val(), black(parent.key, parent.val(), parent.left(), left), right.blacken()); else if(left instanceof Red) @@ -591,7 +598,7 @@ static class RedBranch extends Red{ return super.balanceRight(parent); } - Node blacken(){ + Node blacken(){ return new BlackBranch(key, left, right); } @@ -619,44 +626,44 @@ static class RedBranchVal extends RedBranch{ static public class Seq extends ASeq{ final ISeq stack; final boolean asc; - final int cnt; - - public Seq(ISeq stack, boolean asc,int cnt) { - this.stack = stack; - this.asc = asc; - this.cnt = cnt; - } - - static Seq create(Node t, boolean asc,int cnt) { - return new Seq(push(t, null, asc),asc,cnt); - } - - static ISeq push(Node t, ISeq stack, boolean asc) { - while(t != null) - { - stack = RT.cons(t,stack); - t = asc ? t.left() : t.right(); - } - return stack; - } - - public Object first() { - return stack.first(); - } - - public ISeq rest() { - Node t = (Node)stack.first(); - ISeq nextstack = push(asc ? t.right() : t.left(), stack.rest(), asc); - if(nextstack != null) - { - return new Seq(nextstack,asc,cnt-1); - } - return null; - } - - public int count() { - return cnt; - } + final int cnt; + + public Seq(ISeq stack, boolean asc, int cnt){ + this.stack = stack; + this.asc = asc; + this.cnt = cnt; + } + + static Seq create(Node t, boolean asc, int cnt){ + return new Seq(push(t, null, asc), asc, cnt); + } + + static ISeq push(Node t, ISeq stack, boolean asc){ + while(t != null) + { + stack = RT.cons(t, stack); + t = asc ? t.left() : t.right(); + } + return stack; + } + + public Object first(){ + return stack.first(); + } + + public ISeq rest(){ + Node t = (Node) stack.first(); + ISeq nextstack = push(asc ? t.right() : t.left(), stack.rest(), asc); + if(nextstack != null) + { + return new Seq(nextstack, asc, cnt - 1); + } + return null; + } + + public int count(){ + return cnt; + } } static public class NodeIterator implements Iterator{ @@ -742,13 +749,15 @@ static public void main(String args[]){ } Collections.shuffle(Arrays.asList(ints)); //force the ListMap class loading now - try { - //PersistentListMap.EMPTY.assocEx(1, null).assocEx(2,null).assocEx(3,null); - } catch (Exception e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - System.out.println("Building set"); + try + { + //PersistentListMap.EMPTY.assocEx(1, null).assocEx(2,null).assocEx(3,null); + } + catch(Exception e) + { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + System.out.println("Building set"); //IPersistentMap set = new PersistentArrayMap(); //IPersistentMap set = new PersistentHashtableMap(1001); IPersistentMap set = PersistentHashMap.EMPTY; @@ -766,8 +775,7 @@ static public void main(String args[]){ Integer anInt = ints[i]; set = set.assoc(anInt, anInt); } - //System.out.println("_count = " + set.count()); - + //System.out.println("_count = " + set.count()); // System.out.println("_count = " + set._count + ", min: " + set.minKey() + ", max: " + set.maxKey() // + ", depth: " + set.depth()); @@ -782,7 +790,7 @@ static public void main(String args[]){ } Random rand = new Random(42); - for(int i = 0; i < ints.length/2; i++) + for(int i = 0; i < ints.length / 2; i++) { Integer anInt = ints[rand.nextInt(n)]; set = set.without(anInt); @@ -791,7 +799,7 @@ static public void main(String args[]){ long estimatedTime = System.nanoTime() - startTime; System.out.println(); - System.out.println("_count = " + set.count() + ", time: " + estimatedTime/1000000); + System.out.println("_count = " + set.count() + ", time: " + estimatedTime / 1000000); System.out.println("Building ht"); Hashtable ht = new Hashtable(1001); @@ -806,7 +814,7 @@ static public void main(String args[]){ Integer anInt = ints[i]; ht.put(anInt, anInt); } - //System.out.println("size = " + ht.size()); + //System.out.println("size = " + ht.size()); it = ht.entrySet().iterator(); while(it.hasNext()) { @@ -818,14 +826,14 @@ static public void main(String args[]){ } rand = new Random(42); - for(int i = 0; i < ints.length/2; i++) + for(int i = 0; i < ints.length / 2; i++) { Integer anInt = ints[rand.nextInt(n)]; ht.remove(anInt); } estimatedTime = System.nanoTime() - startTime; System.out.println(); - System.out.println("size = " + ht.size() + ", time: " + estimatedTime/1000000); + System.out.println("size = " + ht.size() + ", time: " + estimatedTime / 1000000); System.out.println("set lookup"); startTime = System.nanoTime(); @@ -837,7 +845,7 @@ static public void main(String args[]){ ++c; } estimatedTime = System.nanoTime() - startTime; - System.out.println("notfound = " + c + ", time: " + estimatedTime/1000000); + System.out.println("notfound = " + c + ", time: " + estimatedTime / 1000000); System.out.println("ht lookup"); startTime = System.nanoTime(); @@ -849,7 +857,7 @@ static public void main(String args[]){ ++c; } estimatedTime = System.nanoTime() - startTime; - System.out.println("notfound = " + c + ", time: " + estimatedTime/1000000); + System.out.println("notfound = " + c + ", time: " + estimatedTime / 1000000); // System.out.println("_count = " + set._count + ", min: " + set.minKey() + ", max: " + set.maxKey() // + ", depth: " + set.depth()); diff --git a/src/jvm/clojure/lang/RT.java b/src/jvm/clojure/lang/RT.java index 87fd7aaf..36e0fa06 100644 --- a/src/jvm/clojure/lang/RT.java +++ b/src/jvm/clojure/lang/RT.java @@ -18,7 +18,7 @@ import java.io.*; public class RT{ - static public Symbol T = Symbol.intern(":t"); +static public Symbol T = new Symbol("t", null); static public Var OUT; static public Var _CT_MODULE; @@ -27,52 +27,54 @@ static public final Object[] EMPTY_ARRAY = new Object[]{}; static public final Character[] chars; static AtomicInteger id = new AtomicInteger(1); - static { - chars = new Character[256]; - for(int i=0;i<chars.length;i++) - chars[i] = new Character((char)i); try - { - OUT = Module.intern("clojure", "^out"); - _CT_MODULE = Module.intern("clojure", "^module"); - - - OUT.bind(new OutputStreamWriter(System.out)); - _CT_MODULE.bind((Module.findOrCreate("clj-user"))); - } - catch(Exception e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - - static public int nextID(){ - return id.getAndIncrement(); - } - -static public boolean equal(Object k1,Object k2){ - return k1 == k2 || - (k1 != null && k1.equals(k2)); -} - - static public Object eq(Object arg1, Object arg2) { - return (arg1 == arg2)?Boolean.TRUE:null; - } - - static public Object eql(Object arg1, Object arg2) { - if(arg1 == arg2) - return Boolean.TRUE; - if(arg1 == null || arg2 == null) - return null; - if(arg1 instanceof Num - && arg1.getClass() == arg2.getClass() - && arg1.equals(arg2)) - return Boolean.TRUE; - if(arg1.getClass() == Character.class - && arg2.getClass() == Character.class - && arg1.equals(arg2)) - return Boolean.TRUE; - return null; - } +static + { + chars = new Character[256]; + for(int i = 0; i < chars.length; i++) + chars[i] = new Character((char) i); + try + { + OUT = Module.intern("clojure", "^out"); + _CT_MODULE = Module.intern("clojure", "^module"); + + + OUT.bind(new OutputStreamWriter(System.out)); + _CT_MODULE.bind((Module.findOrCreate("clj-user"))); + } + catch(Exception e) + { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + } + +static public int nextID(){ + return id.getAndIncrement(); +} + +static public boolean equal(Object k1, Object k2){ + return k1 == k2 || + (k1 != null && k1.equals(k2)); +} + +static public Object eq(Object arg1, Object arg2){ + return (arg1 == arg2) ? Boolean.TRUE : null; +} + +static public Object eql(Object arg1, Object arg2){ + if(arg1 == arg2) + return Boolean.TRUE; + if(arg1 == null || arg2 == null) + return null; + if(arg1 instanceof Num + && arg1.getClass() == arg2.getClass() + && arg1.equals(arg2)) + return Boolean.TRUE; + if(arg1.getClass() == Character.class + && arg2.getClass() == Character.class + && arg1.equals(arg2)) + return Boolean.TRUE; + return null; +} // static public Object equal(Object arg1, Object arg2) { // if(arg1 == null) @@ -87,601 +89,584 @@ static public boolean equal(Object k1,Object k2){ // ?Boolean.TRUE:null; // } - ////////////// Collections support ///////////////////////////////// static public int hash(Object o){ - if(o == null) - return 0; - return o.hashCode(); + if(o == null) + return 0; + return o.hashCode(); } static public int hashCombine(int seed, int hash){ - //a la boost - seed ^= hash + 0x9e3779b9 + (seed << 6) + (seed >> 2); - return seed; -} - -static public ISeq seq(Object coll) { - if(coll == null) - return null; - else if(coll instanceof IPersistentCollection) - return ((IPersistentCollection) coll).seq(); - else if(coll instanceof Iterable) - return IteratorSeq.create(((Iterable) coll).iterator()); - else if(coll instanceof Object[]) - return ArraySeq.create((Object[]) coll); - else - throw new IllegalAccessError("Don't know how to create ISeq from arg"); + //a la boost + seed ^= hash + 0x9e3779b9 + (seed << 6) + (seed >> 2); + return seed; +} + +static public ISeq seq(Object coll){ + if(coll == null) + return null; + else if(coll instanceof IPersistentCollection) + return ((IPersistentCollection) coll).seq(); + else if(coll instanceof Iterable) + return IteratorSeq.create(((Iterable) coll).iterator()); + else if(coll instanceof Object[]) + return ArraySeq.create((Object[]) coll); + else + throw new IllegalAccessError("Don't know how to create ISeq from arg"); } -static public ISeq keys(Object coll) { - return APersistentMap.KeySeq.create(seq(coll)); +static public ISeq keys(Object coll){ + return APersistentMap.KeySeq.create(seq(coll)); } -static public ISeq vals(Object coll) { - return APersistentMap.ValSeq.create(seq(coll)); +static public ISeq vals(Object coll){ + return APersistentMap.ValSeq.create(seq(coll)); } -static public Object meta(Object x) { - if(x == null) - return null; - return ((Obj)x).meta(); +static public Object meta(Object x){ + if(x == null) + return null; + return ((Obj) x).meta(); } -public static int count(Object o) { - if(o == null) - return 0; - return ((IPersistentCollection)o).count(); +public static int count(Object o){ + if(o == null) + return 0; + return ((IPersistentCollection) o).count(); } -static public IPersistentCollection cons(Object x, IPersistentCollection y) { - if(y == null) - return new PersistentList(x); - return y.cons(x); +static public IPersistentCollection cons(Object x, IPersistentCollection y){ + if(y == null) + return new PersistentList(x); + return y.cons(x); } -static public ISeq cons(Object x, ISeq y) { - if(y == null) - return new PersistentList(x); - return y.cons(x); +static public ISeq cons(Object x, ISeq y){ + if(y == null) + return new PersistentList(x); + return y.cons(x); } -static public Object first(Object x) { - if(x == null) - return null; - return seq(x).first(); +static public Object first(Object x){ + if(x == null) + return null; + return seq(x).first(); } -static public Object second(Object x) { - return first(rest(x)); +static public Object second(Object x){ + return first(rest(x)); } -static public Object third(Object x) { - return first(rest(rest(x))); +static public Object third(Object x){ + return first(rest(rest(x))); } -static public Object fourth(Object x) { - return first(rest(rest(rest(x)))); +static public Object fourth(Object x){ + return first(rest(rest(rest(x)))); } -static public ISeq rest(Object x) { - if(x == null) - return null; - return seq(x).rest(); +static public ISeq rest(Object x){ + if(x == null) + return null; + return seq(x).rest(); } -static public ISeq rrest(Object x) { - return rest(rest(x)); +static public ISeq rrest(Object x){ + return rest(rest(x)); } -static public Object peek(Object x) { - if(x == null) - return null; - return ((IPersistentList)x).peek(); +static public Object peek(Object x){ + if(x == null) + return null; + return ((IPersistentList) x).peek(); } -static public Object pop(Object x) { - if(x == null) - return null; - return ((IPersistentList)x).pop(); +static public Object pop(Object x){ + if(x == null) + return null; + return ((IPersistentList) x).pop(); } -static public Object get(Object key, Object coll) { - if(coll == null) - return null; - return ((Associative)coll).get(key); +static public Object get(Object key, Object coll){ + if(coll == null) + return null; + return ((Associative) coll).valAt(key); } -static public Object assoc(Object key, Object val, Object coll) { - if(coll == null) - return new MapEntry(key,val); - return ((Associative)coll).assoc(key,val); +static public Object assoc(Object key, Object val, Object coll){ + if(coll == null) + return new MapEntry(key, val); + return ((Associative) coll).assoc(key, val); } -static public Object contains(Object key, Object coll) { - if(coll == null) - return false; - return ((Associative)coll).contains(key); +static public Object contains(Object key, Object coll){ + if(coll == null) + return false; + return ((Associative) coll).contains(key); } -static public Object find(Object key, Object coll) { - if(coll == null) - return null; - return ((Associative)coll).find(key); +static public Object find(Object key, Object coll){ + if(coll == null) + return null; + return ((Associative) coll).entryAt(key); } //takes a seq of key,val,key,val + //returns tail starting at val of matching key if found, else null -static public ISeq findKey(Keyword key,ISeq keyvals) throws Exception { - while(keyvals != null) - { - ISeq r = keyvals.rest(); - if (r == null) - throw new Exception("Malformed keyword argslist"); - if (keyvals.first() == key) - return r; - keyvals = r.rest(); - } - return null; -} - -static public Object without(Object key, Object coll) { - if(coll == null) - return null; - return ((IPersistentMap)coll).without(key); -} - -static public Object nth(int n, Object coll) { - if(coll == null) - return null; - else if(coll instanceof IPersistentArray) - return ((IPersistentArray)coll).nth(n); - else if(coll instanceof Object[]) - return ((Object[])coll)[n]; - else if(coll instanceof Sequential) - { - ISeq seq = ((IPersistentCollection) coll).seq(); - for(int i=0;i<=n && seq != null;++i, seq = seq.rest()) - { - if(i == n) - return seq.first(); - } - return null; - } - else - return null; -} - -static public Object assocN(int n, Object val, Object coll) { - if(coll == null) - return null; - else if(coll instanceof IPersistentArray) - return ((IPersistentArray)coll).assocN(n,val); - else if(coll instanceof Object[]) - { - //hmm... this is not persistent - Object[] array = ((Object[])coll); - array[n] = val; - return array; - } - else - return null; -} - -static public Iter iter(Object coll) - { - if(coll == null || coll instanceof Iter) - return (Iter) coll; - else if(coll instanceof Iterator) - { - Iterator i = (Iterator) coll; - if(i.hasNext()) - return new IteratorIter(i); - return null; - } - else if(coll instanceof Iterable) - return new IteratorIter(((Iterable) coll).iterator()); - - else - throw new IllegalArgumentException("Don't know how to create Iter from arg"); - } - -/************************ Boxing/casts *******************************/ -static public Object box(Object x) - { - return x; - } - -static public Character box(char x) - { - if(x < chars.length) - return chars[x]; - return new Character(x); - } - -static public Object box(boolean x) - { - return x?T:null; - } - -static public Object box(Boolean x) - { - return x?T:null; - } - -static public Num box(byte x) - { - return Num.from(x); - } - -static public Num box(short x) - { - return Num.from(x); - } - -static public Num box(int x) - { - return Num.from(x); - } - -static public Num box(long x) - { - return Num.from(x); - } - -static public Num box(float x) - { - return Num.from(x); - } +static public ISeq findKey(Keyword key, ISeq keyvals) throws Exception{ + while(keyvals != null) + { + ISeq r = keyvals.rest(); + if(r == null) + throw new Exception("Malformed keyword argslist"); + if(keyvals.first() == key) + return r; + keyvals = r.rest(); + } + return null; +} + +static public Object without(Object key, Object coll){ + if(coll == null) + return null; + return ((IPersistentMap) coll).without(key); +} + +static public Object nth(int n, Object coll){ + if(coll == null) + return null; + else if(coll instanceof IPersistentArray) + return ((IPersistentArray) coll).nth(n); + else if(coll instanceof Object[]) + return ((Object[]) coll)[n]; + else if(coll instanceof Sequential) + { + ISeq seq = ((IPersistentCollection) coll).seq(); + for(int i = 0; i <= n && seq != null; ++i, seq = seq.rest()) + { + if(i == n) + return seq.first(); + } + return null; + } + else + return null; +} + +static public Object assocN(int n, Object val, Object coll){ + if(coll == null) + return null; + else if(coll instanceof IPersistentArray) + return ((IPersistentArray) coll).assocN(n, val); + else if(coll instanceof Object[]) + { + //hmm... this is not persistent + Object[] array = ((Object[]) coll); + array[n] = val; + return array; + } + else + return null; +} + +static public Iter iter(Object coll){ + if(coll == null || coll instanceof Iter) + return (Iter) coll; + else if(coll instanceof Iterator) + { + Iterator i = (Iterator) coll; + if(i.hasNext()) + return new IteratorIter(i); + return null; + } + else if(coll instanceof Iterable) + return new IteratorIter(((Iterable) coll).iterator()); + + else + throw new IllegalArgumentException("Don't know how to create Iter from arg"); +} + +/** + * ********************* Boxing/casts ****************************** + */ +static public Object box(Object x){ + return x; +} + +static public Character box(char x){ + if(x < chars.length) + return chars[x]; + return new Character(x); +} + +static public Object box(boolean x){ + return x ? T : null; +} + +static public Object box(Boolean x){ + return x ? T : null; +} -static public Num box(double x) - { - return Num.from(x); - } +static public Num box(byte x){ + return Num.from(x); +} -static public char charCast(Object x) - { - if(x instanceof Character) - return ((Character)x).charValue(); - return (char) ((Number)x).intValue(); - } +static public Num box(short x){ + return Num.from(x); +} -static public boolean booleanCast(Object x) - { - if(x instanceof Boolean) - return ((Boolean)x).booleanValue(); - return x != null; - } +static public Num box(int x){ + return Num.from(x); +} -static public byte byteCast(Object x) - { - return ((Number)x).byteValue(); - } +static public Num box(long x){ + return Num.from(x); +} -static public short shortCast(Object x) - { - return ((Number)x).shortValue(); - } +static public Num box(float x){ + return Num.from(x); +} -static public int intCast(Object x) - { - return ((Number)x).intValue(); - } +static public Num box(double x){ + return Num.from(x); +} -static public long longCast(Object x) - { - return ((Number)x).longValue(); - } +static public char charCast(Object x){ + if(x instanceof Character) + return ((Character) x).charValue(); + return (char) ((Number) x).intValue(); +} -static public float floatCast(Object x) - { - return ((Number)x).floatValue(); - } +static public boolean booleanCast(Object x){ + if(x instanceof Boolean) + return ((Boolean) x).booleanValue(); + return x != null; +} + +static public byte byteCast(Object x){ + return ((Number) x).byteValue(); +} -static public double doubleCast(Object x) - { - return ((Number)x).doubleValue(); - } +static public short shortCast(Object x){ + return ((Number) x).shortValue(); +} + +static public int intCast(Object x){ + return ((Number) x).intValue(); +} +static public long longCast(Object x){ + return ((Number) x).longValue(); +} -/******************************************* list support ********************************/ +static public float floatCast(Object x){ + return ((Number) x).floatValue(); +} +static public double doubleCast(Object x){ + return ((Number) x).doubleValue(); +} +/** + * **************************************** list support ******************************* + */ -static public ISeq list() - { - return null; - } -static public ISeq list(Object arg1) { - return new PersistentList(arg1); +static public ISeq list(){ + return null; } -static public ISeq list(Object arg1, Object arg2) throws Exception { -return listStar(arg1, arg2, null); +static public ISeq list(Object arg1){ + return new PersistentList(arg1); } -static public ISeq list(Object arg1, Object arg2, Object arg3) throws Exception { -return listStar(arg1, arg2, arg3, null); +static public ISeq list(Object arg1, Object arg2) throws Exception{ + return listStar(arg1, arg2, null); } -static public ISeq list(Object arg1, Object arg2, Object arg3, Object arg4) throws Exception { -return listStar(arg1, arg2, arg3, arg4, null); +static public ISeq list(Object arg1, Object arg2, Object arg3) throws Exception{ + return listStar(arg1, arg2, arg3, null); } -static public ISeq list(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) throws Exception { -return listStar(arg1, arg2, arg3, arg4, arg5, null); +static public ISeq list(Object arg1, Object arg2, Object arg3, Object arg4) throws Exception{ + return listStar(arg1, arg2, arg3, arg4, null); } -static public ISeq listStar(Object arg1, ISeq rest) throws Exception { -return (ISeq) cons(arg1, rest); +static public ISeq list(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) throws Exception{ + return listStar(arg1, arg2, arg3, arg4, arg5, null); } -static public ISeq listStar(Object arg1, Object arg2, ISeq rest) throws Exception { -return (ISeq) cons(arg1, cons(arg2, rest)); +static public ISeq listStar(Object arg1, ISeq rest) throws Exception{ + return (ISeq) cons(arg1, rest); } -static public ISeq listStar(Object arg1, Object arg2, Object arg3, ISeq rest) throws Exception { -return (ISeq) cons(arg1, cons(arg2, cons(arg3, rest))); +static public ISeq listStar(Object arg1, Object arg2, ISeq rest) throws Exception{ + return (ISeq) cons(arg1, cons(arg2, rest)); } -static public ISeq listStar(Object arg1, Object arg2, Object arg3, Object arg4, ISeq rest) throws Exception { -return (ISeq) cons(arg1, cons(arg2, cons(arg3, cons(arg4, rest)))); +static public ISeq listStar(Object arg1, Object arg2, Object arg3, ISeq rest) throws Exception{ + return (ISeq) cons(arg1, cons(arg2, cons(arg3, rest))); } -static public ISeq listStar(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, ISeq rest) throws Exception { -return (ISeq) cons(arg1, cons(arg2, cons(arg3, cons(arg4, cons(arg5, rest))))); +static public ISeq listStar(Object arg1, Object arg2, Object arg3, Object arg4, ISeq rest) throws Exception{ + return (ISeq) cons(arg1, cons(arg2, cons(arg3, cons(arg4, rest)))); } -static public ISeq arrayToList(Object[] a) throws Exception { - ISeq ret = null; - for(int i=a.length-1;i>=0;--i) - ret = (ISeq) cons(a[i], ret); - return ret; +static public ISeq listStar(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, ISeq rest) + throws Exception{ + return (ISeq) cons(arg1, cons(arg2, cons(arg3, cons(arg4, cons(arg5, rest))))); } -static public Object[] seqToArray(ISeq seq) throws Exception { - int len = length(seq); - Object[] ret = new Object[len]; - for(int i=0;seq != null;++i, seq = seq.rest()) - ret[i] = seq.first(); - return ret; +static public ISeq arrayToList(Object[] a) throws Exception{ + ISeq ret = null; + for(int i = a.length - 1; i >= 0; --i) + ret = (ISeq) cons(a[i], ret); + return ret; } -static public int length(ISeq list) throws Exception { -int i = 0; -for(ISeq c = list; c != null; c = c.rest()) - { - i++; - } -return i; +static public Object[] seqToArray(ISeq seq) throws Exception{ + int len = length(seq); + Object[] ret = new Object[len]; + for(int i = 0; seq != null; ++i, seq = seq.rest()) + ret[i] = seq.first(); + return ret; } -static public int boundedLength(ISeq list, int limit) throws Exception { -int i = 0; -for(ISeq c = list; c != null && i <= limit; c = c.rest()) - { - i++; - } -return i; +static public int length(ISeq list) throws Exception{ + int i = 0; + for(ISeq c = list; c != null; c = c.rest()) + { + i++; + } + return i; } +static public int boundedLength(ISeq list, int limit) throws Exception{ + int i = 0; + for(ISeq c = list; c != null && i <= limit; c = c.rest()) + { + i++; + } + return i; +} ///////////////////////////////// reader support //////////////////////////////// static Character readRet(int ret){ - if(ret == -1) - return null; - return box((char) ret); + if(ret == -1) + return null; + return box((char) ret); } -static public Character readChar(Reader r) throws Exception { - int ret = r.read(); - return readRet(ret); +static public Character readChar(Reader r) throws Exception{ + int ret = r.read(); + return readRet(ret); } -static public Character peekChar(Reader r) throws Exception { - int ret; - if(r instanceof PushbackReader) - { - ret = r.read(); - ((PushbackReader) r).unread(ret); - } - else - { - r.mark(1); - ret = r.read(); - r.reset(); - } +static public Character peekChar(Reader r) throws Exception{ + int ret; + if(r instanceof PushbackReader) + { + ret = r.read(); + ((PushbackReader) r).unread(ret); + } + else + { + r.mark(1); + ret = r.read(); + r.reset(); + } - return readRet(ret); + return readRet(ret); } static public int getLineNumber(Reader r){ - if(r instanceof LineNumberingPushbackReader) - return ((LineNumberingPushbackReader)r).getLineNumber(); - return 0; + if(r instanceof LineNumberingPushbackReader) + return ((LineNumberingPushbackReader) r).getLineNumber(); + return 0; } -static public LineNumberingPushbackReader getLineNumberingReader(Reader r) { - if(isLineNumberingReader(r)) - return (LineNumberingPushbackReader) r; - return new LineNumberingPushbackReader(r); +static public LineNumberingPushbackReader getLineNumberingReader(Reader r){ + if(isLineNumberingReader(r)) + return (LineNumberingPushbackReader) r; + return new LineNumberingPushbackReader(r); } -static public boolean isLineNumberingReader(Reader r) { - return r instanceof LineNumberingPushbackReader; +static public boolean isLineNumberingReader(Reader r){ + return r instanceof LineNumberingPushbackReader; } -static public String resolveClassNameInContext(String className) { - //todo - look up in context var - return className; +static public String resolveClassNameInContext(String className){ + //todo - look up in context var + return className; } static public boolean suppressRead(){ - //todo - look up in suppress-read var - return false; -} - -static public void print(Object x, Writer w) throws Exception { - //todo - make extensible - if(x == null) - w.write("null"); - else if(x instanceof ISeq) - { - w.write('('); - for(ISeq s = (ISeq)x;s != null;s = s.rest()) - { - print(s.first(), w); - if(s.rest()!=null) - w.write(' '); - } - w.write(')'); - } - else if(x instanceof String) - { - w.write('"'); - w.write(x.toString()); - w.write('"'); - } - else if(x instanceof Character) - { - w.write('\\'); - char c = ((Character)x).charValue(); - switch(c){ - case '\n': - w.write("newline"); - break; - case '\t': - w.write("tab"); - break; - case ' ': - w.write("space"); - break; - default: - w.write(c); - } - } - else w.write(x.toString()); -} - -static public void formatAesthetic(Writer w,Object obj) throws IOException { - if(obj == null) - w.write("null"); - else - w.write(obj.toString()); -} - -static public void formatStandard(Writer w,Object obj) throws IOException { - if(obj == null) - w.write("null"); - else if(obj instanceof String) - { - w.write('"'); - w.write((String) obj); - w.write('"'); - } - else if(obj instanceof Character) - { - w.write('\\'); - char c = ((Character)obj).charValue(); - switch(c){ - case '\n': - w.write("newline"); - break; - case '\t': - w.write("tab"); - break; - case ' ': - w.write("space"); - break; - default: - w.write(c); - } - } - else - w.write(obj.toString()); -} - -static public Object format(Object o, String s, Object... args) throws Exception { + //todo - look up in suppress-read var + return false; +} + +static public void print(Object x, Writer w) throws Exception{ + //todo - make extensible + if(x == null) + w.write("null"); + else if(x instanceof ISeq) + { + w.write('('); + for(ISeq s = (ISeq) x; s != null; s = s.rest()) + { + print(s.first(), w); + if(s.rest() != null) + w.write(' '); + } + w.write(')'); + } + else if(x instanceof String) + { + w.write('"'); + w.write(x.toString()); + w.write('"'); + } + else if(x instanceof Character) + { + w.write('\\'); + char c = ((Character) x).charValue(); + switch(c) + { + case'\n': + w.write("newline"); + break; + case'\t': + w.write("tab"); + break; + case' ': + w.write("space"); + break; + default: + w.write(c); + } + } + else w.write(x.toString()); +} + +static public void formatAesthetic(Writer w, Object obj) throws IOException{ + if(obj == null) + w.write("null"); + else + w.write(obj.toString()); +} + +static public void formatStandard(Writer w, Object obj) throws IOException{ + if(obj == null) + w.write("null"); + else if(obj instanceof String) + { + w.write('"'); + w.write((String) obj); + w.write('"'); + } + else if(obj instanceof Character) + { + w.write('\\'); + char c = ((Character) obj).charValue(); + switch(c) + { + case'\n': + w.write("newline"); + break; + case'\t': + w.write("tab"); + break; + case' ': + w.write("space"); + break; + default: + w.write(c); + } + } + else + w.write(obj.toString()); +} + +static public Object format(Object o, String s, Object... args) throws Exception{ Writer w; if(o == null) w = new StringWriter(); - else if(equal(o,T)) - w = (Writer)OUT.getValue(); + else if(equal(o, T)) + w = (Writer) OUT.getValue(); else - w = (Writer)o; - doFormat(w,s,ArraySeq.create(args)); + w = (Writer) o; + doFormat(w, s, ArraySeq.create(args)); if(o == null) return w.toString(); return null; } -static public ISeq doFormat(Writer w, String s, ISeq args) throws Exception { - for (int i = 0; i < s.length();) - { - char c = s.charAt(i++); - switch (Character.toLowerCase(c)) - { - case '~': - char d = s.charAt(i++); - switch (Character.toLowerCase(d)) - { - case '%': - w.write('\n'); - break; - case 't': - w.write('\t'); - break; - case 'a': - if(args == null) - throw new IllegalArgumentException("Missing argument"); - RT.formatAesthetic(w, RT.first(args)); - args = RT.rest(args); - break; - case 's': - if(args == null) - throw new IllegalArgumentException("Missing argument"); - RT.formatStandard(w, RT.first(args)); - args = RT.rest(args); - break; - case '{': - int j = s.indexOf("~}", i); //note - does not nest - if(j == -1) - throw new IllegalArgumentException("Missing ~}"); - String subs = s.substring(i, j); - for(ISeq sargs = RT.seq(RT.first(args));sargs != null;) - sargs = doFormat(w, subs, sargs); - args = RT.rest(args); - i = j+2; //skip ~} - break; - case '^': - if(args == null) - return null; - break; - case '~': - w.write('~'); - break; - default: - throw new IllegalArgumentException("Unsupported ~ directive: " + d); - } - break; - default: - w.write(c); - } - } - return args; +static public ISeq doFormat(Writer w, String s, ISeq args) throws Exception{ + for(int i = 0; i < s.length();) + { + char c = s.charAt(i++); + switch(Character.toLowerCase(c)) + { + case'~': + char d = s.charAt(i++); + switch(Character.toLowerCase(d)) + { + case'%': + w.write('\n'); + break; + case't': + w.write('\t'); + break; + case'a': + if(args == null) + throw new IllegalArgumentException("Missing argument"); + RT.formatAesthetic(w, RT.first(args)); + args = RT.rest(args); + break; + case's': + if(args == null) + throw new IllegalArgumentException("Missing argument"); + RT.formatStandard(w, RT.first(args)); + args = RT.rest(args); + break; + case'{': + int j = s.indexOf("~}", i); //note - does not nest + if(j == -1) + throw new IllegalArgumentException("Missing ~}"); + String subs = s.substring(i, j); + for(ISeq sargs = RT.seq(RT.first(args)); sargs != null;) + sargs = doFormat(w, subs, sargs); + args = RT.rest(args); + i = j + 2; //skip ~} + break; + case'^': + if(args == null) + return null; + break; + case'~': + w.write('~'); + break; + default: + throw new IllegalArgumentException("Unsupported ~ directive: " + d); + } + break; + default: + w.write(c); + } + } + return args; } ///////////////////////////////// values ////////////////////////// -static public Object setValues(Object... vals) - { - ThreadLocalData.setValues(vals); - if(vals.length > 0) - return vals[0]; - return null; - } +static public Object setValues(Object... vals){ + ThreadLocalData.setValues(vals); + if(vals.length > 0) + return vals[0]; + return null; +} } diff --git a/src/jvm/clojure/lang/TRef.java b/src/jvm/clojure/lang/TRef.java index a9649b38..9fde0db4 100644 --- a/src/jvm/clojure/lang/TRef.java +++ b/src/jvm/clojure/lang/TRef.java @@ -19,34 +19,34 @@ public class TRef<T>{ final AtomicReference<TVal> tvals; volatile InheritableThreadLocal dvals; -public TRef() { +public TRef(){ this.tvals = new AtomicReference<TVal>(); this.dvals = null; } -public TRef(T initVal) { +public TRef(T initVal){ this.tvals = new AtomicReference<TVal>(); tvals.set(new TVal(initVal, Transaction.ZERO_POINT, null)); } -public T getCurrentVal(){ +public T currentVal(){ Binding b = getThreadBinding(); if(b != null) return (T) b.val; TVal current = getCurrentTVal(); if(current != null) - return (T)current.val; + return (T) current.val; return null; } -public T get() throws Exception{ +public T val() throws Exception{ Binding b = getThreadBinding(); if(b != null) return (T) b.val; Transaction t = Transaction.get(); if(t != null) return (T) t.doGet(this); - return getCurrentVal(); + return currentVal(); } final Binding getThreadBinding(){ @@ -70,7 +70,7 @@ public void pushThreadBinding(T val){ public void popThreadBinding() throws Exception{ Binding b; if(dvals == null || (b = (Binding) dvals.get()) == null) - throw new Exception("Can't pop unbound ref"); + throw new Exception("Can't pop unbound ref"); dvals.set(b.rest); } @@ -84,14 +84,14 @@ public T set(T val) throws Exception{ tvals.set(new TVal(val, Transaction.ZERO_POINT, null)); return val; } - return (T) Transaction.getEx().doSet(this,val); + return (T) Transaction.getEx().doSet(this, val); } public T commute(IFn fn) throws Exception{ Binding b = getThreadBinding(); if(b != null) return (T) (b.val = fn.invoke(b.val)); - return (T) Transaction.getEx().doCommute(this,fn); + return (T) Transaction.getEx().doCommute(this, fn); } public void touch() throws Exception{ @@ -99,7 +99,7 @@ public void touch() throws Exception{ } boolean isBound(){ - return (dvals != null && dvals.get() != null ) + return (dvals != null && dvals.get() != null) || getCurrentTVal() != null; } @@ -112,7 +112,7 @@ TVal getCurrentTVal(){ } TVal valAsOfPoint(TRef tref, int tpoint){ - for(TVal tv = getCurrentTVal();tv != null;tv = tv.prior) + for(TVal tv = getCurrentTVal(); tv != null; tv = tv.prior) { if(tv.tstamp.tpoint <= tpoint) return tv; @@ -120,8 +120,8 @@ TVal valAsOfPoint(TRef tref, int tpoint){ return null; } -TVal valAsOfTime(TRef tref,long msecs){ - for(TVal tv = getCurrentTVal();tv != null;tv = tv.prior) +TVal valAsOfTime(TRef tref, long msecs){ + for(TVal tv = getCurrentTVal(); tv != null; tv = tv.prior) { if(tv.tstamp.msecs <= msecs) return tv; @@ -131,7 +131,7 @@ TVal valAsOfTime(TRef tref,long msecs){ void trimHistory(){ long ctp = Transaction.completedThroughPoint(); - for(TVal tv = getCurrentTVal();tv != null;tv = tv.prior) + for(TVal tv = getCurrentTVal(); tv != null; tv = tv.prior) { while(tv.tstamp.tpoint > ctp) tv = tv.prior; @@ -141,7 +141,7 @@ void trimHistory(){ void trimHistoryPriorToPoint(int tpoint){ long ctp = Transaction.completedThroughPoint(); - for(TVal tv = getCurrentTVal();tv != null;tv = tv.prior) + for(TVal tv = getCurrentTVal(); tv != null; tv = tv.prior) { while(tv.tstamp.tpoint > tpoint || tv.tstamp.tpoint > ctp) tv = tv.prior; @@ -151,7 +151,7 @@ void trimHistoryPriorToPoint(int tpoint){ void trimHistoryPriorToTime(long msecs){ long ctp = Transaction.completedThroughPoint(); - for(TVal tv = getCurrentTVal();tv != null;tv = tv.prior) + for(TVal tv = getCurrentTVal(); tv != null; tv = tv.prior) { while(tv.tstamp.msecs > msecs || tv.tstamp.tpoint > ctp) tv = tv.prior; diff --git a/src/jvm/clojure/lang/ThreadLocalData.java b/src/jvm/clojure/lang/ThreadLocalData.java index 875eb748..09321301 100644 --- a/src/jvm/clojure/lang/ThreadLocalData.java +++ b/src/jvm/clojure/lang/ThreadLocalData.java @@ -17,16 +17,14 @@ public class ThreadLocalData{ private static ThreadLocal<Object[]> values = new ThreadLocal<Object[]>(); static public Object[] getValues(){ - return values.get(); + return values.get(); } -static public void setValues(Object[] vals) { - values.set(vals); +static public void setValues(Object[] vals){ + values.set(vals); } - - private static ThreadLocal<Integer> tltest = new ThreadLocal<Integer>(); private static Integer test; private static volatile int sum; @@ -50,46 +48,46 @@ static public void main(String[] args){ long startTime = System.nanoTime(); sum = 0; - for(int i=0;i<n;i++) + for(int i = 0; i < n; i++) { - sum += test.intValue(); + sum += test.intValue(); } long estimatedTime = System.nanoTime() - startTime; - System.out.println("sum = " + sum + ", time: " + estimatedTime/1000000); + System.out.println("sum = " + sum + ", time: " + estimatedTime / 1000000); startTime = System.nanoTime(); sum = 0; - for(int i=0;i<n;i++) + for(int i = 0; i < n; i++) { sum += tltest.get().intValue(); } estimatedTime = System.nanoTime() - startTime; - System.out.println("sum = " + sum + ", time: " + estimatedTime/1000000); + System.out.println("sum = " + sum + ", time: " + estimatedTime / 1000000); startTime = System.nanoTime(); sum = 0; - for(int i=0;i<n;i++) + for(int i = 0; i < n; i++) { - sum += ((Integer)testmap.get(Thread.currentThread())).intValue(); + sum += ((Integer) testmap.valAt(Thread.currentThread())).intValue(); } estimatedTime = System.nanoTime() - startTime; - System.out.println("sum = " + sum + ", time: " + estimatedTime/1000000); + System.out.println("sum = " + sum + ", time: " + estimatedTime / 1000000); startTime = System.nanoTime(); sum = 0; - for(int i=0;i<n;i++) + for(int i = 0; i < n; i++) { if(fred != null) - sum += ((Integer)testmap.get(Thread.currentThread())).intValue(); + sum += ((Integer) testmap.valAt(Thread.currentThread())).intValue(); else - sum += test.intValue(); + sum += test.intValue(); } estimatedTime = System.nanoTime() - startTime; - System.out.println("sum = " + sum + ", time: " + estimatedTime/1000000); + System.out.println("sum = " + sum + ", time: " + estimatedTime / 1000000); } } diff --git a/src/jvm/clojure/lang/Transaction.java b/src/jvm/clojure/lang/Transaction.java index 1d978852..ed7de3a3 100644 --- a/src/jvm/clojure/lang/Transaction.java +++ b/src/jvm/clojure/lang/Transaction.java @@ -88,7 +88,7 @@ static void statusTransition(TStamp tstamp, TStamp.Status newStatus){ TStamp tstamp; TVal lock(TRef tref, boolean ensurePoint) throws Exception{ - TVal head = (TVal)tref.tvals.get(); + TVal head = (TVal) tref.tvals.get(); //already locked by this transaction if(head != null && head.tstamp == tstamp) return head; @@ -204,7 +204,7 @@ Object run(IFn fn) throws Exception{ Object doGet(TRef tref) throws Exception{ - TVal head = (TVal)tref.tvals.get(); + TVal head = (TVal) tref.tvals.get(); if(head == null) return null; if(head.tstamp == tstamp) @@ -386,7 +386,7 @@ public static void main(String[] args){ for(TRef tref : items) { //Transaction.get().doTouch(tref); - Transaction t = Transaction.get(); + Transaction t = Transaction.get(); int val = (Integer) t.doGet(tref); t.doSet(tref, val + 1); } @@ -417,7 +417,7 @@ public static void main(String[] args){ System.out.println(); for(TRef item : items) { - System.out.printf("%d, ", (Integer) item.getCurrentVal()); + System.out.printf("%d, ", (Integer) item.currentVal()); } } catch(Exception ex) diff --git a/src/jvm/clojure/lang/Var.java b/src/jvm/clojure/lang/Var.java index 3058860b..19cdb716 100644 --- a/src/jvm/clojure/lang/Var.java +++ b/src/jvm/clojure/lang/Var.java @@ -12,29 +12,27 @@ package clojure.lang; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.AtomicInteger; import java.util.Random; -public class Var extends AFn { +public class Var extends AFn{ public final Symbol name; public Module module; public final TRef binding; public boolean exported = false; -Var(Symbol sym, Module ns) { - if (!(sym.getClass() == Symbol.class)) - throw new IllegalArgumentException("Only simple symbols can be var names"); - this.module = ns; - this.name = sym; +Var(Symbol sym, Module ns){ + if(!(sym.getClass() == Symbol.class)) + throw new IllegalArgumentException("Only simple symbols can be var names"); + this.module = ns; + this.name = sym; this.binding = new TRef(); } -public String toString() { - if (module == null) - return "#:" + name; - return module.name + ":" + name; +public String toString(){ + if(module == null) + return "#:" + name; + return module.name + ":" + name; } public Var bind(Object val) throws Exception{ @@ -46,8 +44,8 @@ public Var bind(Object val) throws Exception{ public Object getValue() throws Exception{ if(binding.isBound()) - return binding.get(); - throw new IllegalStateException(this.toString() + " is unbound."); + return binding.val(); + throw new IllegalStateException(this.toString() + " is unbound."); } public Object setValue(Object val) throws Exception{ @@ -55,194 +53,194 @@ public Object setValue(Object val) throws Exception{ return binding.set(val); } -void pushThreadBinding(Object val) { +void pushThreadBinding(Object val){ } -public void popThreadBinding() { +public void popThreadBinding(){ } -final public IFn fn() { +final public IFn fn(){ if(binding.isBound()) - return (IFn) binding.getCurrentVal(); - throw new IllegalStateException(this.toString() + " is unbound."); + return (IFn) binding.currentVal(); + throw new IllegalStateException(this.toString() + " is unbound."); } -public Object invoke() throws Exception { - return fn().invoke(); +public Object invoke() throws Exception{ + return fn().invoke(); } -public Object invoke(Object arg1) throws Exception { - return fn().invoke(arg1); +public Object invoke(Object arg1) throws Exception{ + return fn().invoke(arg1); } -public Object invoke(Object arg1, Object arg2) throws Exception { - return fn().invoke(arg1, arg2); +public Object invoke(Object arg1, Object arg2) throws Exception{ + return fn().invoke(arg1, arg2); } -public Object invoke(Object arg1, Object arg2, Object arg3) throws Exception { - return fn().invoke(arg1, arg2, arg3); +public Object invoke(Object arg1, Object arg2, Object arg3) throws Exception{ + return fn().invoke(arg1, arg2, arg3); } -public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4); +public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4); } -public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5); +public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5); } -public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6); +public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7) - throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7); + throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); + Object arg8) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8, Object arg9) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); + Object arg8, Object arg9) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8, Object arg9, Object arg10) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); + Object arg8, Object arg9, Object arg10) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8, Object arg9, Object arg10, Object arg11) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); + Object arg8, Object arg9, Object arg10, Object arg11) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, - Object arg8, Object arg9, Object arg10, Object arg11, Object arg12) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); + Object arg8, Object arg9, Object arg10, Object arg11, Object arg12) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13) - throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); + throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14) - throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); + throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15); + Object arg15) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15, Object arg16) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, - arg16); + Object arg15, Object arg16) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, + arg16); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15, Object arg16, Object arg17) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, - arg16, arg17); + Object arg15, Object arg16, Object arg17) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, + arg16, arg17); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15, Object arg16, Object arg17, Object arg18) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, - arg16, arg17, arg18); + Object arg15, Object arg16, Object arg17, Object arg18) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, + arg16, arg17, arg18); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, - Object arg15, Object arg16, Object arg17, Object arg18, Object arg19) throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, - arg16, arg17, arg18, arg19); + Object arg15, Object arg16, Object arg17, Object arg18, Object arg19) throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, + arg16, arg17, arg18, arg19); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20) - throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, - arg16, arg17, arg18, arg19, arg20); + throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, + arg16, arg17, arg18, arg19, arg20); } public Object invoke(Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7, Object arg8, Object arg9, Object arg10, Object arg11, Object arg12, Object arg13, Object arg14, Object arg15, Object arg16, Object arg17, Object arg18, Object arg19, Object arg20, Object... args) - throws Exception { - return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, - arg16, arg17, arg18, arg19, arg20,args); + throws Exception{ + return fn().invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, + arg16, arg17, arg18, arg19, arg20, args); } static volatile Integer o = 1; -public static void main(String[] args) { +public static void main(String[] args){ - try - { - int n = Integer.parseInt(args[0]); - class Test extends AFn { - int x = 0; + try + { + int n = Integer.parseInt(args[0]); + class Test extends AFn{ + int x = 0; - public Object invoke(Object arg1) throws Exception { - x += o.intValue(); - return this; - } + public Object invoke(Object arg1) throws Exception{ + x += o.intValue(); + return this; + } - public String toString() { - return Integer.toString(x); - } + public String toString(){ + return Integer.toString(x); + } - } + } - Var test = Module.intern("test", "test"); + Var test = Module.intern("test", "test"); - test.bind(new Test()); + test.bind(new Test()); - Random rand; + Random rand; - Object result = 0; + Object result = 0; - rand = new Random(42); - long startTime = System.nanoTime(); + rand = new Random(42); + long startTime = System.nanoTime(); - for (int i = 0; i < n; i++) - result = test.invoke(result); - long estimatedTime = System.nanoTime() - startTime; - System.out.println("val:" + result + ", time: " + estimatedTime / 1000000); + for(int i = 0; i < n; i++) + result = test.invoke(result); + long estimatedTime = System.nanoTime() - startTime; + System.out.println("val:" + result + ", time: " + estimatedTime / 1000000); - rand = new Random(42); - startTime = System.nanoTime(); + rand = new Random(42); + startTime = System.nanoTime(); - for (int i = 0; i < n; i++) - result = ((IFn) test.getValue()).invoke(result); - estimatedTime = System.nanoTime() - startTime; - System.out.println("val:" + result + ", time: " + estimatedTime / 1000000); + for(int i = 0; i < n; i++) + result = ((IFn) test.getValue()).invoke(result); + estimatedTime = System.nanoTime() - startTime; + System.out.println("val:" + result + ", time: " + estimatedTime / 1000000); - } + } - catch (Exception e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } + catch(Exception e) + { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } } } |