Ticket #275: java-jvm-5.patch
File java-jvm-5.patch, 84.9 KB (added by hopscc, 13 years ago) |
---|
-
Source/BackEndObjC/ObjcBackEnd.cobra
77 77 def readSystemTypes is override 78 78 pass 79 79 80 def fix NilableMemberSigs is override80 def fixMemberSigs is override 81 81 pass 82 82 83 83 def installNativeMethods(box as Box, nativeType as NativeType) is override -
Source/Compiler.cobra
134 134 def readSystemTypes is abstract 135 135 """ Read and Load System Types for backend for Compiler to make available""" 136 136 137 def fix NilableMemberSigs is abstract137 def fixMemberSigs is abstract 138 138 """ 139 139 Most backends dont natively support nilablility, this marks/fixes the common backend 140 140 class signatures that should be marked nilable. … … 253 253 def readSystemTypes is override 254 254 pass 255 255 256 def fix NilableMemberSigs is override256 def fixMemberSigs is override 257 257 pass 258 258 259 259 def installNativeMethods(box as Box, nativeType as NativeType) is override … … 1053 1053 if .referenceVerbosity, print '[lre] in _loadReference("[reference]")' 1054 1054 return false 1055 1055 1056 def fix NilableMemberSigs1057 .backEnd.fix NilableMemberSigs1056 def fixMemberSigs 1057 .backEnd.fixMemberSigs 1058 1058 1059 1059 def installNativeMethods(box as Box, nativeType as NativeType) 1060 1060 .backEnd.installNativeMethods(box, nativeType) … … 1354 1354 thing as IContainer? = nil 1355 1355 for name in names 1356 1356 possible = (thing ? ns).declForName(name) 1357 #print name 1357 1358 assert possible, name 1358 1359 if possible inherits IContainer 1359 1360 thing = possible -
Source/Expr.cobra
162 162 body 163 163 return .isKindOf(.compiler.collectionType) or .isKindOf(.compiler.collectionOfType) 164 164 165 def isKindOfNonNil(type as IType) as bool 166 require 167 .type 168 .compiler 169 body 170 return .type.nonNil.isDescendantOf(type) 171 165 172 get isObjectLiteral as bool 166 173 return false 167 174 … … 1408 1415 if arg.canBeAssignedTo(param.type) 1409 1416 arg.contextType = param.type 1410 1417 else 1411 if false1418 if true 1412 1419 print '<> arg = ' stop 1413 1420 arg.writeDeepString 1414 1421 print '<> param = ' stop -
Source/Boxes.cobra
1235 1235 base.init(TokenFix.empty, TokenFix.empty, backend.cobraNameForNativeBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), List<of ITypeProxy>(), nil) 1236 1236 if nativeType.baseType 1237 1237 _baseNode = backend.nativeTypeProxy(nativeType.baseType to !) 1238 else if nativeType.name <> 'Object' 1239 print 'No baseType for [nativeType.name]' 1238 1240 _initNativeType(nativeType) 1239 1241 1240 1242 def addRefFields -
Source/Cobra.Lang/Java/CobraCore.java
9 9 */ 10 10 package cobra.lang; 11 11 12 import java.util.*; 13 12 14 //interface IHasSourceSite { 13 15 // public SourceSite getSourceSite(); 14 16 //} … … 25 27 //public static String getRuntimePlatform() { return "jvm"; } // prop 26 28 public static final String runtimePlatform = "jvm"; 27 29 30 // property willCheckAssert 28 31 public static boolean getWillCheckAssert() { return _willCheckAssert; } 29 32 public static void setWillCheckAssert(boolean b) { _willCheckAssert = b; } 30 33 34 public static List<String> commandLineArgs = new ArrayList<String>(); 35 36 // Compiler inserts calls to this to initialize commandLineArgs 37 public static void _recordCommandLine(String[] args) { 38 commandLineArgs.addAll(java.util.Arrays.asList(args)); 39 StackTraceElement[] stack = Thread.currentThread ().getStackTrace(); 40 StackTraceElement main = stack[stack.length - 1]; 41 String mainClass = main.getClassName(); 42 commandLineArgs.add(0, mainClass); 43 } 44 45 public static void exit(int exitCode) { 46 //""" Exits the process. """ 47 System.exit(exitCode); 48 } 49 50 public static String newLine = System.getProperty("line.separator"); 51 //""" Returns the newline for the current environment/platform. """ 52 31 53 // Property StringMaker techStringMaker 32 54 /* 33 55 * Used by `assert` failures, `trace` statements and .toTechString methods. … … 35 57 static public CobraImp.SimpleStringMaker getTechStringMaker() { return CobraImp._techStringMaker; } 36 58 static public void setTechStringMaker(CobraImp.SimpleStringMaker value) { CobraImp._techStringMaker = value; } 37 59 60 static public String toTechString(Object x) 61 { 62 return CobraImp.toTechString(x); 63 } 64 38 65 public static int noOp(/* allowNull */ Object... args) { 39 66 /* """ 40 67 No operation. Primarily used in Cobra's own test suite to consume a local variable to avoid undesired warnings. -
Source/Cobra.Lang/Java/PkgSig.java
492 492 System.out.printf( "%-30s %s\n", t, "# JavaType"); 493 493 494 494 printIndent(); 495 String pkgName = this.cls.getPackage().getName(); 495 String pkgName = ""; 496 if (this.cls.getPackage() != null) 497 pkgName = this.cls.getPackage().getName(); 496 498 System.out.printf("%-30s %s\n", pkgName, "# package"); 497 499 498 500 // Name of the class(without pkgname), dotNet form for Generic class -
Source/Cobra.Lang/Java/mkjar
1 #! bash1 #!/bin/bash 2 2 # Build script for java sources for cobra 3 3 # Compile java source classes for java cobra RTL 4 4 # copy them and std sig files to Source dir 5 5 6 6 [ -d classes ] || mkdir classes 7 javac -d classes CobraImp.java CobraCore.java Delegate.java 7 [ -d classes/cobra/lang ] && rm -rf classes/cobra/lang/* 8 javac -d classes SourceSite.java CobraImp.java CobraCore.java Delegate.java AssertException.java CobraDirectString.java 8 9 [ $? == 0 ] || exit 9 10 jar cvf CobraLang.jar -C classes . 10 11 [ $? == 0 ] || exit -
Source/Cobra.Lang/Java/DynamicOperationException.java
1 /* 2 * Dynamic Operations Exceptions 3 */ 4 package cobra.lang; 5 6 import java.util.*; 7 8 9 //## Exceptions about dynamic 10 11 public class DynamicOperationException extends RuntimeException 12 { 13 //""" 14 // The base class for all dynamic operation exceptions. 15 //""" 16 17 public DynamicOperationException(String message) { this(message, nil); } 18 public DynamicOperationException(String message, cause as Exception ) {super(message, cause); } 19 } 20 21 class CannotEnumerateException extends DynamicOperationException 22 { 23 public CannotEnumerateException (String message) {this(message, nil); } 24 public CannotEnumerateException (String message, Exception cause) {super(message, cause); } 25 } 26 27 class UnknownMemberException extends DynamicOperationException 28 { 29 protected Object _obj; 30 protected String _name; 31 Class _type; 32 33 public UnknownMemberException(Object obj, String name as String, Class type) { this(obj, name, type, nil);} 34 public UnknownMemberException(Object obj, String name as String, Class type, Exception cause) 35 { 36 super(String.format("obj=%s, name=%s, type=%s", 37 CobraCore.toTechString(obj), CobraCore.toTechString(name), type), 38 cause); 39 this._obj = obj; 40 this._name = name; 41 this.type = type; 42 } 43 } 44 45 /* 46 * Missing, unreadable Member Exceptions 47 * / 48 class CannotReadPropertyException inherits UnknownMemberException 49 50 # CC: axe init()s 51 52 cue init(obj as Object, name as String, type as Type) 53 .init(obj, name, type, nil) 54 55 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 56 base.init(obj, name, type, innerExc) 57 58 59 class CannotWritePropertyException inherits UnknownMemberException 60 61 # CC: axe init()s 62 63 cue init(obj as Object, name as String, type as Type) 64 .init(obj, name, type, nil) 65 66 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 67 base.init(obj, name, type, innerExc) 68 69 70 class CannotSliceTypeException inherits UnknownMemberException 71 72 # CC: axe init()s 73 74 cue init(obj as Object, name as String, type as Type) 75 .init(obj, name, type, nil) 76 77 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 78 base.init(obj, name, type, innerExc) 79 80 81 class CannotInTypeException inherits UnknownMemberException 82 83 # CC: axe init()s 84 85 cue init(obj as Object, name as String, type as Type) 86 .init(obj, name, type, nil) 87 88 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 89 base.init(obj, name, type, innerExc) 90 91 92 class CannotCompareException inherits DynamicOperationException 93 94 var _a 95 var _b 96 97 cue init(a, b) 98 .init(a, b, nil) 99 100 cue init(a, b, innerExc as Exception?) 101 base.init('a=[a], b=[b]', innerExc) 102 #base.init('a=[CobraCore.toTechString(a)], a.getType=[a.getType.name], b=[CobraCore.toTechString(b)], b.getType=[b.getType.name]', innerExc) 103 _a = a 104 _b = b 105 106 107 108 */ -
Source/Cobra.Lang/Java/SourceSite.java
1 /* 2 * Sourcesite.java 3 */ 4 5 package cobra.lang; 6 7 import java.io.*; 8 9 public class SourceSite { 10 /* 11 * See Cobra.Lang.SourceSite.cobra 12 * 13 * A SourceSite instance captures the source location of a statement or expression, as in the 14 * filename, line number, declaring class name, method name and run-time object. The Cobra 15 * compiler generates SourceSite instances in various circumstances; for example, the `trace` 16 * statement. 17 */ 18 19 protected String _fileName; 20 protected int _lineNum; 21 protected String _className; 22 protected String _memberName; 23 protected Object _object; 24 25 public SourceSite(String fileName, int lineNum, String className, String memberName, Object obj ) { 26 this._fileName = fileName; 27 this._lineNum = lineNum; 28 this._className = className; 29 this._memberName = memberName; 30 this._object = obj; 31 } 32 33 @Override 34 public String toString() { 35 // test 36 // si = SourceSite('Foo.cobra', 10, 'Object', 'bar', BadToString()) 37 // assert 'Foo.cobra' in si.toString 38 // assert 'exception on' in si.toString 39 Object obj; 40 try { 41 obj = CobraCore.toTechString(this._object); 42 } 43 catch (Exception exc) { 44 obj = String.format("(.toTechString or .toString exception on a %s: %s: %s)", _object.getClass().getName(), exc.getClass().getName(), exc.getMessage() ); 45 } 46 return String.format("%s:%d in %s.%s for object %s", this._fileName, this._lineNum, this._className,this._memberName, obj); 47 } 48 49 // Property fileName 50 public String getFileName() { return this._fileName; } 51 52 // Property lineNum 53 public int getLineNum() { return this._lineNum; } 54 55 // Property className 56 public String getClassName() { return this._className; } 57 58 // Property memberName 59 public String getMemberName() { return this._memberName; } 60 61 // Property object 62 public Object getObject() { return this._object; } 63 64 // Property runTimeClassName 65 public String getRunTimeClassname() { return this._object.getClass().getName(); } 66 67 public String oneLiner(String sep ) { 68 return oneLiner(sep, true); 69 } 70 71 public String oneLiner(String sep, boolean willOutputDirectoryNames) { 72 //test 73 // si = SourceSite('Foo.cobra', 10, 'Object', 'bar', Object()) 74 // assert si.oneLiner('; ', true) == 'at Foo.cobra:10; in Object.bar' 75 // si = SourceSite('Foo.cobra', 10, 'Foo', 'bar', Object()) 76 // assert si.oneLiner('; ', true) == 'at Foo.cobra:10; in Foo.bar; subclass Object' 77 //body 78 StringBuilder sb = new StringBuilder(); 79 String fileName = this._fileName; 80 if ( _fileName.length()>0 && ! willOutputDirectoryNames) 81 fileName = (new File((this._fileName)).getName()); 82 sb.append( String.format("at %s:%d%sin %s.%s", 83 fileName, this._lineNum, sep, this._className, this._memberName)); 84 if ( ! (this._object instanceof Class)) { 85 String name = this.getClass().getName(); 86 if ( name != _className) 87 sb.append( String.format("%ssubclass %s", sep, name)); 88 } 89 return sb.toString(); 90 } 91 92 public String htmlForAt() { 93 return htmlForAtArgs(this._fileName, this._lineNum); 94 } 95 96 static public String htmlForAtArgs(String fileName, int lineNum ) { 97 //""" 98 // Returns the HTML for the row labeled "at" in the Cobra Exception Report. 99 // This will be an actual link if the environment variable COBRA_EDIT_LINK is set. 100 // That's what enables clicking on sources in the report to jump to their location in a text editor. 101 //""" 102 File f = new File(fileName); 103 String baseName = f.getName(); 104 String dirName = f.getParent(); 105 if (dirName.length() != 0) 106 dirName = " in " + dirName; 107 String s = "line " + lineNum + "of " + baseName + dirName; 108 String editLink = System.getenv("COBRA_EDIT_LINK"); 109 if (editLink != null && editLink.length() >0) { 110 editLink = editLink.replace("FILE", fileName); // # TODO: url encode the file name 111 editLink = editLink.replace("LINE", "" + lineNum); 112 s = "<a href=\""+ editLink + "\">[s]</a>"; 113 } 114 return s; 115 } 116 } -
Source/Cobra.Lang/Java/mkjarOnly
1 #!/bin/bash 2 # Build script for java sources for cobra 3 # Compile java source classes for java cobra RTL 4 # copy them and std sig files to Source dir 5 6 [ -d classes ] || mkdir classes 7 [ -d classes/cobra/lang ] && rm -rf classes/cobra/lang/* 8 javac -d classes SourceSite.java CobraImp.java CobraCore.java Delegate.java AssertException.java CobraDirectString.java 9 [ $? == 0 ] || exit 10 jar cvf CobraLang.jar -C classes . 11 [ $? == 0 ] || exit 12 cp CobraLang.jar ../.. 13 14 #echo 'pkgSig for CobraLang.jar' 15 #java -cp '.;CobraLang.jar' PkgSig -j CobraLang.jar > CobraLang.jar.sig 16 #cp CobraLang.jar.sig ../.. 17 18 19 ## assume rt.jar, java.util and java.lang sigfiles already exist and are static 20 #cp CobraLang.jar.sig rt.jar.sig java.util.sig java.lang.sig ../.. -
Source/Cobra.Lang/Java/CobraImp.java
17 17 18 18 public String makeString(String[] args) { 19 19 StringBuilder sb = new StringBuilder(); 20 21 20 for (Object arg : args) 21 sb.append(arg); 22 22 return sb.toString(); 23 23 } 24 24 public String makeString(String s) { 25 25 return s; 26 26 } 27 27 public String makeString(int i) { 28 28 return new Integer(i).toString(); 29 29 } 30 30 31 public String makeString(char i) { 32 return new Character(i).toString(); 33 } 34 31 35 public String makeString(Object... args) { 32 36 StringBuilder sb = new StringBuilder(); 33 34 37 for (Object arg : args) 38 sb.append(arg.toString()); 35 39 return sb.toString(); 36 40 } 37 41 } 38 42 //static public StringMaker _printStringMaker = new StringMaker(); 39 43 static public SimpleStringMaker _printStringMaker = new SimpleStringMaker(); 40 44 static public SimpleStringMaker _techStringMaker = new SimpleStringMaker(); 41 45 42 46 static { 43 44 45 46 47 48 47 // _printToStack = new Stack<TextWriter>(); 48 // PushPrintTo(Console.Out); 49 // _printStringMaker = new PrintStringMaker(); 50 // _techStringMaker = new TechStringMaker(); 51 // PromoteNumerics = NumericTypeInfo.PromoteNumerics; 52 } 49 53 50 54 static public void printLine() { 51 55 //_printToStack.Peek().WriteLine(); 52 56 System.out.println(); 53 57 } 54 58 55 59 static public void printLine(String s) { 56 //_printToStack.Peek().WriteLine(s);60 // _printToStack.Peek().WriteLine(s); 57 61 System.out.println(s); 58 62 } 59 63 … … 61 65 } 62 66 63 67 static public void printStop(String s) { 64 //_printToStack.Peek().Write(s);68 // _printToStack.Peek().Write(s); 65 69 System.out.print(s); 66 70 } 67 71 … … 73 77 return s; 74 78 } 75 79 80 static public Object checkNonNil(Object obj, String sourceCode, Object value, /* SourceSite */ String fileName, int lineNum, String className, String memberName, Object thiss) 81 { 82 // used for "x to !" and "someNilable to SomethingNotNilable" 83 if (value == null) { 84 List<Object> l = new ArrayList<Object>(); 85 l.add(0); 86 l.add(sourceCode); 87 l.add(value); 88 throw new NonNilCastException( new SourceSite(fileName, lineNum, className, memberName, thiss), 89 l, obj, null ); 90 } 91 return value; 92 } 76 93 94 /* 95 static public String toTechString(boolean x) 96 { 97 return x ? "true" : "false"; 98 } 77 99 100 static public String toTechString(byte x) 101 { 102 return "" + x; 103 } 104 static public String toTechString(int x) 105 { 106 return "" + x; 107 } 108 static public String toTechString(short x) 109 { 110 return "" + x; 111 } 112 static public String toTechString(long x) 113 { 114 return "" + x; 115 } 116 */ 117 static public String toTechString(Object x) 118 { 119 if (x == null) 120 return "nil"; 121 if (x instanceof Boolean) 122 return String.format("%b", (Boolean)x ? "true" : "false"); 123 if (x instanceof String) 124 { // TODO: handle double backslash 125 String s = (String)x; 126 s = s.replace("\n", "\\n"); 127 s = s.replace("\r", "\\r"); 128 s = s.replace("\t", "\\t"); 129 s = "'" + s + "'"; // TODO: could be more sophisticated with respect to ' and " 130 return s; 131 } 132 if (x instanceof java.util.List) 133 { 134 // TODO: should not go into infinite loop for circular references 135 StringBuilder sb = new StringBuilder(); 136 sb.append(x.getClass().getName() ); 137 sb.append("["); 138 String sep = ""; 139 for (Object item : (java.util.List)x) 140 { 141 sb.append(sep); 142 sb.append( toTechString(item) ); 143 sep = ", "; 144 } 145 sb.append("]"); 146 return sb.toString(); 147 } 148 if (x instanceof java.util.Map) 149 { 150 // TODO: should not go into infinite loop for circular references 151 Map idict = (java.util.Map)x; 152 StringBuilder sb = new StringBuilder(); 153 sb.append( x.getClass().getName()); 154 sb.append("{"); 155 String sep = ""; 156 for (Object key : idict.keySet()) { 157 sb.append( String.format("$1s%2$s: %3$s", sep, toTechString(key), toTechString(idict.get(key))) ); 158 sep = ", "; 159 } 160 sb.append("}"); 161 return sb.toString(); 162 } 163 if (x instanceof java.lang.Iterable) 164 { 165 // TODO: should not go into infinite loop for circular references 166 java.lang.Iterable iter = (java.lang.Iterable)x; 167 StringBuilder sb = new StringBuilder(); 168 sb.append(x.getClass().getName()); 169 sb.append("["); 170 String sep = ""; 171 for (Object item : iter) 172 { 173 sb.append(String.format("%1$s%2$s", sep, toTechString(item))); 174 sep = ", "; 175 } 176 sb.append("]"); 177 return sb.toString(); 178 } 179 if (x instanceof java.lang.Enum) 180 { 181 return x.getClass().getName() + "." + x.toString() + " enum"; 182 } 183 184 // TODO: For StringBuilder, return StringBuilder'aoeu' 185 String tts = x.toString(); 186 if (isInterestingClass(x.getClass())) 187 { 188 String typeName = x.getClass().getName(); 189 if (!tts.contains(typeName) && !(x instanceof CobraDirectString)) 190 tts = String.format("%1$s (%2$s)", tts, typeName); 191 } 192 return tts; 193 } 194 195 static boolean isInterestingClass(Class t) 196 { 197 if (t == java.lang.Integer.class) 198 return false; 199 if (t == java.lang.Character.class) 200 return false; 201 if (t == java.lang.Boolean.class) 202 return false; 203 return true; 204 } 78 205 206 207 79 208 /* IsTrue mappings */ 80 209 static public boolean isTrue(char c) {return c!='\0';} 81 210 82 211 static public boolean isTrue(Character c) {return c!=null && c.charValue()!='\0';} 83 212 84 static public boolean isTrue(int i) {return i!=0;}213 static public boolean isTrue(int i) {return i!=0; } 85 214 86 215 static public boolean isTrue(Integer i) {return i!=null && i.intValue() !=0;} 87 216 88 217 static public boolean isTrue(long i) {return i!=0;} 89 218 90 91 219 static public boolean isTrue(Long i) {return i!=null && i.longValue()!=0;} 220 static public boolean isTrue(Boolean b) {return b!=null && b.booleanValue();} 92 221 93 222 /* 94 223 static public boolean IsTrue(decimal d) {return d!=0;} 95 static public boolean IsTrue(decimal? d) {return d!=null && d.Value!=0; 224 static public boolean IsTrue(decimal? d) {return d!=null && d.Value!=0; } 96 225 */ 97 226 static public boolean isTrue(float f) {return f!=0;} 98 227 99 228 static public boolean isTrue(Float f) {return f!=null && f.floatValue()!=0.0;} 100 229 101 230 static public boolean isTrue(double d) {return d!=0; } 102 231 103 232 static public boolean isTrue(Double d) {return d!=null && d.doubleValue() !=0;} 104 233 105 234 static public boolean isTrue(String s) {return s!=null; } 106 235 107 236 static public boolean isTrue(java.util.Collection c) {return c!=null; } 108 237 109 static public boolean isTrue(Object x) { //rely on unboxing?? 110 if (x==null) 111 return false; 112 if (x instanceof Boolean) 113 return (boolean)(Boolean)x; 114 if (x.equals(0)) 115 return false; 116 if (x instanceof Character) 117 return (Character)x != '\0'; 118 //if (x instanceof decimal) 119 // return (decimal)x!=0; // can't believe x.Equals(0) above doesn't work for decimal. *sigh* 120 if (x instanceof Double) 121 return (Double)x!=0; 122 if (x instanceof Float) 123 return (Float)x!=0; 124 return true; 125 } 126 238 static public boolean isTrue(Object x) { //rely on unboxing?? 239 if (x==null) 240 return false; 241 if (x instanceof Boolean) 242 return (boolean)(Boolean)x; 243 if (x.equals(0)) 244 return false; 245 if (x instanceof Character) 246 return (Character)x != '\0'; 247 //if (x instanceof decimal) 248 // return (decimal)x!=0; // can't believe x.Equals(0) above doesn't work for decimal. *sigh* 249 if (x instanceof Double) 250 return (Double)x!=0; 251 if (x instanceof Float) 252 return (Float)x!=0; 253 return true; 254 } 127 255 256 static public boolean referenceEquals(Object o, Object o1) { return o == o1; } 257 258 128 259 } 129 260 -
Source/Cobra.Lang/Java/mkjarAll
5 5 6 6 echo 'making RTL from java sources' 7 7 [ -d classes ] || mkdir classes 8 javac -d classes CobraImp.java CobraCore.java Delegate.java 8 [ -d classes/cobra/lang ] && rm -rf classes/cobra/lang/* 9 javac -d classes SourceSite.java CobraImp.java CobraCore.java Delegate.java AssertException.java CobraDirectString.java 9 10 [ $? == 0 ] || exit 10 11 jar cvf CobraLang.jar -C classes . 11 12 [ $? == 0 ] || exit -
Source/Cobra.Lang/Java/read-me.text
19 19 - a script to build and copy the various supporting pieces the java backend needs to the compiler Source directory. 20 20 21 21 22 The base java version supported is 1.6.22 The base java version supported is currently 1.6. 23 23 This one specifically 24 24 java version "1.6.0_24" 25 25 Java(TM) SE Runtime Environment (build 1.6.0_24-b07) 26 26 Java HotSpot(TM) Client VM (build 19.1-b02, mixed mode, sharing) 27 28 This will move up to at least 1.7 as the port/code generation progresses 29 and will probably stabilise on 1.8 eventually. 27 30 28 31 = Caveats = 29 32 … … 58 61 happens, good for you. 59 62 This is what you will need to do 60 63 61 1) Apply the patches providing the java backend to the Source tree 64 1) If necessary 65 Apply the patches providing the java backend to the Source tree 62 66 - get the modified compiler subsequently rebuilt 67 68 As on Nov 2011 (and touch wood) all the jvm patches posted have been 69 applied to the code repository source so it should be enough to pull down the latest compiler source and build it. 70 63 71 Patch should be on the cobra website http://cobra-language.com 64 72 Ticket 275: More support for java backend 65 73 http://cobra-language.com/trac/cobra/ticket/275 66 74 67 2) Ensure java and javac executables (1.6 ) are in your PATH and work.75 2) Ensure java and javac executables (1.6 or later) are in your PATH and work. 68 76 69 77 3) Go into this dir and run ./mkJarAll 70 78 ( its a bash script - you will need bash or to port the script, 71 or run the command contents manually) - this builds the 72 tool and uses that to create the class description info and copies73 itto the right places in the cobra source tree)79 or run the command contents manually) - this builds the cobra RTL and 80 package signature tool and uses that to create the class description info and copies 81 them to the right places in the cobra source tree) 74 82 4) find a test cobra script and compile it 75 83 76 84 - How to build and run a cobra program generating a java app - … … 82 90 -kif - leave the generated java files around after compilation 83 91 file.cobra - the cobra source file to compile 84 92 85 If you are lucky you' dll get a whole lot of compiler output at the end of93 If you are lucky you'll get a whole lot of compiler output at the end of 86 94 which you'll see a javac invocation followed by a successful execution 87 95 of the translated cobra program. 88 96 … … 100 108 Maybe more but thats what I've tried so far) 101 109 We seem to be understanding references to java classes in library (jar) files. 102 110 111 Dec-2011 - building and running more simple programs 112 (Up to about 080-* of the files in Tests/100-*) 113 Have properties and Indexers, Casting, reading Commandline ... 114 103 115 - Other - 104 116 105 117 Post issues/questions/comments/etc if you have them to Cobra Programming Language Forum -
Source/Node.cobra
845 845 tag = 'mi' # for minimal 846 846 847 847 sb = StringBuilder('[.getType.name]-[tag]([.serialNum]') 848 848 indSep = ',' 849 if Environment.getEnvironmentVariable('COBRA_INDENT_TECHSTRING') 850 indSep = ',\n\t ' 849 851 if doMin 850 852 __curFields = List<of Field>() 851 853 try 852 854 .addMinFields 853 855 for field in __curFields 854 856 if field.name.length 855 sb.append(' ,[field.name]=[field.value]')857 sb.append('[indSep] [field.name]=[field.value]') 856 858 else 857 sb.append(' ,[field.value]')859 sb.append('[indSep] [field.value]') 858 860 finally 859 861 __curFields = nil 860 862 … … 868 870 value = (field.value to Node).minimalString 869 871 else 870 872 value = field.value 871 sb.append(' ,[field.name]=[value]')873 sb.append('[indSep] [field.name]=[value]') 872 874 finally 873 875 __curFields = nil 874 876 … … 882 884 value = (field.value to Node).minimalString 883 885 else 884 886 value = field.value 885 sb.append(' ,[field.name]=[field.value]')887 sb.append('[indSep] [field.name]=[field.value]') 886 888 finally 887 889 __curFields = nil 888 890 -
Source/Phases/BindInterfacePhase.cobra
13 13 14 14 def innerRun is override 15 15 c = .compiler 16 c.fix NilableMemberSigs16 c.fixMemberSigs 17 17 for basicType in c.basicTypes 18 18 basicType.bindInt 19 19 c.objectType.bindInt -
Source/Indexer.cobra
16 16 cue init(token as IToken, idToken as IToken, box as Box, name as String, paramsList as List<of Param>, returnTypeOrNode as INode, isNames as List<of String>, attribs as AttributeList, docString as String) 17 17 base.init(token, idToken, box, name, returnTypeOrNode, isNames, attribs, docString) 18 18 _params = paramsList 19 19 20 20 get params as IList<of Param> is override 21 21 return _params 22 22 -
Source/BackEndClr/ClrBackEnd.cobra
139 139 #.compiler.readAssembly(t.assembly) # System.dll 140 140 .compiler.clrReadAssembly(t.assembly) # System.dll 141 141 142 def fix NilableMemberSigs is override142 def fixMemberSigs is override 143 143 .compiler.dotNetFixNilableMemberSigs # in ScanClrType 144 144 145 145 # Types -
Source/CobraParser.cobra
453 453 .throwError('Compiler directive "number": unrecognized type "[typeName.text]". Must be one of "decimal", "float", "float32" or "float64".') 454 454 .expect('EOL') 455 455 .backEnd.compiler.numberTypeName = typeName.text 456 on 'platform' 457 plaf = .grab 458 if not plaf.text.isOneOf('any.portable.clr.jvm.objc.') 459 .throwError('Compiler directive "platform": unrecognized platform name "[plaf.text]". Must be one of "portable" or "any", "clr", "jvm" or "objc".') 460 .expect('EOL') 461 if plaf.text in[ 'portable', 'any'] 462 pass 463 else if not .backEnd.name.endsWith(plaf.text) 464 .throwError('This file is marked as platform specific to "[plaf.text]" but this compile is using "[.backEnd.name]" backend.') 456 465 on 'ref' 457 466 pathToken = .grab 458 467 if not pathToken.which.isOneOf('ID.STRING_SINGLE.STRING_DOUBLE.') -
Source/Types.cobra
1340 1340 1341 1341 def isDescendantOf(type as IType) as bool 1342 1342 return base.isDescendantOf(type) and _wrappedType.isDescendantOf(type) 1343 1343 # shouldnt the above conjunction be an 'or' ?? 1344 1344 1345 def isEquatableTo(b as IType) as bool is override 1345 1346 if b inherits NilType 1346 1347 return true -
Source/BackEndJvm/JvmJarSig.cobra
24 24 shared 25 25 var classByNameCache = Dictionary<of String, JavaClassType>() 26 26 """All classes found in all jars keyed by canonical/full name.""" 27 27 28 29 var nameRemaps = { 30 'java.lang.Decimal' : 'java.lang.Double', # BigDecimal eventually with (lotta) codegen support 31 'java.lang.UByte' : 'java.lang.Short', 32 'java.lang.UShort' : 'java.lang.Integer', 33 'java.lang.UInteger': 'java.lang.Long', 34 'java.lang.ULong' : 'java.lang.Long', 35 } 36 """ 37 Remap unique virtualised java class name to an actual existing Java class name. 38 """ 39 28 40 def lookupClassByCobraName(fullCobraName as String) as JavaClassType 29 41 """ 30 This is the only way to access the JarSig classCache contents from outside this file.42 This is intended to be the only way to access the JarSig classCache contents from outside this file. 31 43 """ 32 44 assert fullCobraName[0].isUpper 45 #fullCobraName = .nameRemaps.get(fullCobraName, fullCobraName) 33 46 parts = fullCobraName.split('.') 34 47 for i in 0: parts.length-1 35 48 parts[i] = parts[i][0].toLower.toString + parts[i][1:] 36 49 fullName = parts.join('.') 37 50 #print 'Lookup "[fullCobraName]" as "[fullName]"' 51 if not JarSig.classByNameCache.containsKey(fullName) # dbg 52 print 'Class [fullName] not in JarSig ClassName cache' 53 throw Exception('Cannot find class [fullName]') 38 54 return JarSig.classByNameCache[fullName] 39 55 40 56 def lookupClass(fullName as String) as JavaClassType 41 """ Lookup class by full/canonicalName.""" 57 """ 58 Lookup class by full/canonicalName. 59 Used only for class resolution from within this file. 60 """ 42 61 if not JarSig.classByNameCache.containsKey(fullName) 43 62 if fullName.startsWith(r'[') # [a.b.c; 44 63 .addArrayClass(fullName) … … 78 97 print 'Unknown arrayName [elName]' 79 98 assert false, 'arrayName [elName]' 80 99 if not JarSig.classByNameCache.containsKey(elName) 81 print 'Dbg: class "[elName]" not in classByNameCache "[aName]"' 100 if elName.contains('<') # a generic 101 elNameRaw = elName.before('<') 102 if JarSig.classByNameCache.containsKey(elNameRaw) 103 elName = elNameRaw # rawType is superclass of Generic so find that 104 else 105 print 'Dbg: neither class "[elName]" nor class "[elNameRaw]" are in classByNameCache - element for "[aName]"' 106 else 107 print 'Dbg: class "[elName]" not in classByNameCache - element for "[aName]"' 82 108 #elType = JarSig.classByNameCache[elName] 83 109 elType = JarSig.lookupClass(elName) 84 110 arrayCls = JavaClassType(aName, elType) # ArrayType … … 209 235 #_javaTypes.add(l) 210 236 JarSig.classByNameCache['float'] = JarSig.classByNameCache['java.lang.Float'] 211 237 JarSig.classByNameCache['double'] = JarSig.classByNameCache['java.lang.Double'] 238 239 # these name remaps will probably need some codegen special handling. 240 _dupVirtuals 241 _nonGenericCommon 212 242 243 def _dupVirtuals 244 for dupName in .nameRemaps.keys 245 dupOf = .nameRemaps[dupName] 246 _dupClassTo(dupOf, dupName) 247 248 def _nonGenericCommon 249 #pass 250 # 'java.util.Collection' : 'java.util.Collection<Object>', 251 #_dupClassTo( 'java.util.Collection', 'java.util.Collection<Object>') 252 _makeGenericInstance('java.util.Collection<Object>') # for ICollection/Java.Util.Collection<of Object> 253 # probably others yet 254 255 def _dupClassTo(dupOfName as String, asName as String) 256 ct = JarSig.classByNameCache[dupOfName] 257 parts = asName.split('.') 258 name = parts[parts.length-1] 259 package = parts[0:-1].join('.') # all but last 260 ct = ct.copy(name, package) 261 JarSig.classByNameCache[asName] = ct 262 _javaTypes.add(ct) 213 263 214 264 def _makeGenericInstance(fullName as String) 265 # cached AND exposed to namespace 266 assert fullName.contains('<') 267 .addGenericInstClass(fullName) 268 giCls = JarSig.classByNameCache[fullName] 269 print giCls.canonicalName 270 _javaTypes.add(giCls) 271 #_registerClassType(giCls) 272 215 273 def getExportedTypes as JavaClassType* 216 274 return _javaTypes 217 275 … … 223 281 224 282 # 225 283 # Below are classes describing JavaTypes (class), JavaFields, Java Ctors and JavaMethods 226 # They are temporary placeholders until canget a native implementation and direct access to Java RTL equivalents.284 # They are temporary placeholders until get a native implementation and direct access to Java RTL equivalents. 227 285 228 286 enum JavaType 229 287 NoType, JavaClass, JavaInterface, JavaEnum, GenericParam … … 260 318 var _props as List<of JavaFieldInfo> = JavaClassType._emptyFieldList # JavaFieldInfo* 261 319 var _ctors as List<of JavaCtorInfo> = JavaClassType._emptyCtorList # JavaCtorInfo* 262 320 var _methods as List<of JavaMethodInfo> = JavaClassType._emptyMethodList # JavaMethodInfo* 321 var _indexer as JavaFieldInfo? 322 263 323 264 324 # TODO split these out as subclass 265 325 var _isGenericDefn = false … … 385 445 jct._props = propList 386 446 jct._ctors = ctorList 387 447 jct._methods = methodList 448 jct._fixIdxr 388 449 return jct 389 450 390 451 def _parseList(et as String) as List<of String> is shared … … 439 500 return methodName[2:] 440 501 return nil 441 502 442 # indexer: get<Propname> and has params - first param in paramList is index (retType is Property Type) 443 # or set<PropName> and more than value in paramList, 1st parameter is index and second is value to set. 444 # hops: this isnt goanna work - too many false positives 445 # may work to hard case Collections, Lists and special case Maps... recognise annotation for user written code 446 def isIndexer(methodName as String, method as JavaMethodInfo, isSetProp) as bool is shared 447 if methodName.startsWith('is') 448 return false 449 assert methodName.startsWith('get') or methodName.startsWith('set') 450 isGetProp = not isSetProp 451 return (isGetProp and method.paramNames.count) or (isSetProp and method.paramNames.count > 1) 452 453 def _genProp(method as JavaMethodInfo, propName as String, propList as List<of JavaFieldInfo>, props as Dictionary<of String, JavaFieldInfo>) as JavaFieldInfo is shared 454 """ Create or update property fm getter/setter method and update given List and Dict. """ 503 # unused old obsolete 504 def _genProp0(method as JavaMethodInfo, propName as String, propList as List<of JavaFieldInfo>, props as Dictionary<of String, JavaFieldInfo>) as JavaFieldInfo is shared 505 """ Create or update property fm getter/setter method and update the given List and Dict. """ 455 506 assert method.name.startsWith('get') or method.name.startsWith('set') or method.name.startsWith('is') 456 507 isSetProp = method.name.startsWith('set') 457 508 isGetProp = not isSetProp … … 462 513 prop = JavaFieldInfo() # JavaPropInfo 463 514 prop.name = propName 464 515 prop.isProp = true 465 #prop.isIndexer = .isIndexer(method.name, method, isSetProp) 466 prop.isIndexer = false # TODO support indexers 516 prop.isIndexer = false 467 517 prop.isReadable = prop.isWritable = false 468 518 props[propName] = prop 469 519 propList.add(prop) … … 486 536 assert prop.typeName.length 487 537 return prop 488 538 539 def _genProp(method as JavaMethodInfo, propName as String, propList as List<of JavaFieldInfo>, props as Dictionary<of String, JavaFieldInfo>) as JavaFieldInfo is shared 540 """ Create or update property fm getter/setter method and update the given List and Dict. """ 541 assert method.name.startsWith('get') or method.name.startsWith('set') or method.name.startsWith('is') 542 isSetProp = method.name.startsWith('set') 543 isGetProp = not isSetProp 544 #print method.name, propName 545 if not props.containsKey(propName) # No existing property 546 prop = _genAProp(propName, if(isGetProp, method, nil), if(isSetProp, method, nil), false) 547 props[propName] = prop 548 propList.add(prop) 549 #print '-- new Prop' 550 else 551 prop = props[propName] 552 if isGetProp 553 prop.isReadable = true 554 prop.getter = method 555 if not prop.typeName.length and method.returnTypeName.length 556 prop.typeName = method.returnTypeName 557 #prop.name0 = method.name 558 #print '-- isGetProp' 559 else #isSetProp 560 prop.isWritable = true 561 prop.setter = method 562 #print '-- isSetProp' 563 if not prop.typeName.length and method.paramNames.count 564 prop.typeName = method.paramNames[0] 565 assert prop.name.length 566 assert prop.typeName.length 567 return prop 568 569 def _genAProp(name as String, getMethod as JavaMethodInfo?, setMethod as JavaMethodInfo?, isIndexer as bool ) as JavaFieldInfo is shared 570 """ Create a property given either or both getter/setter methods. """ 571 prop = JavaFieldInfo() # JavaPropInfo 572 prop.name = name 573 prop.isProp = true 574 prop.isIndexer = isIndexer 575 if getMethod 576 prop.isReadable = true 577 prop.getter = getMethod 578 if getMethod.returnTypeName.length, prop.typeName = getMethod.returnTypeName 579 getMethod.prop = prop 580 if not prop.modifiers.count or not prop.modifiers[0].length, prop.modifiers = getMethod.modifiers 581 if not prop.attributes.count, prop.attributes = getMethod.attributes 582 if setMethod 583 prop.isWritable = true 584 prop.setter = setMethod 585 if not prop.typeName.length 586 if isIndexer 587 if setMethod.paramNames.count > 1, prop.typeName = setMethod.paramNames[1] 588 else 589 if setMethod.paramNames.count, prop.typeName = setMethod.paramNames[0] 590 setMethod.prop = prop 591 if not prop.modifiers.count or not prop.modifiers[0].length, prop.modifiers = setMethod.modifiers 592 if not prop.attributes.count, prop.attributes = setMethod.attributes 593 assert prop.name.length 594 assert prop.typeName.length 595 return prop 596 597 598 # support Indexers on Strings and things supporting (java.util.) Map and List Interfaces 599 def _fixIdxr 600 # assumed Default name for indexer methods 601 getterName, setterName = 'getItem', 'setItem' 602 # special case naming weirdnesses of Java lib classes 603 if .canonicalName == 'java.lang.String' 604 getterName, setterName = 'charAt', '' 605 else 606 for ifcName in .interfaceNames # TODO also chase up interface inheritance tree 607 if ifcName.startsWith('java.util.List') 608 getterName, setterName = 'get', 'set' 609 else if ifcName.startsWith('java.util.Map') 610 getterName, setterName = 'get', 'put' 611 612 #TODO also check for specially annotated methods 613 614 assert getterName.length 615 getMethod, setMethod = _lookForMethods(getterName, setterName) 616 if getMethod or setMethod 617 idxrProp = _genAProp('_synthesizedIdxr', getMethod, setMethod, true) 618 _props.add(idxrProp) 619 _indexer = idxrProp 620 print 'dbg: [.canonicalName] has IndexerMethods [getterName] and [setterName] ' 621 #else 622 # print 'dbg: No IndexerMethods [getterName]/[setterName] on [.canonicalName]' 623 624 def _lookForMethods( getterName as String, setterName as String) as List<of JavaMethodInfo?> 625 getter as JavaMethodInfo? = nil 626 setter as JavaMethodInfo? = nil 627 for m in _methods 628 if m.name == getterName, getter = m 629 if m.name == setterName, setter = m 630 return [getter, setter] 631 632 489 633 cue init(name as String, pkg as String, type as JavaType, super as String, ifcs as List<of String>, modifiers as List<of String> ) 490 634 """Create a normal Class or GenericClass Defn. MyClass or MyClass<T>""" 491 635 base.init … … 810 954 get props from var 811 955 get ctors from var 812 956 get methods from var 957 get indexer from var 813 958 814 959 #dbg 815 960 def toMinString as String -
Source/BackEndJvm/JvmType.cobra
5 5 6 6 class JvmNativeType inherits NativeType 7 7 8 shared 9 def nativeType(t0 as IType?) as JavaClassType? 10 """Obtain Jvm backEnd Native type from given IType (nonnil Box).""" 11 assert t0 12 t = t0 to ! 13 if t inherits Box 14 tn = t.nativeType 15 if tn 16 assert tn inherits JvmNativeType 17 return (tn to JvmNativeType).backEndType 18 return nil 19 8 20 var _type as JavaClassType # java.lang.Class eventually 9 21 var nestedName as String? 10 22 23 11 24 cue init(type as JavaClassType) 12 25 base.init 13 26 _type = type … … 51 64 get isSystemTypeClass as bool is override 52 65 return /# _type and #/ .fullName == 'java.lang.Class' 53 66 67 def toString as String is override 68 return 'JvmNativeType([_type])' 69 70 def toTechString as String 71 return .toString 54 72 55 73 class JvmTypeProxy inherits NativeTypeProxy 56 74 """ … … 83 101 84 102 def cobraNameForJvmBoxName(name as String) as String 85 103 """ 86 Assu nmed we've mangled java generics typenames a la .Net ( i.e TypeName`<nGenericTypeParams>)104 Assumed we've mangled java generics typenames a la .Net ( i.e TypeName`<nGenericTypeParams>) 87 105 Returns 'Foo' for 'Foo' and 'Foo<of,>' for 'Foo`2' 88 106 Works on generic and non-generic classes, structs and interfaces. 89 107 Does *not* work for arrays etc. … … 105 123 106 124 cue init(nativeType as NativeType) 107 125 .init((nativeType to JvmNativeType).backEndType) 108 126 109 127 cue init(jvmType as JavaClassType) 110 128 base.init 111 129 _jvmType = jvmType … … 194 212 .throwError(msg) 195 213 return .compiler.intType # CC: to make C# code gen happy. 196 214 215 # make dict same as PrimitiveTypesDict but keyed by dynamic so not typed to nativeType/JavaClassType 216 # and set to Compiler. 197 217 def _initPrimToITypeCache 198 218 typeToIType = _makePrimitiveTypesDict 199 219 jvmPrimitiveToIType = Dictionary<of dynamic, IType>() … … 201 221 jvmPrimitiveToIType[key] = typeToIType[key] 202 222 (.compiler to Compiler).primitiveCache = jvmPrimitiveToIType #to ! 203 223 224 # primitiveTypes java/nativeClassType: cobraBasicType 225 # like Byte: IntType(signed,8), ... Long: IntType(signed, 64) 226 # implies 1:1 nativeClassType: cobraBasicType - needs fixing 204 227 def _makePrimitiveTypesDict as IDictionary<of JavaClassType, IType> 205 228 primitiveToIType = Dictionary<of JavaClassType, IType>() 206 229 for bt in .compiler.basicTypes … … 208 231 # lookup by qualified name (includes translation) and pull out (jvm) NativeType 209 232 key = (.compiler.nativeType((bt.systemAliasProxy to LibraryTypeProxy).qualifiedName) to JvmNativeType).backEndType 210 233 primitiveToIType[key] = bt 234 #print '<.', key.name, bt 235 #print '<..', primitiveToIType.count 211 236 assert primitiveToIType.count == 0 or primitiveToIType.count >=8 212 237 return primitiveToIType 213 238 -
Source/BackEndJvm/to-do.text
1 1 = Java Backend Gen TODO = 2 2 3 Require Base version Java to be java7 4 gain strings in case stmt for free (!) 5 6 3 7 include-tests:no - remove Test invocation call 4 8 5 9 … … 52 56 codegen for props: 'propName' -> getPropName (DONE) 53 57 setPropName convert propName = a.b.c -> setPropName(a.b.c) (DONE - minimally at least) 54 58 59 codegen for is<bool> property accessor isPropName 60 61 Indexers: 55 62 AutoMap map indexers '[]' to methods X.get(idx) v = X[idx] , X.set(idx,val) and X.put(idx,val) -> X[idx] = val 56 63 - unworkable - too many false positives 57 64 58 Handling of indexing '[]' on Maps and Lists 59 x[i]=v : map: x.put(i,v) list: x.set(i,v) 60 v = x[i]: map: v = map.get(i) list: v = list.get(i) 65 Handling of indexing '[]' on Strings, Maps and Lists 66 x[i]=v : String: - map: x.put(i,v) list: x.set(i,v) 67 v = x[i]: String: v = x.charAt(i) map: v = map.get(i) list: v = list.get(i) 68 DONE Nov-2011 69 70 codegen for user code indexers 71 pro/get/set [index as idxT] as T 72 get 73 return _data[index] 74 set 75 _data[index] = value 76 77 accessor: T getIndexer(idxT index) { return _data[index]; } 78 mutator: void setIndexer(idxT index, T value) { _data[index] = value; } 79 80 String Substitutions: 81 format handling: 82 e.g. m=42 83 assert '[m:N]' == '42.00' 84 1) ignore initially 85 2) either map .Net fmt to java equiv (shudder) 86 or treat as java specific form - 87 m=42.0 88 assert '[m:%.2f]' == '42.00' 89 90 91 Arrays 92 Array init from Array literal 93 Array indexing 94 95 61 96 Events 62 97 - auto add boiler plate for listener (de)registration 63 98 - event firing 64 99 65 100 66 101 partial classes 67 Add extra phase to aggregate partial classes together into first Module 102 Add extra phase to aggregate partial classes together into first Module or AST Tree 68 103 (Chk if cobra is doing sommat like this or relying on C# compiler) 69 104 70 105 Extensions … … 131 166 in call wrap arg in a SoftRef (or make own version HardRef subclass j.l.ref.Reference) 132 167 Chg param to be a SoftRef to the arg passed (e.g. 'arg_Ref') 133 168 In the method pull it out from the softref as a local name ('arg') 134 135 169 170 nilable/nonNilable 171 enforcement nonNilable - require use of Java7 and use Objects.requireNonNull() call 172 173 136 174 Add new compiler directive 137 175 @platform portable|jvm|clr|objc 138 176 … … 154 192 or default Decimal to Double ?? 155 193 tests :050-decimal.cobra 156 194 195 Java7 adds java.nio Files and (interface) Path - modify codegen/handling to use that ( wire to >java7) 196 use Paths to create Path and Files to convert Path for use 197 legacy Path p = fileInst.toPath(); // java.io.File to java.nio.Path 198 157 199 Add convenience methods to 158 200 java.io.File for 159 201 remember -
Source/BackEndJvm/ScanJvmType.cobra
198 198 199 199 # work out what doing with indexor and apply to [] 200 200 #_fix('System.Collections.Generic.List<of>', r'[]') 201 _fix('Java.Util.List<of>', r'[] get set remove ')202 _fix('Java.Util.AbstractList<of>', r'[] get set remove ')201 _fix('Java.Util.List<of>', r'[] get set remove size') 202 _fix('Java.Util.AbstractList<of>', r'[] get set remove size') 203 203 _fix('Java.Util.AbstractSequentialList<of>', r'[] get set remove') 204 204 _fix('Java.Util.ArrayList<of>', r'[] get set remove') 205 205 #_fix('Java.Util.CopyOnWriteArrayList<of>', r'[] get set remove') … … 218 218 #_fix('Java.Util.IdentityHash<of,>', r'[] get') 219 219 #_fix('Java.Util.TreeMap<of,>', r'[] get') 220 220 #_fix('Java.Util.WeakHashMap<of,>', r'[] get') 221 _fix('Java.Util.Map.Entry<of,>', r'getKey getValue') 221 222 # Nested classes need to be handled when enclosing class is loaded 223 # see Box._nestedUnNil below 224 #_fix('Java.Util.Map.Entry<of,>', r'getKey getValue') 222 225 #_fix('Java.Util.AbstractMap.SimpleEntry<of,>', r'getKey getValue') 223 226 #_fix('Java.Util.AbstractMap.SimpleImmutableEntry<of,>', r'getKey getValue') 224 #_fix('Java.Util.Properties', r'getProperty')227 _fix('Java.Util.Properties', r'getProperty') 225 228 226 229 #_fix('System.IO.File', 'create createText open openRead openText openWrite readAllBytes readAllLines readAllText') 227 230 _fix('Java.Io.File', 'create createText open openRead openText openWrite readAllBytes readAllLines readAllText getPath getAbsolutePath') … … 233 236 #_fix('java.lang.StringBuilder', 'toString') # ?? 234 237 #_fix('java.lang.Text.RegularExpressions.Regex', 'match replace') 235 238 #_fix('System.Diagnostics.Process', 'processName') 236 _fix(' java.util.regex.Pattern', 'matches matcher pattern split compile')237 _fix(' java.util.regex.Matcher', 'group pattern replaceAll replaceFirst')238 _fix(' java.lang.ProcessBuilder', 'command start directory')239 _fix('Java.Util.Regex.Pattern', 'matches matcher pattern split compile') 240 _fix('Java.Util.Regex.Matcher', 'group pattern replaceAll replaceFirst') 241 _fix('Java.Lang.ProcessBuilder', 'command start directory') 239 242 #_fix('java.lang.Process', 'getInputStream getOutputStream getErrorStream') 240 243 241 244 #_fix('System.Reflection.Assembly', 'getEntryAssembly getExecutingAssembly location') … … 244 247 #_fix('System.Reflection.ParameterInfo', 'parameterType') 245 248 #_fix('System.Reflection.PropertyInfo', 'propertyType') 246 249 250 def jvmFixIndexerMemberSigs 251 # Mapping for (simple) Indexers to java methods. 252 # Fix the listed classes to support Indexors using specified members as accessors and mutators. 253 # called from bindInterface phase so this can only refer to top level Classes in a package. 254 255 # Initially and currently hard coded in JvmJarSig. 256 # TODO: fixup to specify here like nilableMemberSigs 257 # TODO: this really needs to go in a separate file that the compiler reads each time 258 #print 'fixing Indexers' 259 #Format below is 260 #_AddIdxr('FullClassName', 'accessorMethod mutatorMethod') -- Mutator is optional 261 #_addIdxr('Java.Lang.String', 'charAt') 262 #_addIdxr('Java.Util.Map', 'get put') 263 #_addIdxr('Java.Util.List', 'get set') 264 pass 247 265 248 266 # 249 267 # Jvm Type Cache … … 419 437 skip = true 420 438 break 421 439 if skip, continue 422 params = _scanJvmParams(ctorInfo.getParameters, ctorInfo.isVari )440 params = _scanJvmParams(ctorInfo.getParameters, ctorInfo.isVari, false) 423 441 isNames = _isNamesForJavaMemberInfo(ctorInfo) 424 442 attribs = _attribsForJavaMemberInfo(ctorInfo) 425 443 docString = '' # TODO: get doc string for class? … … 481 499 for paramInfo in propInfo.getIndexParameters 482 500 if _badJvmRelatedType(paramInfo) 483 501 return 484 params = _scanJvmParams(propInfo.getIndexParameters, false )502 params = _scanJvmParams(propInfo.getIndexParameters, false, true) 485 503 attribs = _attribsForJavaMemberInfo(propInfo) 486 504 docString = '' 487 505 if propInfo.isReadable … … 529 547 genericParams = List<of IType>() 530 548 for genArg in methInfo.getGenericArguments 531 549 genericParams.add(GenericParam(JvmNativeType(genArg))) 532 params = _scanJvmParams(methInfo.getParameters, methInfo.isVari )550 params = _scanJvmParams(methInfo.getParameters, methInfo.isVari, false) 533 551 isNames = _isNamesForJavaMemberInfo(methInfo) 534 552 if methInfo.isOverride, isNames.add('override') # only on methods 535 553 attribs = _attribsForJavaMemberInfo(methInfo) … … 553 571 else 554 572 .addDecl(method) 555 573 556 def _scanJvmParams(jparams as List<of JavaClassType>?, isVariMethod as bool ) as List<of Param>574 def _scanJvmParams(jparams as List<of JavaClassType>?, isVariMethod as bool, isNotNullable as bool) as List<of Param> 557 575 """ 558 576 Returns a list of Cobra Params given a list of Java ClassTypes (presumably a java parameterList) 559 577 """ … … 572 590 # To support nilable on params need change representation to a javaParamType containing type + attributes (for param) ( + direction possibly) 573 591 # Java not support nilable directly so ignore for moment 574 592 #isNotNull = javaParam.isNonNullable 575 isNotNullable = false # can be null593 #isNotNullable = false # indexer params not be null others can be 576 594 parameterType = javaParam 577 595 type = _jvmMemberTypeProxy(parameterType, isNotNullable) 596 #if isNotNullable, print '>>', javaParam, ' ', type 578 597 if isVari, type = VariTypeProxy(type) 579 598 name = 'unkname' # java not keep names of given formal parameters 580 599 param = Param(name, type) 600 #if isNotNullable 601 # print '>>>' stop 602 # param.writeDeepString 581 603 param.direction = Direction.In # Java doesnt have Out or InOut equivs 582 604 params.add(param) 583 605 return params … … 658 680 #_fix('java.util.Map<of,>.Entry<of,>', r'getKey getValue') 659 681 #_fix('java.util.AbstractMap.SimpleEntry<of,>', r'getKey getValue') 660 682 #_fix('java.util.AbstractMap.SimpleImmutableEntry<of,>', r'getKey getValue') 661 683 var _nestedUnNil as Dictionary<of String, String> = { 684 'Java.Util.Map<of,>.Entry<of,>' : r'getKey getValue', 685 'Java.Util.AbstractMap.SimpleEntry<of,>': r'getKey getValue', 686 'Java.Util.AbstractMap.SimpleImmutableEntry<of,>': r'getKey getValue' 687 } 688 662 689 def _fixNestedNilables 663 690 if .parentBox # nested 664 print 'fixNest', .parentBox.name, .name 665 691 query = '[.parentBox.qualifiedName].[.name]' 692 print 'fixNest', query 693 memberNames = _nestedUnNil.get(query, '') 694 if memberNames.length 695 .parentBox.membersToUnNil = memberNames 696 #print ' unNil', memberNames 666 697 667 698 class Class 668 699 is partial … … 729 760 _scanJvmMethods 730 761 #_scanJvmEvents 731 762 732 def _scanJvmParams(jparams as List<of JavaClassType>?, isVariMethod as bool ) as List<of Param> is override763 def _scanJvmParams(jparams as List<of JavaClassType>?, isVariMethod as bool, isNotNullable as bool) as List<of Param> is override 733 764 # the first argument is implicit in an Extension 734 results = base._scanJvmParams(jparams, isVariMethod )765 results = base._scanJvmParams(jparams, isVariMethod, isNotNullable) 735 766 return results[1:] 736 767 737 768 def jvmExtnNativeType(nativeType as NativeType) as NativeType -
Source/BackEndJvm/JvmBackEnd.cobra
28 28 'IEnumerator<of>' : 'Java.Lang.Iterator<of>', 29 29 'IDictionaryEnumerator' : 'Java.Lang.Iterator', 30 30 #'IDictionaryEnumerator' : 'System.Collections.IDictionaryEnumerator', 31 'ICollection': 'Java.Util.Collection <of Object>', # non generic collection interface31 'ICollection': 'Java.Util.Collection', # non generic collection interface 32 32 'ICollection<of>': 'Java.Util.Collection<of>', 33 33 'IList' : 'Java.Util.List<of Object>', # non generic List interface 34 34 'IList<of>' : 'Java.Util.List<of>', … … 40 40 41 41 'bool' : 'Java.Lang.Boolean', # boolean 42 42 'char' : 'Java.Lang.Character',# char 43 'decimal': 'Java.Lang.D ouble', # ??43 'decimal': 'Java.Lang.Decimal', # virtualised -> Double 44 44 'single': 'Java.Lang.Float', # float 45 45 'double': 'Java.Lang.Double', # double 46 'sbyte' : 'Java.Lang.Byte', 46 'sbyte' : 'Java.Lang.Byte', # byte 47 47 'int16' : 'Java.Lang.Short', # short 48 48 'int32' : 'Java.Lang.Integer', # int 49 'int64' : 'Java.Lang.Long', # long 50 'byte' : 'Java.Lang.Short', # short # rest are unsigned - use next widest 51 'uint16': 'Java.Lang.Integer', # int 52 'uint32': 'Java.Lang.Long', # long 53 'uint64': 'Java.Lang.Long', # long 49 'int64' : 'Java.Lang.Long', # long 50 'int' : 'Java.Lang.Integer', # int primitive (struct) - need same for other primitives?? 51 # rest are unsigned, n/a in Java. But still need to be distinct. 52 # Invent some fake names and remap at javaClass level 53 'byte' : 'Java.Lang.UByte', # virtualised -> Short 54 'uint16': 'Java.Lang.UShort', # virtualised -> Integer 55 'uint32': 'Java.Lang.UInteger',# virtualised -> Long 56 'uint64': 'Java.Lang.ULong', # virtualised -> Long 54 57 55 58 } 56 59 … … 155 158 # rt.jar is only one we need 156 159 .compiler.javaReadJar(JarSig('rt.jar')) 157 160 158 def fix NilableMemberSigs is override159 #.compiler.jvmfixNilableMemberSigs160 pass # TODO161 def fixMemberSigs is override 162 .compiler.jvmFixNilableMemberSigs 163 .compiler.jvmFixIndexerMemberSigs 161 164 162 165 def installNativeMethods(box as Box, nativeType as NativeType) is override 163 #.compiler.installJvmNativeMethods(box, nativeType)164 pass # TODO166 .compiler.installJvmNativeMethods(box, nativeType) 167 #pass # TODO 165 168 166 169 def cobraNameForNativeBoxName(nativeBoxName as String) as String is override 167 170 return JvmTypeProxy.cobraNameForJvmBoxName(nativeBoxName) -
Source/BackEndJvm/JavaGenerator.cobra
370 370 sw.writeAndIndent(r'static public void main(String[] args) {') 371 371 sw.writeLine 372 372 sw.bumpLineNum 373 sw.writeLine(' //cobra.lang.CobraCore.setCommandLineArgs(args); ')373 sw.writeLine('cobra.lang.CobraCore._recordCommandLine(args); ') 374 374 sw.writeLine('(new [mainMethod.parentBox.javaRef]()).main(args);') 375 375 sw.bumpLineNum 376 376 sw.dedentAndWrite('} // end MainWrapper.main\n\n') … … 1195 1195 pro javaExtraIsNames from var 1196 1196 1197 1197 get javaThis as String 1198 return if(.isShared, 'typeof([.parentBox.javaName])', .parentBox.javaThis) 1198 #return if(.isShared, 'typeof([.parentBox.javaName])', .parentBox.javaThis) 1199 return if(.isShared, '([.parentBox.javaName].class)', .parentBox.javaThis) 1199 1200 1200 1201 def writeJavaNotNull(sw as CurlyWriter) 1201 1202 if .resultType.isReference and not .resultType inherits NilableType … … 1665 1666 sw.indent 1666 1667 if .isMain and .compiler.options.boolValue('include-tests') 1667 1668 sw.writeLine('cobra.lang.CobraCore.runAllTests(); // turn off with -include-tests:no (see cobra -h)') 1669 if .isMain and .hasMainParams 1670 sw.writeLine('cobra.lang.CobraCore._recordCommandLine(args); ') 1668 1671 1669 1672 def writeJavaImpFooter(sw as CurlyWriter) 1670 1673 base.writeJavaImpFooter(sw) … … 1785 1788 1786 1789 class Indexer is partial 1787 1790 1788 # TODO1789 pass1791 get javaNotNullPrefix as String is override 1792 return '' 1790 1793 1794 def writeJavaDef(sw as CurlyWriter) is override 1795 #base.writeJavaDef(sw) 1796 assert _name==r'[]' 1797 sw.write('// Indexer ') 1798 #.writeJavaNotNull(sw) 1799 #.writeJavaAttribs(sw) 1800 #.writeJavaIsNames(sw) 1801 sw.write(' [_returnType.javaRef] this') 1802 .writeJavaParams(sw, r'[]') 1803 #.writeSharpBody(sw) 1804 # TODO: finish correctly (method with special attribute??? 1791 1805 1792 1806 class MemberOverload is partial 1793 1807 … … 2669 2683 handled = true 2670 2684 if not handled 2671 2685 _target.writeJavaDef(sw) 2672 sw.write(r'[') 2686 2687 ntIdxr = _lookupReadIndexer 2688 if ntIdxr 2689 assert ntIdxr.getter 2690 assert ntIdxr.getter.name.length 2691 _writeIndexer(sw, '.[ntIdxr.getter.name](', ')') 2692 else 2693 _writeIndexer(sw, r'[', r']') 2694 2695 if parens, sw.write(')') 2696 2697 def _lookupReadIndexer as JavaFieldInfo? 2698 nt = JvmNativeType.nativeType(_target.type) 2699 if nt 2700 ntIdxr = nt.indexer 2701 if ntIdxr and ntIdxr.isReadable 2702 return ntIdxr 2703 #TODO: check for Indexer attribute for a Cobra user written version 2704 return nil 2705 2706 def _writeIndexer(sw as CurlyWriter, prefix as String, suffix as String) 2707 sw.write(prefix) 2708 _writeIdxArgs(sw) 2709 sw.write(suffix) 2710 2711 def _writeIdxArgs(sw as CurlyWriter) 2673 2712 sep = '' 2674 2713 for expr in _args 2675 2714 sw.write(sep) 2676 2715 expr.writeJavaDefInContext(sw) 2677 2716 sep = ', ' 2678 sw.write(']')2679 if parens, sw.write(')')2680 2717 2681 2718 def writeJavaBreakdownItems(sw as CurlyWriter) 2682 2719 base.writeJavaBreakdownItems(sw) … … 2758 2795 # C# chokes on it because the first "X" is considered to be the type 2759 2796 #if .curBox.name + '.' in javaRef 2760 2797 # javaRef = 'global::' + javaRef 2761 if _requiresTypeOf() 2762 sw.write('typeof(') 2798 if _requiresGetClass() # was _requiresTypeOf 2799 #sw.write('typeof(') 2800 sw.write('(') 2763 2801 sw.write(javaRef) 2802 sw.write('.getClass()') 2764 2803 sw.write(')') 2765 2804 else 2766 2805 sw.write(javaRef) 2767 2806 2807 def _requiresGetClass as bool 2808 return false # may need to extend later 2809 2768 2810 /# def _requiresTypeOf as bool 2769 2811 # Cobra never requires that you wrap a type reference in typeof(Foo). 2770 2812 # C# requires typeof() in a variety of circumstances and won't accept it in a variety of others. … … 2787 2829 #/ 2788 2830 2789 2831 def writeJavaDefForBreakdown(sw as CurlyWriter) is override 2790 requiresTypeOf = _requiresTypeOf # using C# version currently - chop ?2791 if not requiresTypeOf, sw.write('typeof(')2832 #requiresTypeOf = _requiresTypeOf # using C# version currently - chop ? 2833 #if not requiresTypeOf, sw.write('typeof(') 2792 2834 .writeJavaDef(sw) 2793 if not requiresTypeOf, sw.write(')')2835 #if not requiresTypeOf, sw.write(')') 2794 2836 2795 2837 2796 2838 class UnaryOpExpr … … 2809 2851 assert specs.containsKey(.token.text) 2810 2852 spec = specs[.token.text] 2811 2853 opText = Utils.javaStringLiteralFor(spec.opMethodName) 2812 sw.write(' CobraLangInternal.CobraImp.DynamicOp([opText], ')2854 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.dynamicOp([opText], ') 2813 2855 _expr.writeJavaDef(sw, false) 2814 2856 sw.write(')') 2815 2857 return … … 3010 3052 #sw.write(').value') 3011 3053 sw.write(')') 3012 3054 else if .compiler.options.boolValue('include-nil-checks') 3013 sw.write('(CobraLangInternal.CobraCore._willCheckNil ? CobraLangInternal.CobraImp.CheckNonNil<[type.javaRef]>([.javaThis], [Utils.javaStringLiteralFor(_expr.toCobraSource)], ') 3055 #sw.write('(cobra.lang.CobraCore._willCheckNil ? cobra.lang./*CobraLangInternal.*/CobraImp.checkNonNil<[type.javaRef]>([.javaThis], [Utils.javaStringLiteralFor(_expr.toCobraSource)], ') 3056 sw.write('(cobra.lang.CobraCore._willCheckNil ? cobra.lang./*CobraLangInternal.*/CobraImp.checkNonNil([.javaThis], [Utils.javaStringLiteralFor(_expr.toCobraSource)], ') 3014 3057 _expr.writeJavaDef(sw, false) 3015 sw.write(', [.javaSourceSiteArgs]) :')3058 sw.write(', [.javaSourceSiteArgs]) :') 3016 3059 _expr.writeJavaDef(sw, false) 3017 3060 sw.write(')') 3018 3061 else … … 3054 3097 3055 3098 def writeJavaDef(sw as CurlyWriter, parens as bool) is override 3056 3099 if _trackLocal 3057 sw.write(' CobraLangInternal.CobraImp.SetLocal("[_trackName]", ')3100 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.setLocal("[_trackName]", ') 3058 3101 else if parens 3059 3102 sw.write('(') 3060 3103 _writeJavaDef(sw) … … 3073 3116 if _left inherits IndexExpr 3074 3117 if _left.target.type.isDynamic 3075 3118 # assigning to an indexer of a dynamically typed target requires special code gen 3076 sw.write(' CobraLangInternal.CobraImp.SetIndexerValue(')3119 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.setIndexerValue(') 3077 3120 _left.target.writeJavaDef(sw, false) 3078 3121 sw.write(', ') 3079 3122 _right.writeJavaDef(sw, false) … … 3100 3143 if _left inherits DotExpr 3101 3144 if _left.left.type.isDynamic 3102 3145 assert _left.right inherits MemberExpr 3103 sw.write(' CobraLangInternal.CobraImp.setPropertyValue(')3146 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.setPropertyValue(') 3104 3147 _left.left.writeJavaDef(sw, false) 3105 3148 sw.write(', ') 3106 3149 sw.write(Utils.javaStringLiteralFor((_left.right to MemberExpr).name)) … … 3153 3196 _left.writeJavaDef(sw, false) 3154 3197 sw.write(' = ') 3155 3198 sw.write('(' + _left.type.javaRef + ')') 3156 sw.write(' CobraLangInternal.CobraImp.Concated(')3199 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.concated(') 3157 3200 _left.writeJavaDef(sw, false) 3158 3201 sw.write(', ') 3159 3202 _right.writeJavaDef(sw, false) … … 3166 3209 assert specs.containsKey(.token.text) 3167 3210 spec = specs[.token.text] 3168 3211 opText = Utils.javaStringLiteralFor(spec.opMethodName) 3169 sw.write(' CobraLangInternal.CobraImp.DynamicOp([opText], ')3212 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.dynamicOp([opText], ') 3170 3213 _left.writeJavaDef(sw) # TODO: add , false 3171 3214 sw.write(', ') 3172 3215 _right.writeJavaDef(sw) # TODO: add , false … … 3217 3260 assert specs.containsKey(.token.text) 3218 3261 spec = specs[.token.text] 3219 3262 opText = Utils.javaStringLiteralFor(spec.opMethodName) 3220 sw.write(' CobraLangInternal.CobraImp.DynamicOp([opText], ')3263 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.dynamicOp([opText], ') 3221 3264 _left.writeJavaDef(sw) # TODO: add , false 3222 3265 sw.write(', ') 3223 3266 _right.writeJavaDef(sw) # TODO: add , false … … 3269 3312 # do this: 3270 3313 src = Utils.javaStringLiteralFor(_right.toCobraSource) 3271 3314 javaNot = if(_op=='OR', '', '!') 3272 sw.write(', [src], new CobraLangInternal.CobraDirectString([javaNot]')3315 sw.write(', [src], new cobra.lang.CobraDirectString([javaNot]') 3273 3316 _left.writeJavaDefForBreakdown(sw) 3274 sw.write(' ? "(short-circuited)" : CobraLangInternal.CobraCore.ToTechString(')3317 sw.write(' ? "(short-circuited)" : cobra.lang.CobraCore.ToTechString(') 3275 3318 _right.writeJavaDefForBreakdown(sw) 3276 3319 sw.write('))') 3277 3320 … … 3316 3359 3317 3360 def _writeJavaDefConcated(sw as CurlyWriter) 3318 3361 sw.write('(' + _left.type.javaRef + ')') 3319 sw.write(' CobraLangInternal.CobraImp.Concated(')3362 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.concated(') 3320 3363 _left.writeJavaDef(sw, false) 3321 3364 sw.write(', ') 3322 3365 _right.writeJavaDef(sw, false) … … 3392 3435 left = _left 3393 3436 right = _right 3394 3437 op = _op 3438 wrapLeft = wrapRight = '' 3395 3439 # Compute the java operation which will be an operator or method call 3396 3440 if op=='EQ' or op=='NE' 3397 3441 if not left.type.isReference and not right.type.isReference … … 3406 3450 else 3407 3451 done = false 3408 3452 stringType = .compiler.stringType 3409 if left.isKindOf(stringType) and right.isKindOf(stringType) # TODO: check for static comparison operations instead 3410 op = _cobraToJava[_op] 3453 charType = .compiler.charType 3454 if left.isKindOfNonNil(stringType) and right.isKindOfNonNil(stringType) # TODO: check for static comparison operations instead 3455 op = if(op in ['EQ', 'NE'], '.equals(', '.compareTo(') 3411 3456 done = true 3457 else if left.isKindOfNonNil(charType) and right.isKindOfNonNil(stringType) 3458 op = if(op in ['EQ', 'NE'], '.equals(', '.compareTo(') 3459 wrapLeft = 'String.valueOf(' 3460 done = true 3461 else if left.isKindOfNonNil(stringType) and right.isKindOfNonNil(charType) 3462 op = if(op in ['EQ', 'NE'], '.equals(', '.compareTo(') 3463 wrapRight = 'String.valueOf(' 3464 done = true 3412 3465 else if left.type inherits Box # TODO: try skipping on requiring that the type is a Box 3413 3466 leftBox = left.type to Box 3414 3467 compareTo = leftBox.memberForName('compareTo') … … 3423 3476 if left.type inherits PrimitiveType and right.type inherits PrimitiveType 3424 3477 op = _cobraToJava[_op] 3425 3478 else if left.type.isReference and right.type.isReference 3426 op = if(op=='IS', ' instanceof ', '! instanceof ') 3479 op = _cobraToJava[_op] 3480 #op = if(op=='IS', ' instanceof ', '! instanceof ') 3427 3481 else 3428 3482 # non-trivial situation.. fall back to runtime support 3429 op = if(op=='IS', ' CobraLangInternal.CobraImp.Is(', 'CobraLangInternal.CobraImp.IsNot(')3483 op = if(op=='IS', 'cobra.lang./*CobraLangInternal.*/CobraImp.is(', 'cobra.lang./*CobraLangInternal.*/CobraImp.isNot(') 3430 3484 else 3431 3485 if left.type.isDynamic or right.type.isDynamic 3432 sw.write(' CobraLangInternal.CobraImp.DynamicCompare(')3486 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.dynamicCompare(') 3433 3487 left.writeJavaDef(sw, false) 3434 3488 sw.write(', ') 3435 3489 right.writeJavaDef(sw, false) … … 3445 3499 done = true 3446 3500 if not done 3447 3501 op = _cobraToJava[_op] 3502 3448 3503 # Write the Java code 3449 3504 if op.length <= 2 3450 left.writeJavaDef(sw)3505 _writeWrapped(sw, wrapLeft, left) 3451 3506 sw.write(op) 3452 right.writeJavaDef(sw)3507 _writeWrapped(sw, wrapRight, right) 3453 3508 else if op == '.equals(' 3454 3509 if _op == 'NE', sw.write('!(') 3455 left.writeJavaDef(sw)3510 _writeWrapped(sw, wrapLeft, left) 3456 3511 sw.write(op) 3457 right.writeJavaDef(sw, false)3512 _writeWrapped(sw, wrapRight, right) 3458 3513 sw.write(')') 3459 3514 if _op == 'NE', sw.write(')') 3460 3515 else if op == '.compareTo(' 3461 left.writeJavaDef(sw)3516 _writeWrapped(sw, wrapLeft, left) 3462 3517 sw.write(op) 3463 right.writeJavaDef(sw, false)3518 _writeWrapped(sw, wrapRight, right) 3464 3519 sw.write(') [_cobraToJava[_op]] 0') 3465 3520 else if op.endsWith('(') 3466 3521 sw.write(op) 3467 left.writeJavaDef(sw)3522 _writeWrapped(sw, wrapLeft, left) 3468 3523 sw.write(',') 3469 right.writeJavaDef(sw)3524 _writeWrapped(sw, wrapRight, right) 3470 3525 sw.write(')') 3471 3526 else 3527 print op 3472 3528 throw FallThroughException(op) 3473 3529 3530 def _writeWrapped( sw as CurlyWriter, wrap as String, e as Expr) 3531 if wrap.length 3532 sw.write(wrap) 3533 e.writeJavaDef(sw) 3534 sw.write(')') 3535 else 3536 e.writeJavaDef(sw) 3537 3474 3538 class ChainedCompareExpr is partial 3475 3539 3476 3540 def writeJavaDef(sw as CurlyWriter, parens as bool) is override … … 3479 3543 if parens, sw.write(')') 3480 3544 3481 3545 def writeJavaDef(sw as CurlyWriter) is override 3482 sw.write(' CobraLangInternal.CobraCore.ChainedComparison(')3546 sw.write('cobra.lang./*CobraLangInternal.*/CobraCore.chainedComparison(') 3483 3547 _items[0].writeJavaDef(sw) 3484 3548 itemIndex = 1 3485 3549 for operation in _operations … … 3509 3573 if _dotRightExpr.definition 3510 3574 sw.write('(' + _dotRightExpr.type.javaRef + ')') 3511 3575 if _right inherits MemberExpr 3512 sw.write(' CobraLangInternal.CobraImp.GetPropertyValue(')3576 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.getPropertyValue(') 3513 3577 _left.writeJavaDef(sw, not _left inherits DotExpr) 3514 3578 sw.write(', ') 3515 3579 sw.write(Utils.javaStringLiteralFor(_right.name)) # was .capitalized 3516 3580 sw.write(')') 3517 3581 else if _right inherits CallExpr 3518 sw.write(' CobraLangInternal.CobraImp.InvokeMethod(')3582 sw.write('cobra.lang.CobraImp.invokeMethod(') 3519 3583 _left.writeJavaDef(sw, not _left inherits DotExpr) 3520 3584 sw.write(', ') 3521 3585 sw.write(Utils.javaStringLiteralFor(_right.name)) # was .capitalized … … 3591 3655 _left.writeJavaDef(sw) 3592 3656 return 3593 3657 sw.write('(') 3594 _right.writeJavaDef(sw, false) # double parens would be pointless and also causes a C# error3658 _right.writeJavaDef(sw, false) 3595 3659 sw.write(')') 3596 3660 if not rightType inherits NilableType and rightType.isReference and .compiler.options.boolValue('include-nil-checks') 3597 sw.write(' CobraLangInternal.CobraImp.CheckNonNil<[_left.type.javaRef]>([.javaThis], [Utils.javaStringLiteralFor(_left.toCobraSource)], ')3661 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.checkNonNil([.javaThis], [Utils.javaStringLiteralFor(_left.toCobraSource)], ') 3598 3662 _left.writeJavaDef(sw, false) 3599 3663 sw.write(', [.javaSourceSiteArgs])') 3600 3664 else … … 3623 3687 #else 3624 3688 # sw.write('[typeJavaRef])CobraLangInternal.CobraImp.ToOrNil<[typeJavaRef]>(') 3625 3689 # .left.writeJavaDef(sw) 3626 sw.write('[typeJavaRef]) CobraLangInternal.CobraImp.ToOrNil<[typeJavaRef]>(')3690 sw.write('[typeJavaRef])cobra.lang.CobraImp.toOrNil<[typeJavaRef]>(') 3627 3691 .left.writeJavaDef(sw) 3628 3692 sw.write(')') 3629 3693 … … 3764 3828 sw.write('new [expr.receiverType.javaRef](') 3765 3829 .writeJavaArgs(sw) 3766 3830 sw.write(')') 3767 else if expr. type.nonNil.isDescendantOf(.compiler.delegateType)3831 else if expr.isKindOfNonNil(.compiler.delegateType) 3768 3832 isMethodSig = true 3769 3833 else if expr.type.isSystemTypeClass or _type.isDynamic 3770 3834 isDynamic = true 3771 3835 else 3772 3836 assert false, expr 3773 3837 else if expr inherits IndexExpr 3774 if expr. type.nonNil.isDescendantOf(.compiler.delegateType)3838 if expr.isKindOfNonNil(.compiler.delegateType) 3775 3839 isMethodSig = true 3776 3840 else if expr.type.isSystemTypeClass or _type.isDynamic 3777 3841 isDynamic = true -
Tests/200-misc/870-platform-directive/030-platform-directive-jvm.cobra
1 #.require. clr 2 #.error. platform specific to "jvm" 3 @platform jvm 4 5 class Plaf 6 7 def main is shared 8 System.out.println('Hello') -
Tests/200-misc/870-platform-directive/020-platform-directive-clr.cobra
1 #.require. clr 2 @platform clr 3 4 class Plaf 5 6 def main is shared 7 Console.writeLine('Hello') -
Tests/200-misc/870-platform-directive/060-platform-directive-jvm.cobra
1 #.require. jvm 2 @platform jvm 3 4 class Plaf 5 6 def main is shared 7 System.out.println('Hello') -
Tests/200-misc/870-platform-directive/040-platform-directive-any.cobra
1 @platform any 2 3 class Plaf 4 5 def main is shared 6 print 'Hello' -
Tests/200-misc/870-platform-directive/010-platform-directive-wrong.cobra
1 #.error. unrecognized platform name 2 @platform unk 3 4 class Plaf 5 6 def main is shared 7 Console.writeLine('Hello') -
Tests/200-misc/870-platform-directive/050-platform-directive-portable.cobra
1 @platform portable 2 3 class Plaf 4 5 def main is shared 6 print 'Hello' -
Tests/100-basics/060-string.cobra
1 #.require. clr 1 2 namespace Test 2 3 3 4 class Test -
Tests/100-basics/062j-string-substitution-fmt.cobra
1 #.require. jvm 2 # some simple string subst formatting tests - java format descriptions 3 namespace Test 4 5 class Test 6 7 def main 8 is shared 9 10 # formatting 11 #mol as float = 42.0 12 #print '[mol:%.2d]' 13 ## TODO This not yet working as formatting on makeString in java version NYI 14 #assert '[mol:%.2d]'=='42.00' 15 16 a = 99 17 # test some using format substitution without the escape syntax. 18 t = String.format('a = %0$s[a]]', c'[') 19 assert t == r'a = [99]' 20 21 s10 = 'FMT:a = '+ ns'[' +'[a]]' 22 assert s10 == r'FMT:a = [99]' 23 24 a1 = String.format('%0$s[a]]', ns'[') 25 s11 = 'a = [a1]' 26 assert s11 == r'a = [99]' 27 28 29 -
Tests/100-basics/062-string-substitution.cobra
23 23 # nested brackets 24 24 s as String = 'abc' 25 25 i = 1 26 assert 'the letter at [i] is [s[i]].'=='the letter at 1 is b.' 26 #print 'the letter at [i] is [s[i]].' 27 #assert 'the letter at [i] is [s[i]].'=='the letter at 1 is b.' 28 si = s[i] 29 assert 'the letter at [i] is [si].'=='the letter at 1 is b.' 27 30 28 31 # substitution works with double quotes 29 32 i = 3 … … 42 45 assert 'foo \[bar] [foo]' == r'foo [bar] 1' 43 46 assert 'foo [bar] \[foo]' == r'foo 2 [foo]' 44 47 45 # formatting 46 mol as int = 42 47 assert '[mol:N]'=='42.00' 48 assert "[mol:N]"=='42.00' 48 # formatting - moved to 062-string-substitution-fmt 49 #mol as int = 42 50 #assert '[mol:N]'=='42.00' 51 #assert "[mol:N]"=='42.00' 52 #assert '[mol:%2d]'=='42.00' # jvm 49 53 50 54 # the ns prefix means "no sub" or "no substitution" 51 55 assert ns'aoeu'=='aoeu' -
Tests/100-basics/060j-string.cobra
1 #.require. jvm 2 namespace Test 3 4 class Test 5 6 def main 7 is shared 8 9 s as String = '' 10 assert not s.length 11 s = 'aoeu' 12 assert 'aoeu'.length 13 assert s.length==4 14 15 assert 'aoeu'=='aoeu' 16 assert s=='aoeu' 17 assert s<>'asdf' 18 19 assert s.equals('aoeu') 20 # assert s.getHashCode<>0 # clr method name 21 assert s.hashCode<>0 # java method 22 23 s = "aoeu" # double quotes 24 25 assert 'aoeu'.length==4 26 #assert '\a'.length==1 # illegal escape chars in java 27 #assert '\b'.length==1 28 #assert '\f'.length==1 29 assert '\n'.length==1 30 assert '\t'.length==1 31 assert '\\'.length==1 32 assert '\r'.length==1 33 assert '\0'.length==1 34 assert '\\t'.length==2 35 assert '\\t'[1]=='t' 36 assert '\\t'[1]==c't' 37 38 # concat 39 assert 'a' + 'b' == 'ab' 40 assert 'a' + '' == 'a' 41 assert 'a' + 'b' + 'c' == 'abc' 42 43 # try some methods 44 assert 'abc'.indexOf('b')==1 45 assert 'abc'.indexOf('d')==-1 46 assert 'abc'.endsWith('c') 47 48 # comparisons to chars 49 assert 'x'==c'x' 50 assert c'x'=='x' 51 assert '\0'==c'\0' 52 assert '\0'==String.valueOf(c'\0') 53 54 # += 55 s = 'x' 56 s += 'y' 57 assert s=='xy' 58 59 60 # concat with valueOf(char) - toString not available on char 61 s = 'aoeu' 62 #s = s[0].toString + 'b' 63 s = String.valueOf(s[0]) + 'b' 64 assert s=='ab' 65 66 # chars 67 assert 'a'[0] == c'a' 68 assert '"'[0] == c'"' 69 assert "'"[0] == c"'" 70 71 # backslashes 72 assert 'cobra\'s lair' == "cobra's lair" 73 assert '"' == "\"" 74 assert '\'' == "'" 75 assert '\''[0] == c"'" 76 assert "\""[0] == c'"' -
Tests/100-basics/070-is-and-is-not.cobra
1 #.require. clr 1 2 namespace Test 2 3 3 4 class Test -
Tests/100-basics/063-string-substitution-escaped.cobra
1 1 # Tests/100-basics/063-esc-string-subst.cobra 2 2 # Tests for escaping of substitution syntax in strings 3 3 # By hopscc 4 #.require. clr 4 5 class Test 5 6 6 7 def main is shared … … 45 46 assert s9 == r"8:a = \[[a]]" 46 47 47 48 48 # test some the old way without the escape syntax.49 t = String.format('a = {0}[a]]', c'[')50 assert t == r'a = [99]'51 49 s10 = 'FMT:a = '+ ns'[' +'[a]]' 52 50 assert s10 == r'FMT:a = [99]' 53 51 54 a1 = String.format('{0}[a]]', ns'[')55 s11 = 'a = [a1]'56 assert s11 == r'a = [99]'57 52 58 53 s12 = 'a = [c'['][a]]' 59 54 assert s12 == r'a = [99]'