Ticket #275: java-jvm-4.patch
File java-jvm-4.patch, 60.7 KB (added by hopscc, 13 years ago) |
---|
-
Source/Members.cobra
1098 1098 1099 1099 pro isMain from var as bool 1100 1100 1101 pro hasMainParams from var as bool 1102 """ Flag that this method needs main entry point params inserted. Used by BackEnd codeGen""" 1103 1101 1104 get isMethod as bool is override 1102 1105 return true 1103 1106 -
Source/Compiler.cobra
1543 1543 branch .options.get('back-end') 1544 1544 on 'none', _backEnd = ClrBackEnd(this) # TODO-SELFHOST 1545 1545 on 'clr', _backEnd = ClrBackEnd(this) 1546 on 'jvm', _backEnd = JvmBackEnd(this) 1546 on 'jvm' 1547 _backEnd = JvmBackEnd(this) 1548 if .options['number'] == 'decimal', .options['number'] = 'float' 1547 1549 on 'objc', _backEnd = ObjcBackEnd(this) 1548 1550 else, throw FallThroughException(.options.get('back-end')) 1549 1551 -
Source/Expr.cobra
584 584 var _args as List<of Expr> 585 585 var _hasParens as bool 586 586 var _definition as IMember? 587 var _hasMainArgs as bool = false 587 588 588 589 cue init(token as IToken, name as String, args as List<of Expr>, hasParens as bool) 589 590 .init(token, name, nil, args, hasParens as bool) … … 612 613 get genericArgTypes from var 613 614 614 615 get hasParens from var 615 616 617 pro hasMainArgs from var 618 """Indicate if this call needs args passed into main method inserted by backend. For MainWrapper """ 619 616 620 get willChangeVar as bool is override 617 621 for arg in _args, if arg.willChangeVar, return true 618 622 for arg in _args, if arg.direction <> Direction.In, return true -
Source/Cobra.Lang/Java/CobraCore.java
9 9 */ 10 10 package cobra.lang; 11 11 12 //interface IHasSourceSite { 13 // public SourceSite getSourceSite(); 14 //} 15 16 12 17 public class CobraCore { 13 18 14 19 public static Boolean _willCheckInvariant = true; … … 20 25 //public static String getRuntimePlatform() { return "jvm"; } // prop 21 26 public static final String runtimePlatform = "jvm"; 22 27 28 public static boolean getWillCheckAssert() { return _willCheckAssert; } 29 public static void setWillCheckAssert(boolean b) { _willCheckAssert = b; } 30 31 // Property StringMaker techStringMaker 32 /* 33 * Used by `assert` failures, `trace` statements and .toTechString methods. 34 */ 35 static public CobraImp.SimpleStringMaker getTechStringMaker() { return CobraImp._techStringMaker; } 36 static public void setTechStringMaker(CobraImp.SimpleStringMaker value) { CobraImp._techStringMaker = value; } 37 23 38 public static int noOp(/* allowNull */ Object... args) { 24 39 /* """ 25 40 No operation. Primarily used in Cobra's own test suite to consume a local variable to avoid undesired warnings. -
Source/Cobra.Lang/Java/AssertException.java
1 1 /* 2 2 * java code for cobra assert exception ( placeholder currently) 3 * in process of Converting from cobra to java code4 3 * Initially using java assertion till this is working 4 * 5 * Exceptions for Assertions, contracts, etc. 5 6 */ 6 7 7 8 package cobra.lang; 8 9 9 import java.util. List;10 import java.util.*; 10 11 11 12 12 class AssertException extends Exceptionimplements IHasSourceSite, HasAppendNonPropertyKeyValues13 class AssertException extends RuntimeException //implements IHasSourceSite, HasAppendNonPropertyKeyValues 13 14 // has DetailedStackTrace(false) 14 15 { 15 Object _this;16 Object _info; /* dynamic */17 SourceSite_sourceSite;18 java.util.List<Object> _expressions;16 protected Object _this; 17 protected Object _info; /* dynamic */ 18 protected Object /*SourceSite*/ _sourceSite; 19 protected java.util.List<Object> _expressions; 19 20 20 AssertException(SourceSite sourceSite, java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*dynamic? */) 21 String nl = System.getProperties().getProperty("line.separator"); 22 23 public AssertException(/*SourceSite*/ Object sourceSite, java.util.List<Object> expressions /*dynamic */, 24 Object thiss, Object info /*dynamic? */) 21 25 { 22 this(sourceSite, expressions, thiss, info, n il)26 this(sourceSite, expressions, thiss, info, null); 23 27 } 24 28 25 AssertException(SourceSite sourceSite, java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*as dynamic?*/, Exception innerExc) 29 public AssertException(/*SourceSite*/ Object sourceSite, java.util.List<Object> expressions /*dynamic */, 30 Object thiss, Object info /*dynamic?*/, Exception innerExc) 26 31 { 27 super( 'assert', innerExc)28 _sourceSite = sourceSite 29 _expressions = expressions 30 _this = thiss 31 _info = info 32 super("assert", innerExc); 33 _sourceSite = sourceSite; 34 _expressions = expressions; 35 _this = thiss; 36 _info = info; 32 37 } 33 // UNFINISHED34 38 35 Object getThis { return _this; } 39 // Property this 40 public Object getThis() { return _this; } 36 41 37 Object getInfo { return _info; } 42 // Property info 43 public Object getInfo() { return _info; } 38 44 39 SourceSite getSourceSite { return _sourceSite; } 45 // Property sourceSite 46 public Object /*SourceSite*/ getSourceSite() { return _sourceSite; } 40 47 41 List<Object> getExpressions { return _expressions; } 48 // Property expressions 49 public List<Object> getExpressions() { return _expressions; } 42 50 43 51 @Override 44 String getMessage() 45 { 46 nl = System.properties.newLine 47 StringBuilder sb = new StringBuilder(nl); 48 sb.append('sourceSite = [.sourceSite][nl]'); 49 sb.append('info = [.makeString(.info)][nl]'); 50 sb.append('this = [.makeString(.this)][nl]'); 51 int indentLevel = 1; 52 int i = 1; 53 List<Object> exprs = _expressions; 54 while (i < exprs.size) { 55 Object item = exprs.get(i)); 56 if (item == +1) { 57 indentLevel += 1; 58 i += 1; 59 } 60 else if (item == -1) { 61 indentLevel -= 1; 62 i += 1; 63 } 64 else { 65 String source = (String)item; 66 Object value = exprs.get(i+1); 67 dirStr = value to? CobraDirectString 68 valueString = if(dirStr, dirStr.string, .makeString(value)) 69 sb.append(String(' ', indentLevel*4)) 70 sb.append('[source] = [valueString][nl]'); 71 i += 2; 72 } 73 } 74 75 return sb.toString 76 } 52 public String getMessage() { 53 StringBuilder sb = new StringBuilder(nl); 54 sb.append(String.format("sourceSite = %s%s", this._sourceSite, nl)); 55 sb.append(String.format("info = %s%s", this.makeString(this._info), nl)); 56 sb.append(String.format("this = %s%s", this.makeString(_this), nl)); 57 int indentLevel = 1; 58 int i = 1; 59 List<Object> exprs = _expressions; 60 while (i < exprs.size()) { 61 Object item = exprs.get(i); 62 if (item.equals(+1)) { 63 indentLevel++; 64 i += 1; 65 } 66 else if (item.equals(-1)) { 67 indentLevel--; 68 i += 1; 69 } 70 else { 71 String source = (String) item; 72 Object value = exprs.get(i+1); 73 String valueString = ""; 74 valueString = (value instanceof CobraDirectString) ? 75 ((CobraDirectString)value).string : this.makeString(value); 76 sb.append( this.replicateString(" ", indentLevel*4) ); 77 sb.append( String.format("%s = %s%s", source, valueString, nl)); 78 i += 2; 79 } 80 } 81 return sb.toString(); 82 } 77 83 78 String makeString(Object obj /*dynamic? */) 79 { 80 String s; 81 try { 82 s = CobraCore.techStringMaker.makeString(obj); 83 } 84 catch (Exception e) { 85 s = 'CobraCore.techStringMaker.makeString exception: ' + e.message; 86 } 87 return s; 88 } 84 String replicateString(String s, int count) { 85 StringBuilder sb = new StringBuilder(s); 86 while (--count > 0) sb.append(s); 87 return sb.toString(); 88 } 89 90 String makeString(Object obj /*dynamic? */) { 91 String s; 92 try { 93 s = CobraCore.getTechStringMaker().makeString(obj); 94 } 95 catch (Exception e) { 96 s = "CobraCore.techStringMaker.makeString exception: " + e.getMessage(); 97 } 98 return s; 99 } 89 100 90 def appendNonPropertyKeyValues(target as HasAppendKeyValue ) 101 /* 102 def appendNonPropertyKeyValues(target as HasAppendKeyValue ) 91 103 # Invoked by the Cobra Exception Report and CobraMain-ObjectExplorer-WinForms 92 104 # By adding the expression breakdown as entries in the view, 93 105 # object values will be clickable which will lead to their own detailed view. … … 108 120 target.appendKeyValue(String(c' ', indentLevel*4)+source, value) 109 121 i += 2 110 122 111 112 113 114 115 123 def populateTreeWithExpressions(tree as ITreeBuilder) 124 # Invoked by the Object Explorer, but any tool could use this by implementing ITreeBuilder. 125 # By adding the expression breakdown as entries in the view, 126 # object values will be clickable which will lead to their own detailed view. 127 i, exprs = 1, _expressions 116 128 while i < exprs.count 117 129 item = exprs[i] 118 130 if item == +1 … … 127 139 tree.appendKeyValue(source, value) 128 140 i += 2 129 141 142 */ 130 143 144 } 131 145 146 class InvariantException extends AssertException 147 { 148 public InvariantException(/*SourceSite*/ Object sourceSite, 149 java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*dynamic? */) 150 { 151 this(sourceSite, expressions, thiss, info, null); 152 } 153 154 public InvariantException(/*SourceSite*/ Object sourceSite, 155 java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*dynamic? */, 156 Exception cause) 157 { 158 super(sourceSite, expressions, thiss, info, cause); 159 } 160 } 132 161 162 class RequireException extends AssertException 163 { 164 protected RequireException _next; 133 165 134 /* 135 ## Exceptions about dynamic 166 public RequireException(/*SourceSite*/ Object sourceSite, 167 java.util.List<Object> expressions /*dynamic */, 168 Object thiss, 169 Object info /*dynamic? */) 170 { 171 this(sourceSite, expressions, thiss, info, null); 172 } 173 174 public RequireException(/*SourceSite*/ Object sourceSite, 175 java.util.List<Object> expressions /*dynamic */, 176 Object thiss, 177 Object info /*dynamic? */, 178 Exception cause ) 179 { 180 super(sourceSite, expressions, thiss, info, cause); 181 } 182 183 //Property RequireException next 184 public RequireException getNext() { return this._next;} 185 public void setNext(RequireException value) { this._next = value; } 186 } 136 187 137 class DynamicOperationException inherits Exception138 """139 The base class for all dynamic operation exceptions.140 """141 188 142 cue init(message as String?) 143 .init(message, nil) 189 class EnsureException extends AssertException 190 { 144 191 145 cue init(message as String?, innerExc as Exception?) 146 base.init(message, innerExc) 192 public EnsureException(/*SourceSite*/ Object sourceSite, 193 java.util.List<Object> expressions /*dynamic */, 194 Object thiss, 195 Object info /*dynamic? */) 196 { 197 this(sourceSite, expressions, thiss, info, null); 198 } 147 199 148 class CannotEnumerateException inherits DynamicOperationException 149 150 # CC: axe init()s 200 public EnsureException(/*SourceSite*/ Object sourceSite, 201 java.util.List<Object> expressions /*dynamic */, 202 Object thiss, 203 Object info /*dynamic? */, 204 Exception cause) 205 { 206 super(sourceSite, expressions, thiss, info, cause); 207 } 208 } 151 209 152 cue init(message as String?) 153 .init(message, nil) 210 class NonNilCastException extends AssertException 211 { 154 212 155 cue init(message as String?, innerExc as Exception?) 156 base.init(message, innerExc) 157 158 159 class UnknownMemberException inherits DynamicOperationException 213 public NonNilCastException(/*SourceSite*/ Object sourceSite, 214 java.util.List<Object> expressions /*dynamic */, 215 Object thiss, 216 Object info /*dynamic? */) 217 { 218 this(sourceSite, expressions, thiss, info, null); 219 } 160 220 161 var _obj as Object162 var _name as String163 var _type as Type164 221 165 cue init(obj as Object, name as String, type as Type) 166 .init(obj, name, type, nil) 222 public NonNilCastException(/*SourceSite*/ Object sourceSite, 223 java.util.List<Object> expressions /*dynamic */, 224 Object thiss, 225 Object info /*dynamic? */, 226 Exception cause ) 227 { 228 super(sourceSite, expressions, thiss, info, cause); 229 } 167 230 168 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 169 base.init('obj=[CobraCore.toTechString(obj)], name=[CobraCore.toTechString(name)], type=[type]', innerExc) 170 _obj = obj 171 _name = name 172 _type = type 231 @Override 232 public String getMessage() { 233 return String.format("Cast to non-nil failed.%s%s", this.nl, super.getMessage() ) ; 234 } 235 } 173 236 174 237 175 class CannotReadPropertyException inherits UnknownMemberException176 238 177 # CC: axe init()s239 /* ## Misc exceptions 178 240 179 cue init(obj as Object, name as String, type as Type)180 .init(obj, name, type, nil)181 182 cue init(obj as Object, name as String, type as Type, innerExc as Exception?)183 base.init(obj, name, type, innerExc)184 185 186 class CannotWritePropertyException inherits UnknownMemberException187 188 # CC: axe init()s189 190 cue init(obj as Object, name as String, type as Type)191 .init(obj, name, type, nil)192 193 cue init(obj as Object, name as String, type as Type, innerExc as Exception?)194 base.init(obj, name, type, innerExc)195 196 197 class CannotSliceTypeException inherits UnknownMemberException198 199 # CC: axe init()s200 201 cue init(obj as Object, name as String, type as Type)202 .init(obj, name, type, nil)203 204 cue init(obj as Object, name as String, type as Type, innerExc as Exception?)205 base.init(obj, name, type, innerExc)206 207 208 class CannotInTypeException inherits UnknownMemberException209 210 # CC: axe init()s211 212 cue init(obj as Object, name as String, type as Type)213 .init(obj, name, type, nil)214 215 cue init(obj as Object, name as String, type as Type, innerExc as Exception?)216 base.init(obj, name, type, innerExc)217 218 219 class CannotCompareException inherits DynamicOperationException220 221 var _a222 var _b223 224 cue init(a, b)225 .init(a, b, nil)226 227 cue init(a, b, innerExc as Exception?)228 base.init('a=[a], b=[b]', innerExc)229 #base.init('a=[CobraCore.toTechString(a)], a.getType=[a.getType.name], b=[CobraCore.toTechString(b)], b.getType=[b.getType.name]', innerExc)230 _a = a231 _b = b232 233 234 ## Assertions, contracts, etc.235 236 class AssertException inherits Exception implements IHasSourceSite, HasAppendNonPropertyKeyValues237 has DetailedStackTrace(false)238 239 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?)240 .init(sourceSite, expressions, thiss, info, nil)241 242 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?)243 base.init('assert', innerExc)244 _sourceSite = sourceSite245 _expressions = expressions246 _this = thiss247 _info = info248 249 get this from var as Object250 251 get info from var as dynamic?252 253 get sourceSite from var as SourceSite254 255 get expressions from var as IList<of dynamic>256 257 get message as String? is override258 nl = Environment.newLine259 sb = StringBuilder(nl)260 sb.append('sourceSite = [.sourceSite][nl]')261 sb.append('info = [.makeString(.info)][nl]')262 sb.append('this = [.makeString(.this)][nl]')263 i = indentLevel = 1264 exprs = _expressions265 while i < exprs.count266 item = exprs[i]267 if item == +1268 indentLevel += 1269 i += 1270 else if item == -1271 indentLevel -= 1272 i += 1273 else274 source = item to String275 value = exprs[i+1]276 dirStr = value to? CobraDirectString277 valueString = if(dirStr, dirStr.string, .makeString(value))278 sb.append(String(c' ', indentLevel*4))279 sb.append('[source] = [valueString][nl]')280 i += 2281 282 return sb.toString283 284 def makeString(obj as dynamic?) as String285 try286 s = CobraCore.techStringMaker.makeString(obj)287 catch e as Exception288 s = 'CobraCore.techStringMaker.makeString exception: ' + e.message289 return s290 291 def appendNonPropertyKeyValues(target as HasAppendKeyValue )292 # Invoked by the Cobra Exception Report and CobraMain-ObjectExplorer-WinForms293 # By adding the expression breakdown as entries in the view,294 # object values will be clickable which will lead to their own detailed view.295 indentLevel = 0296 target.appendKeyValue('expression breakdown:', Html(''))297 i, exprs = 1, _expressions298 while i < exprs.count299 item = exprs[i]300 if item == +1301 indentLevel += 1302 i += 1303 else if item == -1304 indentLevel -= 1305 i += 1306 else307 source = item to String308 value = exprs[i+1]309 target.appendKeyValue(String(c' ', indentLevel*4)+source, value)310 i += 2311 312 def populateTreeWithExpressions(tree as ITreeBuilder)313 # Invoked by the Object Explorer, but any tool could use this by implementing ITreeBuilder.314 # By adding the expression breakdown as entries in the view,315 # object values will be clickable which will lead to their own detailed view.316 i, exprs = 1, _expressions317 while i < exprs.count318 item = exprs[i]319 if item == +1320 tree.indent321 i += 1322 else if item == -1323 tree.outdent324 i += 1325 else326 source = item to String327 value = exprs[i+1]328 tree.appendKeyValue(source, value)329 i += 2330 331 332 class InvariantException inherits AssertException333 334 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?)335 .init(sourceSite, expressions, thiss, info, nil)336 337 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?)338 base.init(sourceSite, expressions, thiss, info, innerExc)339 340 341 class RequireException inherits AssertException342 343 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?)344 .init(sourceSite, expressions, thiss, info, nil)345 346 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?)347 base.init(sourceSite, expressions, thiss, info, innerExc)348 349 pro next from var as RequireException?350 351 352 class EnsureException inherits AssertException353 354 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?)355 .init(sourceSite, expressions, thiss, info, nil)356 357 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?)358 base.init(sourceSite, expressions, thiss, info, innerExc)359 360 361 class NonNilCastException inherits AssertException362 363 # it's unfortunate that we have to choose between inheriting AssertException or NullReferenceException364 365 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?)366 .init(sourceSite, expressions, thiss, info, nil)367 368 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?)369 base.init(sourceSite, expressions, thiss, info, innerExc)370 371 get message as String? is override372 return 'Cast to non-nil failed.[Environment.newLine][base.message]'373 374 375 ## Misc exceptions376 377 241 class ExpectException inherits Exception 378 242 379 243 cue init(expectedExceptionType as Type, actualException as Exception?) … … 420 284 cue init(msg as String?) 421 285 base.init 422 286 */ 423 }424 No newline at end of file -
Source/Cobra.Lang/Java/CobraDirectString.java
1 /* 2 * CobraDirectString Used internally for assert, require and ensure to encode strings 3 * that should not be passed to CobraCore.toTechString. 4 */ 5 package cobra.lang; 6 7 public class CobraDirectString { 8 public String string; 9 10 // ctor 11 public CobraDirectString(String s) { this.string = s; } 12 13 @Override 14 public String toString() { return string; } 15 } -
Source/Cobra.Lang/Java/Delegate.java
1 /* 2 * Start of a Delegate baseclass for Cobra implemented for Java 3 * The cobra compiler java backend will be reponsible for mapping the construction, initialisation and 4 * invocation of a Delegate to the API below 5 * construct sig delName(param as paramType0,...) as retType -> d = new Delegate(retType, paramType0, ...) 6 * ( or no args and void returnType -> d = new Delegate() ) 7 * assign myDelegate as delName = ref inst.method -> d.init(inst, "method") 8 * call myDelegate(arg0,...) -> d.invoke(arg0,...) 9 * (or no args: myDelegate() -> d.invoke() ) 10 * 11 * Doesnt support Generics. 12 * This Implementation genericised on ReturnType 13 */ 14 15 package cobra.lang; 16 17 import java.lang.*; 18 import java.io.*; 19 import java.util.*; 20 import java.lang.reflect.*; 21 22 public class Delegate<T> { 23 Class<T> returnType; // method returnType 24 Class<?>[] paramTypes; // Types of the method parameters 25 26 Class targetClass; 27 Object target; 28 String methodName; 29 Method method; 30 31 protected List<Delegate<T>> multiCastList; 32 33 /* 34 * A Delegate is a Type describing a method signature (returnType and ParamTypes) that can hold a 35 * method and target to invoke it on (instance or static). 36 * Start with recording the signature - return Type and parameter Types 37 */ 38 public Delegate(Class<T> returnType, Class<?>... paramTypes) { 39 //public Delegate(Class... paramTypes) { 40 this.returnType = returnType; 41 this.paramTypes = paramTypes; 42 } 43 44 /* 45 * Convenience for a Delegate with no params, no return type. 46 */ 47 static public Delegate allVoid() { 48 return new Delegate<Void>(void.class); 49 } 50 51 /* 52 * Initialise to a instance method on a particular target object 53 * Repeated calls will overwrite any previous settings. 54 */ 55 public void init(Object target, String methodName){ 56 this.target = target; 57 this.targetClass = target.getClass(); 58 this.methodName = methodName; 59 matchMethod(); 60 } 61 62 /* 63 * Initialise to a static method (on a target class) 64 * Repeated calls will overwrite any previous settings. 65 */ 66 public void init(Class targetClass, String methodName){ 67 this.target = null; 68 this.targetClass = targetClass; 69 this.methodName = methodName; 70 matchMethod(); 71 } 72 73 74 /* 75 * Ensure that there is a match for the given method name, return type and paramtypes on the target given. 76 * Record the Method and make accessible for later invocation 77 */ 78 void matchMethod() { 79 NoSuchMethodException e0 = null; 80 Class<?> mclass = this.targetClass; 81 for(;;) { 82 try { 83 this.method = mclass.getDeclaredMethod(this.methodName, this.paramTypes); 84 this.method.setAccessible(true); 85 this.targetClass = mclass; 86 break; 87 } catch(NoSuchMethodException e) { 88 if (mclass == Object.class) { 89 throw new RuntimeException(e0!=null ? e0 : e); 90 } else { 91 if (e0 == null) e0 = e; 92 mclass = mclass.getSuperclass(); 93 } 94 } 95 } 96 Class methodType = this.method.getReturnType(); 97 if ( ! isCompatibleType(this.returnType, methodType)) { 98 String msg = "NoSuchMethodException "+this.methodName + ":" ; 99 msg += "method returnType " + methodType.getName() + " not compatible with Delegate returnType " + this.returnType.getClass().getName(); 100 throw new RuntimeException(new NoSuchMethodException(msg)); 101 } 102 } 103 104 /** Maps primitives to their corresponding wrappers and vice versa. */ 105 private static final Map<Class,Class> PRIMITIVES_MAP = new HashMap<Class,Class>(); 106 107 static { 108 PRIMITIVES_MAP.put(boolean.class, Boolean.class); 109 PRIMITIVES_MAP.put(byte.class, Byte.class); 110 PRIMITIVES_MAP.put(char.class, Character.class); 111 PRIMITIVES_MAP.put(double.class, Double.class); 112 PRIMITIVES_MAP.put(float.class, Float.class); 113 PRIMITIVES_MAP.put(int.class, Integer.class); 114 PRIMITIVES_MAP.put(long.class, Long.class); 115 PRIMITIVES_MAP.put(short.class, Short.class); 116 PRIMITIVES_MAP.put(void.class, Void.class); 117 PRIMITIVES_MAP.put(Boolean.class, boolean.class); 118 PRIMITIVES_MAP.put(Byte.class, byte.class); 119 PRIMITIVES_MAP.put(Character.class, char.class); 120 PRIMITIVES_MAP.put(Double.class, double.class); 121 PRIMITIVES_MAP.put(Float.class, float.class); 122 PRIMITIVES_MAP.put(Integer.class, int.class); 123 PRIMITIVES_MAP.put(Long.class, long.class); 124 PRIMITIVES_MAP.put(Short.class, short.class); 125 PRIMITIVES_MAP.put(Void.class, void.class); 126 } 127 128 //private boolean isCompatibleType(Class<?> c1, Class<?> c2) { 129 private boolean isCompatibleType(Class<T> c1, Class<?> c2) { 130 return c1 == c2 || 131 c1 == PRIMITIVES_MAP.get(c2) || 132 c1.isAssignableFrom(c2) || 133 c2.isAssignableFrom(c1); 134 } 135 136 137 /** 138 * Executes the method synchronously on the calling thread and returns the 139 * result value. 140 * Any checked exceptions are caught and wrapped in a RuntimeException. 141 * MultCast Delegates are all run and the result of the last returned. 142 * 143 * @param arguments Values to pass to the method. 144 * @return result of calling the method. 145 */ 146 @SuppressWarnings("unchecked") // doesnt like the return cast 147 public T invoke(Object... arguments) { 148 assert !(this.method == null && this.multiCastList == null) : "Delegate.invoke: both method and multicastList null"; 149 Object result = null; 150 if (this.method != null) { 151 try { 152 result = this.method.invoke(this.target, arguments); 153 } catch(IllegalAccessException e) { 154 throw new RuntimeException(e); 155 } catch(InvocationTargetException e) { 156 throw new RuntimeException(e.getCause()); 157 } 158 } 159 if ( this.multiCastList != null && ! this.multiCastList.isEmpty()) { 160 for (Delegate d : this.multiCastList) { 161 result = d.invoke(arguments); 162 } 163 } 164 return (T) result; 165 } 166 167 /* 168 * Add an additional Delegate to make a multicast invocation List on a single Delegate. 169 * The original Delegate is not inserted in the multicast List 170 */ 171 public void add(Object target, String methodName){ 172 //Delegate d = new Delegate(this.returnType, this.paramTypes); 173 Delegate<T> d = new Delegate<T>(this.returnType, this.paramTypes); 174 if (target instanceof Class) 175 d.init((Class)target, methodName); 176 else 177 d.init(target, methodName); 178 179 if (this.multiCastList == null) { 180 this.multiCastList = new ArrayList<Delegate<T>>(); 181 } 182 this.multiCastList.add(d); 183 } 184 185 /* 186 * Remove an entry from a multicast invocation List. 187 */ 188 public void remove(Object target, String methodName){ 189 if (this.multiCastList == null || this.multiCastList.isEmpty()) { 190 return; 191 } 192 Delegate found = null; 193 for (Delegate d : this.multiCastList) { 194 if (d.target == target && d.methodName == methodName) { 195 found = d; 196 break; 197 } 198 } 199 if (found != null) { 200 this.multiCastList.remove(found); 201 } 202 } 203 204 public void clear(){ 205 this.target = null; 206 this.targetClass = null; 207 this.methodName = null; 208 this.multiCastList = null; 209 } 210 } 211 212 213 class TestDelegate { 214 215 public static void main(String... args) { 216 testSimple(); 217 testDiffInstances(); 218 testMulticast(); 219 220 Assert.end(); 221 } 222 223 static void testSimple() { 224 String s = "Testing Java Delegate!"; 225 Delegate d = new Delegate<Void>(Void.class, String.class); 226 d.init(System.out, "println"); // d.set(System.out.println) 227 d.invoke(s); 228 229 OutputStream os = new ByteArrayOutputStream(); 230 PrintStream ps = new PrintStream(os); 231 d.init(ps, "print"); // d.set(ps.print) 232 d.invoke("xx"); 233 //System.out.println("["+os.toString()+"]"); 234 Assert.equals(os.toString(), "xx"); 235 236 d = Delegate.allVoid(); // no args, no return 237 //d.init(System.out, "println"); // d.set(System.out.println) 238 //d.invoke(); 239 os = new ByteArrayOutputStream(); 240 ps = new PrintStream(os); 241 d.init(ps, "println"); // d.set(System.out.println) 242 d.invoke(); 243 Assert.equals(os.toString(), System.getProperties().getProperty("line.separator")); 244 245 } 246 247 static class X { 248 public String getS1() { return "S1";} 249 public String getS1x(int n) { return "S1"+n; } 250 } 251 252 static class Y { 253 public String aStr() { return "Str";} 254 public String nStr(int i) { return "" + i + "Str"; } 255 } 256 257 static void testDiffInstances() { 258 Delegate<String> d = new Delegate<String>(String.class); // no arg 259 X x = new X(); 260 Y y = new Y(); 261 d.init(x, "getS1"); // d.set(x.getS1) 262 String s = d.invoke(); 263 Assert.equals(s, "S1"); 264 //System.out.println("[" + s + "]"); 265 266 d.init(y, "aStr"); // d.set(y.aStr) 267 s = (String) d.invoke(); 268 Assert.equals(s, "Str"); 269 270 Delegate<String> d1 = new Delegate<String>(String.class, int.class); 271 d1.init(x, "getS1x"); // d.set(x.getS1x) 272 String s1 = d1.invoke(99); 273 Assert.equals(s1, "S199"); 274 275 d1.init(y, "nStr"); // d.set(y.nStr) 276 s1 = d1.invoke(1234); 277 Assert.equals(s1, "1234Str"); 278 } 279 280 static void testMulticast() { 281 Delegate<String> d0 = new Delegate<String>(String.class); // no args 282 X x = new X(); 283 Y y = new Y(); 284 d0.add(x, "getS1"); // d.add(x.getS1) 285 String s = d0.invoke(); 286 Assert.nonNull(s, "s"); 287 Assert.equals(s, "S1"); 288 289 d0.add(y, "aStr"); // d.set(y.nStr) 290 String s1 = d0.invoke(); 291 Assert.equals(s1, "Str"); 292 293 294 String nl = System.getProperties().getProperty("line.separator"); 295 296 Delegate<Void> d = new Delegate<Void>(void.class, String.class); 297 ByteArrayOutputStream os = new ByteArrayOutputStream(); 298 PrintStream ps = new PrintStream(os); 299 d.add(ps, "println"); // d.set(ps.println) 300 d.invoke("11"); 301 Assert.equals(os.toString(), "11"+nl); 302 303 d.clear(); 304 os.reset(); 305 d.add(ps, "println"); // d.set(ps.println) 306 d.add(ps, "print"); // d.set(ps.print) 307 d.invoke("22"); 308 Assert.equals(os.toString(), "22"+nl+"22"); 309 //System.out.println(nl+os.toString()); 310 311 os = new ByteArrayOutputStream(); 312 ps = new PrintStream(os); 313 d.clear(); 314 d.add(ps, "print"); // d.set(ps.print) 315 d.add(ps, "print"); // d.set(ps.print) 316 d.add(ps, "print"); // d.set(ps.print) 317 d.invoke("33."); 318 Assert.equals(os.toString(), "33.33.33."); 319 320 d.add(ps, "println"); // d.set(ps.println) 321 os.reset(); 322 d.invoke("33."); 323 Assert.equals(os.toString(), "33.33.33.33."+nl); 324 } 325 326 } 327 328 class Assert { 329 static boolean assertsEnabled = false; 330 static { 331 assert assertsEnabled = true; // Intentional side-effect!!! 332 // Now assertsEnabled is set to the correct value, true if asserts enabled, false otherwise 333 } 334 335 336 static void equals(Object s0, Object s1) { 337 assert s0.equals(s1) : mkAssertMsg(s0, s1); 338 if (assertsEnabled) System.out.print("."); 339 } 340 341 static String mkAssertMsg(Object s0, Object s1) { 342 return String.format("\"%s\".equals(\"%s\")\n arg0=[%s]\n arg1=[%s]", s0, s1, s0, s1); 343 } 344 345 static void nonNull(Object o, String s0 ) { 346 assert o != null : String.format("\"%s\" not Null", s0); 347 if (assertsEnabled) System.out.print("1"); 348 } 349 350 static void end() { if (assertsEnabled) System.out.println(); } 351 } -
Source/Cobra.Lang/Java/CobraImp.java
3 3 * Native java support code RTL 4 4 * 5 5 * Currently only stubbed, minimal native code impl. 6 * see also Cobra.Lang/NativeExtern.cobra 6 7 */ 7 8 package cobra.lang; 8 9 … … 34 35 return sb.toString(); 35 36 } 36 37 } 37 //static public StringMaker _printStringMaker ;38 //static public StringMaker _printStringMaker = new StringMaker(); 38 39 static public SimpleStringMaker _printStringMaker = new SimpleStringMaker(); 40 static public SimpleStringMaker _techStringMaker = new SimpleStringMaker(); 39 41 40 42 static { 41 43 // _printToStack = new Stack<TextWriter>(); 42 44 // PushPrintTo(Console.Out); 43 //_printStringMaker = new SimpleStringMaker();44 45 // _printStringMaker = new PrintStringMaker(); 45 46 // _techStringMaker = new TechStringMaker(); 46 47 // PromoteNumerics = NumericTypeInfo.PromoteNumerics; … … 71 72 static public String makeString(String s) { 72 73 return s; 73 74 } 75 76 77 78 79 /* IsTrue mappings */ 80 static public boolean isTrue(char c) {return c!='\0';} 74 81 82 static public boolean isTrue(Character c) {return c!=null && c.charValue()!='\0';} 83 84 static public boolean isTrue(int i) {return i!=0; } 85 86 static public boolean isTrue(Integer i) {return i!=null && i.intValue() !=0;} 87 88 static public boolean isTrue(long i) {return i!=0;} 89 90 static public boolean isTrue(Long i) {return i!=null && i.longValue()!=0;} 91 static public boolean isTrue(Boolean b) {return b!=null && b.booleanValue();} 92 93 /* 94 static public boolean IsTrue(decimal d) {return d!=0;} 95 static public boolean IsTrue(decimal? d) {return d!=null && d.Value!=0; } 96 */ 97 static public boolean isTrue(float f) {return f!=0;} 98 99 static public boolean isTrue(Float f) {return f!=null && f.floatValue()!=0.0;} 100 101 static public boolean isTrue(double d) {return d!=0; } 102 103 static public boolean isTrue(Double d) {return d!=null && d.doubleValue() !=0;} 104 105 static public boolean isTrue(String s) {return s!=null; } 106 107 static public boolean isTrue(java.util.Collection c) {return c!=null; } 108 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 127 75 128 } 76 129 -
Source/Phases/IdentifyMainPhase.cobra
40 40 mainMethod = mainList[0] 41 41 if .checkMain(mainMethod) 42 42 mainMethod.isMain = true 43 mainMethod.hasMainParams = true 43 44 if not mainMethod.isShared 44 45 _createSharedMainWrapper(mainMethod) 45 46 else … … 88 89 89 90 instantiate = PostCallExpr(Token.empty, TypeExpr(mainMethod.parentBox), List<of Expr>()) 90 91 mainCall = CallExpr(Token.empty, 'main', List<of Expr>(), false) 92 mainCall.hasMainArgs = true # backend insert args passed to main 91 93 dot = DotExpr(Token.empty, 'DOT', instantiate, mainCall) 92 94 93 95 method = Method(Token.empty, Token.empty, theClass, 'main', List<of Param>(), .compiler.voidType, nil, ['shared'], mainMethod.attributes, '') 96 method.hasMainParams = true # backend insert params on main method 94 97 method.addStmt(dot) 95 98 96 99 theClass.addDecl(method) -
Source/BackEndClr/SharpGenerator.cobra
2293 2293 return 2294 2294 sw.write('if (CobraLangInternal.CobraCore._willCheckAssert && !') 2295 2295 _expr.writeSharpDef(sw) 2296 sw.write(') ')2296 sw.write(') \n') # hops add \n for readability 2297 2297 sw.indent 2298 2298 sw.write('throw new CobraLangInternal.AssertException([.sharpSourceSite], ') 2299 2299 _expr.writeSharpBreakdown(sw) -
Source/BackEndClr/ClrBackEnd.cobra
110 110 ns.addUseDirective(UseDirective(useToken, ['System', 'IO'])) 111 111 ns.addUseDirective(UseDirective(useToken, ['System', 'Text'])) 112 112 ns.addUseDirective(UseDirective(useToken, ['Cobra', 'Lang'])) 113 #ns.addUseDirective(UseDirective(useToken, ['Cobra', 'Extn'])) 113 114 114 115 def fixLibExtension(libRef as String) as String is override 115 116 """ -
Source/BackEndJvm/to-do.text
151 151 -> try and use BigDecimal and convert all calls (:-( 152 152 153 153 Maybe easier to just default to Integer and ignore Decimal (initially) 154 or default Decimal to Double ?? 155 tests :050-decimal.cobra 154 156 155 156 157 Add convenience methods to 157 158 java.io.File for 158 159 remember … … 260 261 0: Treat default as Integer, map explicit decimal to float 261 262 262 263 264 Default Number type to non-decimal ( float??) 265 263 266 Delegates 264 267 Need some sort of placeholder for setProperties 265 268 Drop something into CobraCore - Cobra.Lang.Delegate? (DONE) -
Source/BackEndJvm/JvmBackEnd.cobra
66 66 if parentNameSpace and parentNameSpace.fullName == 'Java.Lang' 67 67 branch name 68 68 on 'Boolean', n = 'bool' 69 on 'boolean', n = 'bool' 69 70 #on 'SByte', n = 'int8' 70 71 on 'Byte', n = 'uint8' 72 on 'byte', n = 'uint8' 71 73 on 'Short', n = 'int16' 74 on 'short', n = 'int16' 72 75 #on 'UInt16', n = 'uint16' 73 76 on 'Integer', n = 'int32' 74 77 #on 'UInt32', n = 'uint32' 75 78 on 'Long', n = 'int64' 76 on 'UInt64', n = 'uint64' 79 on 'long', n = 'int64' 80 on 'UInt64', n = 'int64' 77 81 on 'Character', n = 'char' 78 82 on 'Float', n = 'float32' 79 83 on 'Double', n = 'float' 80 on 'BigDecimal', n = 'decimal' 84 on 'BigDecimal', n = 'decimal' # eventually 81 85 return n 82 86 83 87 def computeOutName as String is override -
Source/BackEndJvm/JavaGenerator.cobra
606 606 class CharType is partial 607 607 608 608 get javaInit as String is override 609 return '(char acter)0'609 return '(char)0' 610 610 611 611 612 612 class DynamicType is partial … … 620 620 621 621 class FloatType is partial 622 622 623 #get javaInit as String is override # where not implemeneted as a primitive 624 # return 'null' # 'new Float(0)' 625 623 626 get javaName as String is override 624 #return _nativeType.fullName 625 return 'float' 627 #return _nativeType.fullName # java.lang.{Double,Float} 628 # should name to primitives but not prob with JvmJarSig._aliasPrimitives 629 # TODO fix primitives float, double... vs classes java.lang.Float, java.lang.Double 630 t = _nativeType.fullName 631 branch t 632 on 'java.lang.Double', primName = 'double' 633 on 'java.lang.Float', primName = 'float' 634 else 635 throw FallThroughException() 636 return primName 626 637 627 638 628 639 class IntType is partial 629 640 630 641 get javaName as String is override 631 # should name to primitives but not prob fmJvmJarSig._aliasPrimitives642 # should name to primitives but not prob with JvmJarSig._aliasPrimitives 632 643 # TODO fix primitives int, long,... vs classes java.lang.Integer, java.lang.Long 633 644 #return _nativeType.fullName 634 645 t = _nativeType.fullName … … 1018 1029 class GenericParam is partial 1019 1030 1020 1031 get javaInit as String is override 1021 # TODO: ack. does Java have anything like this? 1022 return 'default([_name])' 1032 return 'null /*default([_name])*/' # not poss in java 1023 1033 1024 1034 def writeJavaDef(sw as CurlyWriter) 1025 1035 base.writeJavaDef(sw) … … 1121 1131 class LocalVar is partial 1122 1132 1123 1133 def writeJavaDef(sw as CurlyWriter) 1124 base.write SharpDef(sw)1134 base.writeJavaDef(sw) 1125 1135 sw.write('[.type.javaRef] [.javaName]') 1126 1136 init = .type.javaInit 1127 1137 if init.length, sw.write(' = [init]') … … 1587 1597 name = _implementsType.javaRef + '.' + name 1588 1598 .writeJavaIsNames(sw) 1589 1599 sw.write('[returnType.javaRef] [name][.javaGenericParams]') 1590 if . isMain1600 if .hasMainParams # insert args for main method for this backend 1591 1601 sw.write(r'(String[] args)') 1592 1602 else 1593 1603 .writeJavaParams(sw) … … 1887 1897 #_expr.writeJavaBreakdown(sw) 1888 1898 #sw.write('[.javaThis]') 1889 1899 sw.write(' : ') 1900 sw.write('String.format("assertion %s FAILED", ') 1901 #sw.write('"assertion " + ') 1902 tmpsw = CurlyWriter(StringWriter(), sw.curlyLineNumberTreatment) 1903 _expr.writeJavaDef(tmpsw) 1904 #sw.write(tmpsw.toString.replace('"', r'\"')) 1905 sw.write(Utils.javaStringLiteralFor(tmpsw.toString)) 1906 #sw.write('" + " FAILED "') 1907 sw.write(')') 1890 1908 if _info 1891 sw.write(' "')1909 sw.write(' + "info="+') 1892 1910 _info.writeJavaDef(sw) 1893 sw.write('"')1894 else1895 sw.write('"assertion ')1896 tmpsw = CurlyWriter(StringWriter(), sw.curlyLineNumberTreatment)1897 _expr.writeJavaDef(tmpsw)1898 sw.write(tmpsw.toString.replace('"', r'\"'))1899 sw.write(' FAILED"')1900 1911 sw.write(';\n') 1901 1912 sw.dedent 1902 1913 … … 2453 2464 sw.write(sep) 2454 2465 arg.writeJavaDefInContext(sw) 2455 2466 sep = ', ' 2467 if .hasMainArgs # for MainWrapper - pass through args fm main method 2468 sw.write('args') # same name(s) as inserted args on main method 2456 2469 sw.write(')') 2457 2470 2458 2471 def writeJavaBreakdownItems(sw as CurlyWriter) is override … … 2678 2691 on Treatment.AsIs 2679 2692 _expr.writeJavaDef(sw, parens) 2680 2693 on Treatment.InvokeRuntime 2681 sw.write(' CobraLangInternal.CobraImp.IsTrue(')2694 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.isTrue(') 2682 2695 _expr.writeJavaDef(sw, false) 2683 2696 sw.write(')') 2684 2697 on Treatment.CompareToZero 2685 sw.write('[lparen]0 !=')2698 sw.write('[lparen]0 != ') 2686 2699 _expr.writeJavaDef(sw, true) 2687 2700 sw.write(rparen) 2688 2701 on Treatment.CompareToZeroChar 2689 sw.write("[lparen]'\\0' !=")2702 sw.write("[lparen]'\\0' != ") 2690 2703 _expr.writeJavaDef(sw, true) 2691 2704 sw.write(rparen) 2692 2705 on Treatment.CompareToNull 2693 sw.write('[lparen] null!=')2706 sw.write('[lparen] null!= ') 2694 2707 _expr.writeJavaDef(sw, true) 2695 2708 sw.write(rparen) 2696 2709 … … 2790 2803 class Literal 2791 2804 is partial 2792 2805 2793 defasJava as String2806 get asJava as String 2794 2807 return '/* TODO_Literal */' 2795 2808 2796 2809 def writeJavaDef(sw as CurlyWriter, parens as bool) is override … … 2803 2816 get willWriteJavaBreakdownItems as bool is override 2804 2817 return false 2805 2818 2819 2820 2821 class BoolLit 2822 is partial 2823 2824 get asJava as String is override 2825 return if(_value, 'true', 'false') 2826 2827 2828 class CharLit 2829 is partial 2830 2831 get asJava as String is override 2832 if _value[0] to int == 39, return "'\\''" # single quote 2833 else, return "'" + _value.toString + "'" 2834 2835 2836 class DecimalLit 2837 is partial 2838 2839 get asJava as String is override 2840 return _value.toString(Utils.cultureInfoForNumbers) + '/*decimal*/' 2841 2842 2843 class FractionalLit 2844 is partial 2845 2846 get asJava as String is override 2847 if _type == .compiler.floatType(32), suffix = 'f' 2848 else if _type == .compiler.floatType(64), suffix = '' 2849 else if _type == .compiler.decimalType, suffix = '/*decimal*/' 2850 else, throw FallThroughException(_type) 2851 return _value.toString(Utils.cultureInfoForNumbers) + suffix 2852 2853 2854 class FloatLit 2855 is partial 2856 2857 get asJava as String is override 2858 # suppose you have the literal: 0.00001 2859 # using 'F' format for 'fixed point' gives '0.00' which loses the original value 2860 # using 'R' format for 'round trip' gives '1E-05' 2861 s = _value.toString('R', Utils.cultureInfoForNumbers) 2862 if s.indexOf('.') == -1 and 'E' not in s, s += '.0' 2863 if (.type to FloatType).size == 32, s += 'f' 2864 else, s += 'd' 2865 return s 2866 2806 2867 class IntegerLit is partial 2807 2868 2808 defasJava as String is override2869 get asJava as String is override 2809 2870 s = '' 2810 2871 if (info = .token.info) inherits int 2811 2872 branch info … … 2822 2883 return _value.toString + s 2823 2884 else 2824 2885 return '([s])[_value.toString]' 2825 2826 class BoolLit2827 is partial2828 2886 2829 def asJava as String is override2830 return if(_value, 'true', 'false')2831 2832 2833 class CharLit2834 is partial2835 2836 def asJava as String is override2837 if _value[0] to int == 39, return "'\\''" # single quote2838 else, return "'" + _value.toString + "'"2839 2840 2841 2887 class NilLiteral 2842 2888 is partial 2843 2889 2844 defasJava as String is override2890 get asJava as String is override 2845 2891 return 'null' 2846 2892 2847 2893 class StringLit is partial 2848 2894 2849 defasJava as String is override2895 get asJava as String is override 2850 2896 return Utils.javaStringLiteralFor(_string) 2851 2897 2852 2898 class StringSubstLit is partial … … 2875 2921 2876 2922 class BaseLit is partial 2877 2923 2878 defasJava as String is override2924 get asJava as String is override 2879 2925 return 'super' 2880 2926 2881 2927 2882 2928 class ThisLit is partial 2883 2929 2884 defasJava as String is override2930 get asJava as String is override 2885 2931 return .compiler.curBox.javaThis 2886 2932 2887 2933 2888 2934 class VarLit is partial 2889 2935 2890 defasJava as String is override2936 get asJava as String is override 2891 2937 return _name 2892 2938 2893 2939 class ToNilableOrNotExpr … … 3042 3088 assert _left.definition inherits IVar 3043 3089 _left.definition.ifInheritsStack = Stack<of IType>(_backUpIfInheritsStack) 3044 3090 3091 3092 class NumericPromoExpr is partial 3093 3094 def _writeJavaDefDynamic(sw as CurlyWriter) 3095 specs = OperatorSpecs.binaryOpSpecsByCobraText 3096 assert specs.containsKey(.token.text) 3097 spec = specs[.token.text] 3098 opText = Utils.javaStringLiteralFor(spec.opMethodName) 3099 sw.write('cobra.lang./*CobraLangInternal.*/CobraImp.DynamicOp([opText], ') 3100 _left.writeJavaDef(sw) 3101 sw.write(', ') 3102 _right.writeJavaDef(sw) 3103 sw.write(')') 3104 3105 3106 class AugAssignMathExpr is partial 3107 3108 def _writeJavaDef(sw as CurlyWriter) is override 3109 if .isConcated 3110 _writeJavaDefConcated(sw) 3111 else if _type.isDynamic 3112 _writeJavaDefDynamic(sw) 3113 else 3114 _writeJavaDefOperation(sw) 3115 3116 def _writeJavaDefConcated(sw as CurlyWriter) 3117 _left.writeJavaDef(sw, false) 3118 sw.write(' = ') 3119 sw.write('(' + _left.type.javaRef + ')') 3120 sw.write('CobraLangInternal.CobraImp.Concated(') 3121 _left.writeJavaDef(sw, false) 3122 sw.write(', ') 3123 _right.writeJavaDef(sw, false) 3124 sw.write(')') 3125 3126 def _writeJavaDefDynamic(sw as CurlyWriter) is override 3127 _left.writeJavaDef(sw) 3128 sw.write(' = ') 3129 specs = OperatorSpecs.binaryOpSpecsByCobraText 3130 assert specs.containsKey(.token.text) 3131 spec = specs[.token.text] 3132 opText = Utils.javaStringLiteralFor(spec.opMethodName) 3133 sw.write('CobraLangInternal.CobraImp.DynamicOp([opText], ') 3134 _left.writeJavaDef(sw) # TODO: add , false 3135 sw.write(', ') 3136 _right.writeJavaDef(sw) # TODO: add , false 3137 sw.write(')') 3138 3139 def _writeJavaDefOperation(sw as CurlyWriter) 3140 op = '' 3141 sep = ',' # for the method call case 3142 branch _op 3143 on 'PLUS_EQUALS' 3144 op = '+=' 3145 on 'MINUS_EQUALS' 3146 op = '-=' 3147 on 'STAR_EQUALS' 3148 op = '*=' 3149 on 'STARSTAR_EQUALS' 3150 #op = 'CobraLangInternal.CobraImp.PowerToEquals(' 3151 op = 'java.lang.Math.pow(' 3152 on 'SLASH_EQUALS' 3153 op = '/=' # TODO: finish this 3154 on 'SLASHSLASH_EQUALS' 3155 op = '/=' # TODO: finish this 3156 on 'PERCENT_EQUALS' 3157 op = '%=' 3158 else 3159 throw FallThroughException(_op) 3160 assert op.length 3161 if op.length==2 3162 _left.writeJavaDef(sw) 3163 sw.write(op) 3164 _right.writeJavaDef(sw) 3165 else 3166 sw.write(op) # ex: 'CobraLangInternal.CobraImp.Foo(' 3167 _left.writeJavaDef(sw) 3168 sw.write(sep) 3169 _right.writeJavaDef(sw) 3170 sw.write(')') 3171 3172 3173 class AugAssignBitwiseExpr 3174 is partial 3175 3176 def _writeJavaDef(sw as CurlyWriter) is override 3177 if _left.type.isDynamic 3178 _left.writeJavaDef(sw) 3179 sw.write(' = ') 3180 specs = OperatorSpecs.binaryOpSpecsByCobraText 3181 assert specs.containsKey(.token.text) 3182 spec = specs[.token.text] 3183 opText = Utils.javaStringLiteralFor(spec.opMethodName) 3184 sw.write('CobraLangInternal.CobraImp.DynamicOp([opText], ') 3185 _left.writeJavaDef(sw) # TODO: add , false 3186 sw.write(', ') 3187 _right.writeJavaDef(sw) # TODO: add , false 3188 sw.write(')') 3189 return 3190 op = '' 3191 branch _op 3192 on 'AMPERSAND_EQUALS' 3193 op = '&=' 3194 on 'VERTICAL_BAR_EQUALS' 3195 op = '|=' 3196 on 'CARET_EQUALS' 3197 op = '^=' 3198 on 'DOUBLE_LT_EQUALS' 3199 op = '<<=' 3200 on 'DOUBLE_GT_EQUALS' 3201 op = '>>=' 3202 else 3203 throw FallThroughException(_op) 3204 assert op.length 3205 _left.writeJavaDef(sw) 3206 sw.write(op) 3207 _right.writeJavaDef(sw) 3208 3209 3210 class BinaryBoolExpr 3211 is partial 3212 3213 def _writeJavaDef(sw as CurlyWriter) is override 3214 if _op=='IMPLIES' 3215 sw.write('!') 3216 _left.writeJavaDef(sw) 3217 branch _op 3218 on 'AND' 3219 sw.write('&&') 3220 on 'OR' or 'IMPLIES' 3221 sw.write('||') 3222 _right.writeJavaDef(sw) 3223 3224 def _writeJavaBreakdownItemsRight(sw as CurlyWriter) is override 3225 # have to respect the short circuit otherwise something like "s and s.length" will give 3226 # NullReference exception for "s.length" 3227 # solution is: given L and R, 3228 # write: "R", (!(L) ? "short-circuted" : (R).ToString()) 3229 # that's for 'AND'. for, 'OR', remove the !, for 'IMPLIES' it's like AND 3230 3231 # so rather than: 3232 # _right.writeJavaBreakdownItems(sw) 3233 # do this: 3234 src = Utils.javaStringLiteralFor(_right.toCobraSource) 3235 javaNot = if(_op=='OR', '', '!') 3236 sw.write(', [src], new CobraLangInternal.CobraDirectString([javaNot]') 3237 _left.writeJavaDefForBreakdown(sw) 3238 sw.write(' ? "(short-circuited)" : CobraLangInternal.CobraCore.ToTechString(') 3239 _right.writeJavaDefForBreakdown(sw) 3240 sw.write('))') 3241 3242 3243 3244 class BinaryBitwiseExpr 3245 is partial 3246 3247 def _writeJavaDef(sw as CurlyWriter) is override 3248 if _type.isDynamic 3249 _writeJavaDefDynamic(sw) 3250 return 3251 op = '' 3252 branch _op 3253 on 'AMPERSAND' 3254 op = '&' 3255 on 'VERTICAL_BAR' 3256 op = '|' 3257 on 'CARET' 3258 op = '^' 3259 on 'DOUBLE_LT' 3260 op = '<<' 3261 on 'DOUBLE_GT' 3262 op = '>>' 3263 else 3264 throw FallThroughException(_op) 3265 assert op.length 3266 _left.writeJavaDef(sw) 3267 sw.write(op) 3268 _right.writeJavaDef(sw) 3269 3270 3271 class BinaryMathExpr is partial 3272 3273 def _writeJavaDef(sw as CurlyWriter) is override 3274 if .isConcated 3275 _writeJavaDefConcated(sw) 3276 else if _type.isDynamic 3277 _writeJavaDefDynamic(sw) 3278 else 3279 _writeJavaDefOperation(sw) 3280 3281 def _writeJavaDefConcated(sw as CurlyWriter) 3282 sw.write('(' + _left.type.javaRef + ')') 3283 sw.write('CobraLangInternal.CobraImp.Concated(') 3284 _left.writeJavaDef(sw, false) 3285 sw.write(', ') 3286 _right.writeJavaDef(sw, false) 3287 sw.write(')') 3288 3289 def _writeJavaDefOperation(sw as CurlyWriter) 3290 intType = .compiler.anyIntType 3291 left = _left 3292 right = _right 3293 op = '' 3294 pre = '' 3295 sep = ',' # for the method call case 3296 branch _op 3297 on 'PLUS' 3298 op = '+' 3299 on 'MINUS' 3300 op = '-' 3301 on 'STAR' 3302 op = '*' 3303 on 'STARSTAR' 3304 #op = 'CobraLangInternal.CobraImp.PowerTo(' 3305 op = 'System.Math.Pow(' 3306 if _left.isKindOf(intType) and _right.isKindOf(intType) 3307 pre = '(' + .compiler.intType.javaRef + ')' 3308 on 'SLASH' 3309 op = '/' 3310 if _left.isKindOf(intType) and _right.isKindOf(intType) 3311 pre = '(' + .compiler.numberType.javaRef + ')' 3312 on 'SLASHSLASH' 3313 if left.isKindOf(intType) and right.isKindOf(intType) 3314 op = '/' 3315 else if left.isKindOf(.compiler.decimalType) or right.isKindOf(.compiler.decimalType) 3316 #op = 'System.Decimal.Floor(' 3317 op = 'java.lang.Math.floor(' 3318 sep = '/' 3319 else if left.isKindOf(.compiler.anyFloatType) or right.isKindOf(.compiler.anyFloatType) 3320 op = 'java.lang.Math.floor(' 3321 sep = '/' 3322 else 3323 throw FallThroughException([left.type, right.type]) 3324 on 'PERCENT' 3325 op = '%' 3326 else 3327 throw FallThroughException(_op) 3328 assert op.length 3329 sw.write(pre) 3330 if op.length==1 3331 _left.writeJavaDef(sw) 3332 sw.write(op) 3333 _right.writeJavaDef(sw) 3334 else 3335 sw.write(op) # ex: 'CobraLangInternal.CobraImp.Foo(' 3336 _left.writeJavaDef(sw) 3337 sw.write(sep) 3338 _right.writeJavaDef(sw) 3339 sw.write(')') 3340 3045 3341 class CompareExpr 3046 3342 is partial 3047 3343 … … 3244 3540 def _writeJavaDef(sw as CurlyWriter) is override 3245 3541 _left.writeJavaDef(sw) 3246 3542 sw.write(' instanceof ') 3247 _right.write SharpDef(sw, false)3543 _right.writeJavaDef(sw, false) 3248 3544 3249 3545 3250 3546 class ToExpr is partial … … 3508 3804 base.writeJavaBreakdownItems(sw) 3509 3805 # TODO 3510 3806 3511 class SharpExpr 3807 class SharpExpr # should become JavaExpr or BackEndExpr 3512 3808 is partial 3513 3809 3514 3810 def writeJavaDef(sw as CurlyWriter, parens as bool) is override … … 3555 3851 3556 3852 class ThisOrBaseLit is partial 3557 3853 3558 defasJava as String is override3854 get asJava as String is override 3559 3855 return 'this' 3560 3856 3561 3857 class ContractPart is partial -
Source/TestifyRunner.cobra
407 407 options['willRunExe'] = _willRunExes # internal, specific to testify 408 408 409 409 firstLine = '' 410 count0 = lines.count 410 411 rc = _processFirstlineDirectives(baseName, fileNames, inout lines, inout options, out firstLine) 411 412 if rc == 0, return 0 412 413 firstLineInsensitive = firstLine.trim.replace(' ', '') 413 414 nRemovedLines = count0 - lines.count 414 415 # Check for inline warning and error messages that are expected. 415 416 # (Starting in 2007-12 this is now the preferred way to specify these messages-- 416 417 # with the actual line of code that generates them. 417 418 # The old method of specifying at the top will still be needed for errors 418 419 # and warnings that have no associated line number.) 419 420 expectingError = false 420 inLineMessages = _getInlineMessages(lines, out expectingError)421 inLineMessages = _getInlineMessages(lines, nRemovedLines, out expectingError) 421 422 if inLineMessages.count > 0 # hasInlineMessages 422 423 return _testifyInlineMessages(inLineMessages, expectingError, 423 424 compilerVerbosity, [baseName], options, verbose ) 424 425 425 426 if firstLineInsensitive.startsWith('#.error.') 426 427 # deprecated: put errors on the lines where they occur. the "hasInlineMessages" code above will detect them. 427 # note that errors that are only detected by the backend C# compiler are not detectable by testify428 # Note that errors that are only detected by the backend C# compiler are not detectable by testify 428 429 # CC: support split with a String extension method 429 430 # error = firstLine.split('.error.',1)[1].trim.toLower 430 431 index = firstLine.indexOf('.error.') … … 548 549 549 550 return 1 # continue processing in caller 550 551 551 def _getInlineMessages(lines as List<of String>, expectingError as out bool) as Dictionary<of int, String>552 def _getInlineMessages(lines as List<of String>, offset as int, expectingError as out bool) as Dictionary<of int, String> 552 553 """ Walk lines and accumulate inline warnings and error messages. """ 553 554 inLineMessages = Dictionary<of int, String>() 554 lineNum = 1 555 firstLine = 1 + offset 556 lineNum = firstLine 555 557 expectingError = false 556 558 for line in lines 557 if lineNum > 1and ('.warning.' in line or '.error.' in line)559 if lineNum > firstLine and ('.warning.' in line or '.error.' in line) 558 560 if '.warning.' in line 559 561 message = line[line.indexOf('.warning.') + '.warning.'.length:] 560 562 messageType = 'w' -
Tests/100-basics/050-decimal.cobra
1 #.require. clr 2 # revisit this for Java when decide and implement what to do about Decimal Type 1 3 namespace Test 2 4 3 5 class Test -
Tests/100-basics/052-float.cobra
1 # .require. clr 2 # This is clr specific re inheritance of literals and floats 1 3 namespace Test 2 4 3 5 class Test -
Tests/100-basics/052j-float.cobra
1 # .require. jvm 2 namespace Test 3 4 class Test 5 6 def main 7 is shared 8 9 f as float = 1.0f 10 assert f 11 assert f==1.0f 12 assert f==1 13 14 sum as float = 0.1f+0.1f+0.1f+0.1f+0.1f+0.1f+0.1f+0.1f+0.1f+0.1f 15 assert sum<>1.0f 16 assert sum<>0.1f*10 17 18 ff = Float(1.0f) 19 assert ff inherits Float # .warning. is always 20 ii = Integer(1) 21 #assert not (ii inherits Float) # .warning. is never 22 # above also throws compiler error 23 o as Object = ii 24 assert not (o inherits Float) 25 26 g as float = 2f 27 assert g 28 assert g == 2.0f 29 assert g == 2.00f 30 assert g == 2 31 assert g == f + f 32 33 # small numbers 34 a = 0.00001f 35 b = 0.000001f 36 assert a > b 37 38 # can assign ints to floats 39 f = 7 40 41 # can compare ints and floats 42 assert f > 0 43 assert 0 < f