Ticket #275: java-jvm-6.patch
File java-jvm-6.patch, 66.3 KB (added by hopscc, 13 years ago) |
---|
-
Source/Members.cobra
63 63 var _matchingBaseMember as IBoxCodeMember? 64 64 var _sharedMethodBacking as String? 65 65 var _sharedMethodBackingIsAlias as bool 66 var _aliasedMethodBacking as String? 66 67 var _binaryName as String? 67 68 68 69 cue init(token as IToken, idToken as IToken, parentBox as Box, name as String, isNames as String*, attribs as AttributeList) … … 108 109 109 110 pro sharedMethodBackingIsAlias from var 110 111 112 pro aliasedMethodBacking from var 113 111 114 get testMethods as IList<of TestMethod> 112 115 if _testMethods is nil, _testMethods = List<of TestMethod>() 113 116 return _testMethods to ! -
Source/BackEndObjC/ObjcBackEnd.cobra
86 86 def cobraNameForNativeBoxName(nativeBoxName as String) as String is override 87 87 return nativeBoxName # TODO 88 88 89 def isRunnableFile( fullExeFileName as String) as bool is override 90 return true # may need extending 91 89 92 # Types 90 93 get objectTypeProxy as AbstractTypeProxy is override 91 94 """Type proxy for BE root of Object hierarchy.""" -
Source/Compiler.cobra
146 146 on the instance. 147 147 """ 148 148 149 def isRunnableFile( fullExeFileName as String) as bool is abstract 150 """Test if given filename is an executable ( vs a library or something else) """ 151 149 152 # Native Types access 150 153 def cobraNameForNativeBoxName(name as String) as String is abstract 151 154 """ … … 259 262 def installNativeMethods(box as Box, nativeType as NativeType) is override 260 263 pass 261 264 265 def isRunnableFile(fullExeFileName as String) as bool is override 266 return true 267 262 268 # Native Type access 263 269 def cobraNameForNativeBoxName(name as String) as String is override 264 270 return name + '_BBE' … … 658 664 .options = options 659 665 bar = '----------------------------------------------------------------------------------------------------' 660 666 .initBackEnd 667 661 668 .defaultOutName = if(.options.buildStandardLibrary, 'Cobra.Lang.dll', fileNames[0]) 662 669 _pathsToCompile = fileNames 663 670 hasErrors = false … … 1349 1356 return type to ! 1350 1357 1351 1358 def _libraryType(names as vari String) as IType 1352 # printnames1359 #trace names 1353 1360 ns as IContainer = _globalNS 1354 1361 thing as IContainer? = nil 1355 1362 for name in names 1356 1363 possible = (thing ? ns).declForName(name) 1357 1364 #print name 1365 # dbg 1366 #if not possible 1367 # trace thing ? ns 1368 # ((thing ? ns) to NameSpace).dumpDeclsNameKeys 1358 1369 assert possible, name 1359 1370 if possible inherits IContainer 1360 1371 thing = possible -
Source/Cobra.Lang/Java/InvariantException.java
1 /* 2 * java code for cobra Invariant exception 3 * thrown when an invariant failure detected (Contracts) 4 * 5 * 6 */ 7 8 package cobra.lang; 9 10 import java.util.*; 11 12 13 public class InvariantException extends AssertException 14 { 15 public InvariantException(/*SourceSite*/ Object sourceSite, 16 java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*dynamic? */) 17 { 18 this(sourceSite, expressions, thiss, info, null); 19 } 20 21 public InvariantException(/*SourceSite*/ Object sourceSite, 22 java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*dynamic? */, 23 Exception cause) 24 { 25 super(sourceSite, expressions, thiss, info, cause); 26 } 27 } -
Source/Cobra.Lang/Java/AssertException.java
1 1 /* 2 * java code for cobra assert exception ( placeholder currently)3 * Initially using java assertion till this is working2 * java code for cobra assert exception 3 * ( Root class of Cobra Assertions and contracts exceptions) 4 4 * 5 5 * Exceptions for Assertions, contracts, etc. 6 6 */ … … 10 10 import java.util.*; 11 11 12 12 13 class AssertException extends RuntimeException //implements IHasSourceSite, HasAppendNonPropertyKeyValues13 public class AssertException extends RuntimeException //implements IHasSourceSite, HasAppendNonPropertyKeyValues 14 14 // has DetailedStackTrace(false) 15 15 { 16 16 protected Object _this; … … 36 36 _info = info; 37 37 } 38 38 39 public AssertException(/*SourceSite*/ Object sourceSite, Object[] expressionsArr /*dynamic */, 40 Object thiss, Object info /*dynamic? */) 41 { 42 this(sourceSite, expressionsArr, thiss, info, null); 43 } 44 45 public AssertException(/*SourceSite*/ Object sourceSite, Object[] expressionsArr /*dynamic */, 46 Object thiss, Object info /*dynamic?*/, Exception innerExc) 47 { 48 super("assert", innerExc); 49 _sourceSite = sourceSite; 50 _expressions = Arrays.asList(expressionsArr); 51 _this = thiss; 52 _info = info; 53 } 54 39 55 // Property this 40 56 public Object getThis() { return _this; } 41 57 … … 142 158 */ 143 159 144 160 } 145 146 class InvariantException extends AssertException147 {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 }161 162 class RequireException extends AssertException163 {164 protected RequireException _next;165 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 next184 public RequireException getNext() { return this._next;}185 public void setNext(RequireException value) { this._next = value; }186 }187 188 189 class EnsureException extends AssertException190 {191 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 }199 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 }209 210 class NonNilCastException extends AssertException211 {212 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 }220 221 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 }230 231 @Override232 public String getMessage() {233 return String.format("Cast to non-nil failed.%s%s", this.nl, super.getMessage() ) ;234 }235 }236 237 238 239 /* ## Misc exceptions240 241 class ExpectException inherits Exception242 243 cue init(expectedExceptionType as Type, actualException as Exception?)244 base.init245 _expectedExceptionType = expectedExceptionType246 _actualException = actualException247 248 get expectedExceptionType from var as Type249 250 get actualException from var as Exception?251 252 get message as String? is override253 sb = StringBuilder()254 sb.append('Expecting exception: [_expectedExceptionType.name], but ')255 if _actualException256 sb.append('a different exception was thrown: [_actualException]')257 else258 sb.append('no exception was thrown.')259 return sb.toString260 261 262 class FallThroughException inherits Exception263 264 cue init265 .init(nil)266 pass267 268 cue init(info as Object?)269 base.init270 _info = info271 272 cue init(info as Object?, innerExc as Exception?)273 base.init(nil, innerExc)274 _info = info275 276 get message as String is override277 return 'info=[CobraCore.toTechString(_info)]'278 279 get info from var as Object?280 281 282 class SliceException inherits SystemException283 284 cue init(msg as String?)285 base.init286 */ -
Source/Cobra.Lang/Java/EnsureException.java
1 /* 2 * java code for cobra Ensure exception 3 * thrown when a contracts postcondition fails. 4 */ 5 6 package cobra.lang; 7 8 import java.util.*; 9 10 11 public class EnsureException extends AssertException 12 { 13 14 public EnsureException(/*SourceSite*/ Object sourceSite, 15 java.util.List<Object> expressions /*dynamic */, 16 Object thiss, 17 Object info /*dynamic? */) 18 { 19 this(sourceSite, expressions, thiss, info, null); 20 } 21 22 public EnsureException(/*SourceSite*/ Object sourceSite, 23 java.util.List<Object> expressions /*dynamic */, 24 Object thiss, 25 Object info /*dynamic? */, 26 Exception cause) 27 { 28 super(sourceSite, expressions, thiss, info, cause); 29 } 30 } 31 -
Source/Cobra.Lang/Java/PkgSig.java
279 279 int m = theClass.getModifiers(); 280 280 //if( java.lang.reflect.Modifier.isPublic(m) ) 281 281 //if( ! java.lang.reflect.Modifier.isPrivate(m) ) 282 if( Modifier.isPublic(m) || Modifier.isProtected(m) ) 282 if( Modifier.isPublic(m) || Modifier.isProtected(m) ) { 283 283 allClasses.add( theClass ); 284 284 } 285 286 // special case for pkgPrivate java.lang.AbstractStringBuilder parent of public String{Buffer,Builder} 287 if ( ClassSig.isPkgPrivate(m) && theClass.getName().equals("java.lang.AbstractStringBuilder") ) { 288 allClasses.add( theClass ); 289 } 290 285 291 // skip interfaces 286 292 //if( theClass.isInterface() ){ 287 293 // continue; … … 475 481 this.indent--; 476 482 } 477 483 478 public boolean isPkgPrivate(int m) {484 static public boolean isPkgPrivate(int m) { 479 485 // if (!cobraGen) 480 486 // return false 481 487 … … 601 607 printIndent(); 602 608 String typeName = f.getType().getName(); 603 609 System.out.printf("%s\n", typeName); 604 if ( f.getType().isEnum()) { 610 //if ( f.getType().isEnum()) { 611 if ( f.isEnumConstant()) { 605 612 this.indent++; 606 613 printIndent(); 607 614 System.out.printf("%d\n", Enum.valueOf( this.cls, f.getName()).ordinal() ); -
Source/Cobra.Lang/Java/DynamicOperationException.java
14 14 // The base class for all dynamic operation exceptions. 15 15 //""" 16 16 17 public DynamicOperationException(String message) { this(message, n il); }18 public DynamicOperationException(String message, cause as Exception) {super(message, cause); }17 public DynamicOperationException(String message) { this(message, null); } 18 public DynamicOperationException(String message, Exception cause) {super(message, cause); } 19 19 } 20 20 21 21 class CannotEnumerateException extends DynamicOperationException 22 22 { 23 public CannotEnumerateException (String message) {this(message, n il); }23 public CannotEnumerateException (String message) {this(message, null); } 24 24 public CannotEnumerateException (String message, Exception cause) {super(message, cause); } 25 25 } 26 26 … … 30 30 protected String _name; 31 31 Class _type; 32 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)33 public UnknownMemberException(Object obj, String name, Class type) { this(obj, name, type, null);} 34 public UnknownMemberException(Object obj, String name, Class type, Exception cause) 35 35 { 36 36 super(String.format("obj=%s, name=%s, type=%s", 37 37 CobraCore.toTechString(obj), CobraCore.toTechString(name), type), 38 38 cause); 39 39 this._obj = obj; 40 40 this._name = name; 41 this. type = type;41 this._type = type; 42 42 } 43 43 } 44 44 -
Source/Cobra.Lang/Java/mkjarOnly
5 5 6 6 [ -d classes ] || mkdir classes 7 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 EXCEPTIONS="AssertException.java InvariantException.java RequireException.java EnsureException.java NonNilCastException.java DynamicOperationException.java" 9 javac -d classes SourceSite.java CobraImp.java CobraCore.java Delegate.java ${EXCEPTIONS} CobraDirectString.java 9 10 [ $? == 0 ] || exit 10 11 jar cvf CobraLang.jar -C classes . 11 12 [ $? == 0 ] || exit -
Source/Cobra.Lang/Java/NonNilCastException.java
1 /* 2 * java code for cobra NonNil Cast exception. 3 * Thrown when Null check for non nullable instance fails. 4 */ 5 6 package cobra.lang; 7 8 import java.util.*; 9 10 11 public class NonNilCastException extends AssertException 12 { 13 14 public NonNilCastException(/*SourceSite*/ Object sourceSite, 15 java.util.List<Object> expressions /*dynamic */, 16 Object thiss, 17 Object info /*dynamic? */) 18 { 19 this(sourceSite, expressions, thiss, info, null); 20 } 21 22 23 public NonNilCastException(/*SourceSite*/ Object sourceSite, 24 java.util.List<Object> expressions /*dynamic */, 25 Object thiss, 26 Object info /*dynamic? */, 27 Exception cause ) 28 { 29 super(sourceSite, expressions, thiss, info, cause); 30 } 31 32 @Override 33 public String getMessage() { 34 return String.format("Cast to non-nil failed.%s%s", this.nl, super.getMessage() ) ; 35 } 36 } 37 38 39 40 /* ## Misc exceptions 41 42 class ExpectException inherits Exception 43 44 cue init(expectedExceptionType as Type, actualException as Exception?) 45 base.init 46 _expectedExceptionType = expectedExceptionType 47 _actualException = actualException 48 49 get expectedExceptionType from var as Type 50 51 get actualException from var as Exception? 52 53 get message as String? is override 54 sb = StringBuilder() 55 sb.append('Expecting exception: [_expectedExceptionType.name], but ') 56 if _actualException 57 sb.append('a different exception was thrown: [_actualException]') 58 else 59 sb.append('no exception was thrown.') 60 return sb.toString 61 62 63 class FallThroughException inherits Exception 64 65 cue init 66 .init(nil) 67 pass 68 69 cue init(info as Object?) 70 base.init 71 _info = info 72 73 cue init(info as Object?, innerExc as Exception?) 74 base.init(nil, innerExc) 75 _info = info 76 77 get message as String is override 78 return 'info=[CobraCore.toTechString(_info)]' 79 80 get info from var as Object? 81 82 83 class SliceException inherits SystemException 84 85 cue init(msg as String?) 86 base.init 87 */ -
Source/Cobra.Lang/Java/RequireException.java
1 /* 2 * java code for cobra Require exception 3 * thrown when a contract precondition test fails 4 */ 5 6 package cobra.lang; 7 8 import java.util.*; 9 10 11 public class RequireException extends AssertException 12 { 13 protected RequireException _next; 14 15 public RequireException(/*SourceSite*/ Object sourceSite, 16 java.util.List<Object> expressions /*dynamic */, 17 Object thiss, 18 Object info /*dynamic? */) 19 { 20 this(sourceSite, expressions, thiss, info, null); 21 } 22 23 public RequireException(/*SourceSite*/ Object sourceSite, 24 java.util.List<Object> expressions /*dynamic */, 25 Object thiss, 26 Object info /*dynamic? */, 27 Exception cause ) 28 { 29 super(sourceSite, expressions, thiss, info, cause); 30 } 31 32 //Property RequireException next 33 public RequireException getNext() { return this._next;} 34 public void setNext(RequireException value) { this._next = value; } 35 } 36 -
Source/Cobra.Lang/Java/CobraImp.java
77 77 return s; 78 78 } 79 79 80 static public Object checkNonNil(Object obj, String sourceCode, Object value, /* SourceSite */ String fileName, int lineNum, String className, String memberName, Object thiss) 80 @SuppressWarnings("unchecked") 81 static public <T> List<T> makeList(T... args) { 82 return new ArrayList<T>(Arrays.asList(args)); 83 } 84 85 /* 86 @SuppressWarnings("unchecked") 87 static public <T> List<T> makeList(T... args) { 88 List<T> l = new ArrayList<T>(); 89 for (T arg : args) { 90 l.add(arg); 91 } 92 return l; 93 } 94 */ 95 96 @SuppressWarnings("unchecked") 97 static public <T> Set<T> makeSet(T... args) { 98 return new HashSet<T>(Arrays.asList(args)); 99 } 100 101 @SuppressWarnings("unchecked") 102 static public <K,V> Map<K,V> makeDict( Object... args) { 103 Map<K,V> d = new HashMap<K,V>(); 104 for (int i=0; i<args.length; i+=2) 105 d.put((K)args[i], (V)args[i+1]); //[unchecked] warning here 106 return d; 107 } 108 109 110 static public <T> T checkNonNil(Object obj, String sourceCode, T value, /* SourceSite */ String fileName, int lineNum, String className, String memberName, Object thiss) 81 111 { 82 112 // used for "x to !" and "someNilable to SomethingNotNilable" 83 113 if (value == null) { -
Source/Container.cobra
169 169 body 170 170 #print _declsByName.keys 171 171 return if(_declsByName.containsKey(name), _declsByName[name], nil) 172 172 173 # for debug 174 def dumpDeclsNameKeys 175 print _declsByName.keys 176 173 177 def declForName(name as String) as IMember? 174 178 implements IContainer 175 179 return if(_declsByName.containsKey(name), _declsByName[name], nil) -
Source/BackEndClr/ClrBackEnd.cobra
142 142 def fixMemberSigs is override 143 143 .compiler.dotNetFixNilableMemberSigs # in ScanClrType 144 144 145 def isRunnableFile(fullExeFileName as String) as bool is override 146 """Test if filename is runnable ( vs a library or something else) """ 147 return fullExeFileName.endsWith('.exe') 148 145 149 # Types 146 150 get objectTypeProxy from var is override 147 151 """Type proxy for BE root of Object hierarchy.""" -
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
26 26 """All classes found in all jars keyed by canonical/full name.""" 27 27 28 28 29 var nameRemaps = {29 var virtualNameRemaps = { 30 30 'java.lang.Decimal' : 'java.lang.Double', # BigDecimal eventually with (lotta) codegen support 31 31 'java.lang.UByte' : 'java.lang.Short', 32 32 'java.lang.UShort' : 'java.lang.Integer', … … 42 42 This is intended to be the only way to access the JarSig classCache contents from outside this file. 43 43 """ 44 44 assert fullCobraName[0].isUpper 45 #fullCobraName = . nameRemaps.get(fullCobraName, fullCobraName)45 #fullCobraName = .virtualNameRemaps.get(fullCobraName, fullCobraName) 46 46 parts = fullCobraName.split('.') 47 47 for i in 0: parts.length-1 48 48 parts[i] = parts[i][0].toLower.toString + parts[i][1:] … … 188 188 _genTypesList 189 189 _aliasPrimitives 190 190 191 if jarName == 'rt.jar' # special for system jarfile 192 # these name remaps will probably need some codegen special handling. 193 _dupVirtuals 194 _nonGenericCommon 195 196 197 191 198 def _genTypesList 192 199 jarName = if(.name.endsWith('.sig'), .name[:-4], .name) 193 200 fileName = JarSig.sigFile(jarName) … … 236 243 JarSig.classByNameCache['float'] = JarSig.classByNameCache['java.lang.Float'] 237 244 JarSig.classByNameCache['double'] = JarSig.classByNameCache['java.lang.Double'] 238 245 239 # these name remaps will probably need some codegen special handling.240 _dupVirtuals241 _nonGenericCommon242 243 246 def _dupVirtuals 244 for dupName in .nameRemaps.keys 245 dupOf = .nameRemaps[dupName] 247 # Make cache and jar export entries for virtualised types that dont exist in java 248 # but cobra has and expects to be distinct. They get remapped to an existing Java Type 249 for dupName in .virtualNameRemaps.keys 250 dupOf = .virtualNameRemaps[dupName] 246 251 _dupClassTo(dupOf, dupName) 247 252 248 253 def _nonGenericCommon 249 # pass254 # spoof generic Instances for cobra non generic Types that java genericises 250 255 # 'java.util.Collection' : 'java.util.Collection<Object>', 251 256 #_dupClassTo( 'java.util.Collection', 'java.util.Collection<Object>') 252 257 _makeGenericInstance('java.util.Collection<Object>') # for ICollection/Java.Util.Collection<of Object> 253 258 # probably others yet 254 259 255 260 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 261 if JarSig.classByNameCache.containsKey(asName) # already cached 262 ct = JarSig.classByNameCache[asName] 263 else 264 ct = JarSig.classByNameCache[dupOfName] 265 parts = asName.split('.') 266 name = parts[parts.length-1] 267 package = parts[0:-1].join('.') # all but last 268 ct = ct.copy(name, package) 269 JarSig.classByNameCache[asName] = ct 262 270 _javaTypes.add(ct) 263 271 264 272 def _makeGenericInstance(fullName as String) 265 273 # cached AND exposed to namespace 266 274 assert fullName.contains('<') 267 .addGenericInstClass(fullName) 275 if not JarSig.classByNameCache.containsKey(fullName) # already cached 276 .addGenericInstClass(fullName) 268 277 giCls = JarSig.classByNameCache[fullName] 269 print giCls.canonicalName278 #print giCls.canonicalName 270 279 _javaTypes.add(giCls) 271 #_registerClassType(giCls)272 280 273 281 def getExportedTypes as JavaClassType* 274 282 return _javaTypes … … 403 411 field.modifiers = _parseList(_popTop(lines), [c' ']) 404 412 field.typeName = _popTop(lines) 405 413 if type == JavaType.JavaEnum and field.typeName == absName #'[pkg].[name]' 406 field.value = _popTop(lines) 414 t = _peekTop(lines) 415 if t.length - t.trimStart.length > 8 416 field.value = _popTop(lines) 407 417 #field.attributes = _parseList(_popTop(lines)) 408 418 fieldList.add(field) 409 419 … … 486 496 if not e.length, continue 487 497 break 488 498 return e.trim 499 500 def _peekTop(content as List<of String>) as String is shared 501 if content.count == 0 502 return '' 503 return content[0] 504 489 505 490 506 # property: get<Propname> and no paramList and returnType is Property Type or 491 507 # is<PropName> and no paramList and returnType is bool … … 602 618 # special case naming weirdnesses of Java lib classes 603 619 if .canonicalName == 'java.lang.String' 604 620 getterName, setterName = 'charAt', '' 621 else if .canonicalName.startsWith('java.util.List`') 622 getterName, setterName = 'get', 'set' 623 else if .canonicalName.startsWith('java.util.Map`') 624 getterName, setterName = 'get', 'put' 605 625 else 606 626 for ifcName in .interfaceNames # TODO also chase up interface inheritance tree 607 if ifcName.startsWith('java.util.List ')627 if ifcName.startsWith('java.util.List`') 608 628 getterName, setterName = 'get', 'set' 609 else if ifcName.startsWith('java.util.Map ')629 else if ifcName.startsWith('java.util.Map`') 610 630 getterName, setterName = 'get', 'put' 611 631 612 632 #TODO also check for specially annotated methods … … 614 634 assert getterName.length 615 635 getMethod, setMethod = _lookForMethods(getterName, setterName) 616 636 if getMethod or setMethod 617 idxrProp = _genAProp('_synthesizedIdxr', getMethod, setMethod, true)637 idxrProp = _genAProp('[.canonicalName]_synthesizedIdxr', getMethod, setMethod, true) 618 638 _props.add(idxrProp) 619 639 _indexer = idxrProp 620 print 'dbg: [.canonicalName] has IndexerMethods [getterName] and [setterName] ' 640 sb = StringBuilder('= ') 641 if getMethod 642 sb.append(getterName) 643 if setMethod, sb.append(',') 644 if setMethod 645 sb.append(setterName) 646 print 'dbg: [.canonicalName] indexerMethods [sb.toString] ' 621 647 #else 622 648 # print 'dbg: No IndexerMethods [getterName]/[setterName] on [.canonicalName]' 623 649 … … 1150 1176 sb = StringBuilder('def [nampar] ') 1151 1177 if .returnTypeName.length 1152 1178 sb.append('as [.returnTypeName] ') 1179 else 1180 sb.append('as ??? ') 1153 1181 if .modifiers.count 1154 1182 sb.append('is ') 1155 1183 sep='' -
Source/BackEndJvm/to-do.text
3 3 Require Base version Java to be java7 4 4 gain strings in case stmt for free (!) 5 5 6 Indexers on Generics ( List<of String>) 7 - Not recognising/setup indexer record on JavaClass (or searching inheritance hier List<String> ^ List<E>... 8 - seems to be missing NativeType entry should be List<of String> -> List<String> 9 - (unfortunately) like commandLineArgs (065j-indexing.cobra) 6 10 11 Add code for generating attributes from 'has XXXXX' 12 - chk cobra syntax allows AttribName(value[, value]) like ctor not just AttribName ? 13 14 executable autgen jarfile 15 gen srcs into own dir ./java 16 compile classes into own dir ./classes 17 generate exe jarfile ( auto manifest file) ./<exename>.jar 18 remove unlise -kif generated java files 19 remove intermediate classfiles 20 run as java -cp '<otherRefs...>' -jar App.jar args.... 21 7 22 include-tests:no - remove Test invocation call 8 23 9 24 10 25 _fixNativeMethods - static method entries on box instance 11 26 12 27 13 fixup Object namespace for X-compile so items like System.Object are rooted off 14 java.lang namespace ( rather than .Net system) 15 DONE June-2011 28 Get Testifyrunner working on java gen 16 29 17 30 passthru compilation of *.java files 18 31 - seems to work for single files But 19 32 - calc of main class fm passthru *.java files 20 33 21 computeOutName from name of main class (or first/only) class in file rather22 than permutation of input name23 DONE 31-Jan-201124 25 34 26 35 cobra namespaces capitalized (as .Net) Java all lowercase 27 36 - convert namespaces in java code to lowcase … … 41 50 ( look for calls to .capitalized) 42 51 DONE (I think) 43 52 44 remove all uses of ClrNativeType in core compiler ( ->NativeType??)45 Compiler/Enums/Types.cobra46 DONE47 48 53 properties - pro/get/set 49 54 - auto convert to java getters/setters and map calls 50 55 - Whats the equiv for indexers? … … 107 112 If lookup for name fails see if sig matches extension and remap call to extn static class method 108 113 109 114 110 Parse error lines fm java giving source line, find (trailing comment) cobra111 line number and modify the java error msg line with the cobra lineno112 printing that in any java error mesages so to relate the java error back113 to the generating cobra code line.114 - start with just spew the javac lines to output115 - assemble into ErrorMessage Line and 'supporting lines associated with it - keeps error line count in sync116 DONE117 115 118 116 119 117 single file: … … 122 120 run class file 123 121 124 122 If specify multiple files 125 generate th m all to java src in in namespace dir hier126 compile to class files ( 123 generate them all to java src in in namespace dir hier 124 compile to class files (in class dir hier) 127 125 generate manifest file and generate classfiles to jar file 128 126 Leave jar file at root of hierarchy 129 127 -> single or multiple files just gen an executable jarfile 130 128 131 129 add synonym for sharp''/sharp"" -> java''/java"" 132 130 or general be''/be""/backend'' (for backend) … … 145 143 java specify with @interface and Metainfo 146 144 e.g @Documented //we want the annotation to show up in the Javadocs 147 145 @Retention(RetentionPolicy.RUNTIME)) 148 146 149 147 Java has Set in its collections framework so use that instead of Cobra lib version. 150 148 151 149 Cobra methods nonVirtual (C# not marked virtual) in java mark as final (Cannot redefine or override). … … 217 215 218 216 Instead use google collections/Guava 219 217 - support for List, Set and Map literals 218 com.google.common.collect 219 l = [lit,lit,...] List<InferredType> l = Lists.newArrayList<InferredType>( lit, lit, ....); 220 OR (immutable) List<InferredType> l = new ArrayList<InferredType>( Arrays.asList(lit, lit, ....)); 221 (mutable) List<InferredType> l = new ArrayList<InferredType>( new ArrayList(Arrays.asList(lit, lit, ....))); 222 223 m = {a:b, ...} Map<InferredK, InferredV> m = Maps.newHashMap<>(); m.put(a,b); ... 224 (Immutable - up to 5 entries) ImmutableMap<InferredfTypeKey,InferredTypeValue> m = ImmutableMap.of(a, b, ...); 225 (Immutable any #) ImmutableMap<InferredfTypeKey,InferredTypeValue> m = ImmutableMap.Builder<InferredfTypeKey,InferredTypeValue>().put(a, b)... (.put(c.d)...}.build(); 226 (Mutable) Make immutable map and 227 Map m = new HashMap<inferredK,inferredV>(immutableMap) OR 228 Map m = Maps.newHashMap<inferredK,inferredV>(mutableMap) 229 OR 230 add CobraMutableMap<K,V> inherits HashMap - adds ctor taking varargs list of k,v) 231 Map m = new CobraMutableMap<K,V>(a,b,...) 232 OR static factory 233 CobraCore.fillHashMap(new HashMap<K,V>(), a,b,...) 234 OR (http://blogs.steeplesoft.com/2011/10/funky-object-initialization/ ) 235 Map m = new HashMap<inferredK,inferredV>() { { 236 put(a,b); 237 ...; 238 } }; 239 Wait for Java8 and hope have implemented List and Map literals 240 220 241 - Simple file reading API 221 242 243 244 222 245 ensure support ( as builtin alternative) for jikes compiler. 223 246 https://sourceforge.net/projects/jikes/files/Jikes/ 224 247 … … 484 507 485 508 = Other back ends = 486 509 Fantom : compile to jvm or dotNet 510 511 ----------------------------------------------- 512 Done 513 fixup Object namespace for X-compile so items like System.Object are rooted off 514 java.lang namespace ( rather than .Net system) 515 DONE June-2011 516 517 518 computeOutName from name of main class (or first/only) class in file rather 519 than permutation of input name 520 DONE 31-Jan-2011 521 522 remove all uses of ClrNativeType in core compiler ( ->NativeType??) 523 Compiler/Enums/Types.cobra 524 DONE 525 526 Parse error lines fm java giving source line, find (trailing comment) cobra 527 line number and modify the java error msg line with the cobra lineno 528 printing that in any java error mesages so to relate the java error back 529 to the generating cobra code line. 530 - start with just spew the javac lines to output 531 - assemble into ErrorMessage Line and 'supporting lines associated with it - keeps error line count in sync 532 DONE 533 -
Source/BackEndJvm/ScanJvmType.cobra
184 184 _fix('Java.Lang.Object', 'toString getClass clone') 185 185 # ^ regarding .toString, not technically true, but common enough and life is too painful when the return type is nilable 186 186 #_fix('java.lang.System', 'out') #stdout 187 _fix('Java.Lang.String', 'concat remove replace replaceAll replaceFirst substring toLowerCase toUpperCase trim format')187 _fix('Java.Lang.String', r'[] length charAt concat remove replace replaceAll replaceFirst substring toLowerCase toUpperCase trim format') 188 188 #_fix('System.Type', 'assembly name toString') 189 189 # namespace can return nil if the Type is a generic parameter 190 190 #_fix('System.Environment', 'commandLine currentDirectory newLine version') … … 340 340 return .name == 'Exception' and .parentNameSpace and .parentNameSpace.fullName == 'Java.Lang' 341 341 342 342 def prepSystemObjectClassJvm 343 # TODO chk thats this has desired result. 343 # TODO chk thats this has desired result. 344 344 # map method getType to java getClass 345 345 # C#'s typeof(X) is X.getType in Cobra. 346 346 #existing = .declForName('getClass') to BoxMember 347 347 #overload = MemberOverload(existing) 348 348 #.registerOverload(overload) 349 349 meth = Method(TokenFix.empty, TokenFix.empty, this, 'getType', List<of Param>(), .compiler.typeTypeProxy, nil, ['shared'], AttributeList(), 'Returns the Type instance that defines this type.') 350 meth. sharedMethodBacking = 'getClass'350 meth.aliasedMethodBacking = 'getClass' 351 351 #meth.sharedMethodBackingIsAlias = true # not static 352 352 #overload.addMember(meth) 353 353 .addDecl(meth) … … 398 398 if (lastDecl to Object).getType.getProperty('ParentBox') # CC: if lastDecl responds to (get parentBox as Box?) 399 399 lastDecl.parentBox = this 400 400 401 401 def _isStaticConstant( fi as JavaFieldInfo) as bool 402 return fi.isStatic or fi.name == fi.name.toUpper 403 402 404 def _scanJvmFields 403 405 for fieldInfo in _jvmType.getFields 404 406 #if fieldInfo.declaringType is not _jvmType, continue 405 407 if fieldInfo.isDefault, continue # pkgprivate 406 408 if fieldInfo.isPrivate, continue 407 name = Utils.cobraNameForNativeMemberName(fieldInfo.name) 409 # Unlike C# leave all static constant fieldnames ((mostly) upcase) as is 410 name = if( _isStaticConstant(fieldInfo), fieldInfo.name, Utils.cobraNameForNativeMemberName(fieldInfo.name)) 408 411 type = _jvmMemberTypeResultProxy(fieldInfo, fieldInfo.type) 409 412 attrs = AttributeList() 410 413 if fieldInfo.isProtected … … 490 493 if propInfo.isWritable 491 494 prop.makeSetPart(TokenFix.empty) 492 495 if _declsByName.containsKey(prop.name) # for # Double.naN 493 print 'DUP name exists already for property "[prop.name]" on', /#_declsByName[prop.name],#/ .name 496 # unfortunately its common for java libs to use method length() rather than getLength() 497 # lose this when enable postSigFixups handling 498 if prop.name <> 'length' 499 print 'DUP name exists already for property "[prop.name]" on', /#_declsByName[prop.name],#/ .name 494 500 return # just drop the property; field or method still available 495 501 .addDecl(prop) 496 502 -
Source/BackEndJvm/JvmBackEnd.cobra
41 41 'bool' : 'Java.Lang.Boolean', # boolean 42 42 'char' : 'Java.Lang.Character',# char 43 43 'decimal': 'Java.Lang.Decimal', # virtualised -> Double 44 'float': 'Java.Lang.Float', # float 45 'float32': 'Java.Lang.Float', # float 46 'float64': 'Java.Lang.Double', # double 44 47 'single': 'Java.Lang.Float', # float 45 48 'double': 'Java.Lang.Double', # double 46 49 'sbyte' : 'Java.Lang.Byte', # byte … … 169 172 def cobraNameForNativeBoxName(nativeBoxName as String) as String is override 170 173 return JvmTypeProxy.cobraNameForJvmBoxName(nativeBoxName) 171 174 175 def isRunnableFile( fullExeFileName as String) as bool is override 176 """Test if filename is runnable ( vs a library or something else) """ 177 return fullExeFileName.endsWith('.class') or fullExeFileName.endsWith('.jar') 178 172 179 # Types 173 180 get objectTypeProxy as AbstractTypeProxy is override 174 181 """Type proxy for BE root of Object hierarchy.""" -
Source/BackEndJvm/JavaCompilationMessage.cobra
17 17 var _fileName as String? 18 18 var _lineNum as int? 19 19 var _isError as bool 20 20 var _lpad = -1 21 21 22 cue init(line as String, compiler as Compiler) 22 23 require not .willSkipMessage(line) 23 24 base.init(line) … … 35 36 _message = _cleanUp(line) 36 37 37 38 def append(line as String, compiler as Compiler) 38 line = line.trim 39 #line = line.trim 40 if _lpad == -1 41 lineTrim = line.trimStart 42 _lpad = line.length - lineTrim.length 43 line = line.trim 44 else if line.trim == '^' 45 line = line[_lpad:] 39 46 _message += '\n >: ' + line 40 47 if System.Text.RegularExpressions.Regex.isMatch(line, r'// \d+\s*$') 41 48 lidx = line.lastIndexOf('//') -
Source/BackEndJvm/JavaGenerator.cobra
178 178 def _parseJavaCompilerOutput(output as String) 179 179 jcm as JavaCompilationMessage? = nil 180 180 for line in output.split(c'\n') 181 line = line.trim182 if not line .length, continue181 line0 = line.trim 182 if not line0.length, continue 183 183 if JavaCompilationMessage.willSkipMessage(line) 184 184 if jcm, jcm.append(line, this) 185 185 continue … … 511 511 return .fullName + .javaSuffix 512 512 513 513 get javaQualifier as String 514 ensure result.endsWith('.') 515 # TODO : Fix this with correct Namespace setup for java516 #if .fullName == 'System'517 # return 'java.lang.'514 ensure result.endsWith('.') or result.length == 0 515 # suppress naming of 'global' default namespace 516 if .fullName.toLower == 'global' 517 return '' 518 518 javaName = .fullName.toLower # java idiom is all lowercase for packages 519 519 return javaName + .javaSuffix + '.' 520 520 … … 1914 1914 .writeJavaSetLine(sw) 1915 1915 .writeJavaDef(sw) 1916 1916 1917 1918 1917 class AssertStmt is partial 1919 1918 1920 1919 def writeJavaDef(sw as CurlyWriter) … … 1922 1921 if not .compiler.options.boolValue('include-asserts') 1923 1922 return 1924 1923 sw.write('if (cobra.lang.CobraCore._willCheckAssert') 1925 # TODO - implement cobra assertions - needs cobra assertException + Sourcesite 1926 /# 1924 1927 1925 sw.write(' && !') 1928 1926 _expr.writeJavaDef(sw) 1929 1927 sw.write(')\n') 1930 1928 sw.indent 1931 1929 1932 # TODO later Implement SourceSite and CobraLang AssertException1933 1930 sw.write('throw new cobra.lang.AssertException([.javaSourceSite], ') 1934 1931 _expr.writeJavaBreakdown(sw) 1935 1932 sw.write('[.javaThis], ') … … 1939 1936 sw.write('null') 1940 1937 sw.write(');\n') 1941 1938 sw.dedent 1942 #/1943 1939 1940 /# 1944 1941 # use java asserts initially at least 1945 1942 sw.write(')\n') 1946 1943 sw.indent … … 1962 1959 _info.writeJavaDef(sw) 1963 1960 sw.write(';\n') 1964 1961 sw.dedent 1962 #/ 1965 1963 1966 1967 1964 class BlockStmt is partial 1968 1965 1969 1966 def writeJavaDef(sw as CurlyWriter) … … 2094 2091 2095 2092 2096 2093 class OldForNumericStmt is partial 2094 # We dont support this in Java 2097 2095 2098 def writeJavaDef(sw as CurlyWriter) 2096 def writeJavaDef(sw as CurlyWriter) is override 2097 varName = _var.javaName 2098 sw.write('Error-Old-Numeric-Form-unsupported;\n') 2099 sw.write('// Old Numeric For form is obsolete and not supported - convert cobra code to new form "for [varName] in start : stop : step "\n') 2100 sw.write('// Should become something like "for [varName] in ') 2101 _start.writeJavaDef(sw) 2102 sw.write(':') 2103 _stop.writeJavaDef(sw) 2104 if _step 2105 sw.write(':') 2106 _step.writeJavaDef(sw, false) 2107 sw.write('"\n') 2108 /# 2099 2109 base.writeJavaDef(sw) 2100 2110 varName = _var.javaName 2101 2111 trackLocals = .compiler.willTrackLocals … … 2129 2139 else, sw.write('[varName]--') 2130 2140 sw.write(')') 2131 2141 _block.writeJavaDef(sw) 2142 #/ 2132 2143 2133 2134 2144 class ForNumericStmt is partial 2135 2145 2136 2146 def writeJavaDef(sw as CurlyWriter) … … 2375 2385 sw.write(';\n') 2376 2386 else 2377 2387 sw.write('return;\n') 2388 2389 class TraceStmt 2390 is partial 2378 2391 2392 pass 2379 2393 2394 2395 class TraceLocationStmt 2396 is partial 2397 2398 def writeJavaDef(sw as CurlyWriter) 2399 base.writeJavaDef(sw) 2400 if .includeTraces 2401 sw.write('CobraLangInternal.CobraCore.Tracer.Trace([.javaSourceSite]);\n') 2402 2403 2404 class TraceAllStmt 2405 is partial 2406 2407 def writeJavaDef(sw as CurlyWriter) 2408 base.writeJavaDef(sw) 2409 if .includeTraces 2410 sw.write('CobraLangInternal.CobraCore.Tracer.Trace([.javaSourceSite], "this", [_codePart.javaThis]') 2411 for param in _codePart.params 2412 sw.write(', "[param.name]", [param.javaName]') 2413 for local in _codePart.locals 2414 sw.write(', "[local.name]", [local.javaName]') 2415 sw.write(');\n') 2416 2417 2418 class TraceExprsStmt 2419 is partial 2420 2421 def writeJavaDef(sw as CurlyWriter) 2422 base.writeJavaDef(sw) 2423 if .includeTraces 2424 sw.write('CobraLangInternal.CobraCore.Tracer.Trace([.javaSourceSite]') 2425 sep = ', ' 2426 for expr in _exprs 2427 sw.write('[sep][Utils.javaStringLiteralFor(expr.toCobraSource)][sep]') 2428 expr.writeJavaDef(sw, false) 2429 sw.write(');\n') 2430 2431 2432 class UsingStmt 2433 is partial 2434 2435 def writeJavaDef(sw as CurlyWriter) 2436 base.writeJavaDef(sw) 2437 name = _var.javaName 2438 sw.write('// using - needs work\n') 2439 # should extend this so takes an initialisation block rather than single initExpr 2440 sw.write('try ') 2441 sw.write('[name] = ') 2442 _initExpr.writeJavaDef(sw) 2443 sw.write(';\n') 2444 _block.writeJavaDef(sw) 2445 2446 # by hand ( w/o java7 2447 if false 2448 sw.write('[name] = ') 2449 _initExpr.writeJavaDef(sw) 2450 sw.write(';try\n') 2451 _block.writeJavaDef(sw) 2452 sw.write('finally {\n') 2453 sw.indent 2454 if _var.type.isReference 2455 sw.write('if ([name]!=null) { ((java.lang.AutoCloseable)[name]).close(); [name] = null; }\n') 2456 else 2457 sw.write('((java.lang.AutoCloseable)[name]).close();\n') 2458 sw.dedentAndWrite('}\n') 2459 2460 2461 class WhileStmt 2462 is partial 2463 2464 def writeJavaDef(sw as CurlyWriter) 2465 base.writeJavaDef(sw) 2466 sw.write('while (') 2467 _expr.writeJavaDef(sw, false) 2468 sw.write(')') 2469 _block.writeJavaDef(sw) 2470 2471 2472 class PostWhileStmt 2473 is partial 2474 2475 def writeJavaDef(sw as CurlyWriter) is override 2476 # base.writeSharpDef(sw) - don't generate the other form of while loop 2477 sw.write('do') 2478 _block.writeJavaDef(sw, false) 2479 sw.dedent 2480 sw.write('} while (') 2481 _expr.writeJavaDef(sw, false) 2482 sw.write(');\n') 2483 2484 class YieldStmt 2485 is partial 2486 2487 pass 2488 2489 2490 class YieldBreakStmt 2491 is partial 2492 2493 def writeJavaDef(sw as CurlyWriter) 2494 base.writeJavaDef(sw) 2495 sw.write('yield break;\n') 2496 2497 2498 class YieldReturnStmt 2499 is partial 2500 2501 def writeJavaDef(sw as CurlyWriter) 2502 base.writeJavaDef(sw) 2503 ensurePart = .compiler.curCodeMember.ensurePart 2504 willEnsure = ensurePart and ensurePart.willGenerateCode 2505 if willEnsure 2506 sw.write('_lh_canEnsure = true;\n') 2507 if _expr 2508 backEndResultVarName = .compiler.curCodeMember.backEndResultVarName 2509 if willEnsure and backEndResultVarName.length 2510 # TODO: resolve yield return with ensure 2511 # sw.write('yield return [backEndResultVarName]=') 2512 # so for now: 2513 sw.write('yield return ') 2514 _expr.writeJavaDefInContext(sw) 2515 sw.write(';\n') 2516 else 2517 sw.write('yield return ') 2518 _expr.writeJavaDefInContext(sw) 2519 sw.write(';\n') 2520 else 2521 sw.write('yield return;\n') 2522 2523 2524 2525 2526 2380 2527 ## 2381 2528 ## Expressions 2382 2529 ## … … 2443 2590 sw.write(';\n') 2444 2591 2445 2592 def writeJavaBreakdown(sw as CurlyWriter) 2446 sw.write(r'new object[] { 0')2593 sw.write(r'new Object[] { 0') 2447 2594 .writeJavaBreakdownItems(sw) 2448 2595 sw.write('}, ') 2449 2596 … … 2459 2606 def writeJavaDefForBreakdown(sw as CurlyWriter) 2460 2607 .writeJavaDef(sw) 2461 2608 2462 2609 def _mapJavaTypeToClass(typeName as String, defaultSuffix as String) as String 2610 # support for getClass and primitive mapping 2611 if typeName == 'int', typeName = 'Integer.TYPE' 2612 else if typeName == 'bool', typeName = 'Boolean.TYPE' 2613 else if typeName == 'char', typeName = 'Character.TYPE' 2614 else, typeName = typeName + defaultSuffix 2615 #else if typeName == 'byte', typeName = 'Byte.TYPE' 2616 #else if typeName == 'sbyte', typeName = 'Byte.TYPE' 2617 #else if typeName == 'short', typeName = 'Short.TYPE' 2618 #else if typeName == 'int16', typeName = 'Short.TYPE' 2619 #else if typeName == 'int32', typeName = 'Integer.TYPE' 2620 #else if typeName == 'long', typeName = 'Long.TYPE' 2621 #else if typeName == 'int64', typeName = 'Long.TYPE' 2622 #else if typeName == 'float', typeName = 'Float.TYPE' 2623 #else if typeName == 'float32', typeName = 'Float.TYPE' 2624 #else if typeName == 'double', typeName = 'Double.TYPE' 2625 #else if typeName == 'float64', typeName = 'Double.TYPE' 2626 #else, typeName = typeName + defaultSuffix 2627 return typeName 2628 2463 2629 class NameExpr is partial 2464 2630 2465 2631 get asJava as String … … 2560 2726 2561 2727 def writeJavaDef(sw as CurlyWriter, parens as bool) is override 2562 2728 # recall that this cannot be the right side of "foo.bar" since that is a MemberExpr 2563 javaRef = .javaQualification + .javaName 2564 if _requiresGetClass, javaRef = javaRef + '.getClass()' 2565 #print 'Dbg: IdExpr::', javaRef 2566 sw.write(javaRef) 2567 2729 name = .javaQualification + .javaName 2730 if _requiresGetClass 2731 name = _getClass(name) 2732 #name = _mapJavaTypeToClass(name, '') 2733 sw.write(name) 2734 2568 2735 get javaQualification as String 2569 2736 qual = '' 2570 2737 if .definition inherits IVar … … 2573 2740 else 2574 2741 pn = .definition.parentNameSpace 2575 2742 if pn, qual = pn.javaQualifier 2576 #print 'Dbg: IdExpr.qual::', qual2577 2743 return qual 2578 2744 2579 2745 get javaName as String … … 2591 2757 if not .isTypeReference, return false 2592 2758 superNode = .superNode 2593 2759 if superNode inherits DotExpr, return false 2594 if superNode inherits InheritsExpr, return false2760 #if superNode inherits InheritsExpr, return false 2595 2761 if superNode inherits PostCallExpr 2596 2762 if superNode.expr is this 2597 2763 return false … … 2614 2780 def writeJavaDefForBreakdown(sw as CurlyWriter) is override 2615 2781 name = .javaQualification + .javaName 2616 2782 # _requiresGetClass may return false, but in the java def breakdown, .getClass is always required 2617 if .isTypeReference, name = name + '.getClass()' 2783 if .isTypeReference, name = _getClass(name) 2784 #name = _mapJavaTypeToClass(name, '') 2618 2785 sw.write(name) 2786 2787 def _getClass(name as String) as String 2788 if .javaName.endsWith('.TYPE') # primitive already typed 2789 return name 2790 if not .javaName.startsWithLowerLetter 2791 name = name + '.class' 2792 else 2793 name = _mapJavaTypeToClass(name, '.getClass()') 2794 return name 2795 2619 2796 2620 2621 2797 class IfExpr is partial 2622 2798 2623 2799 def writeJavaDef(sw as CurlyWriter, parens as bool) is override … … 2695 2871 if parens, sw.write(')') 2696 2872 2697 2873 def _lookupReadIndexer as JavaFieldInfo? 2698 nt = JvmNativeType.nativeType(_target.type) 2874 nt = JvmNativeType.nativeType(_target.type.nonNil) 2875 #print 'dbg', _target.type.nonNil, nt 2699 2876 if nt 2700 2877 ntIdxr = nt.indexer 2701 2878 if ntIdxr and ntIdxr.isReadable … … 2731 2908 sw.write('(') 2732 2909 _expr.writeJavaDef(sw) 2733 2910 sw.write(')') 2734 sw.write('== null')2911 sw.write('== null') 2735 2912 if parens, sw.write(')') 2736 2913 2737 2914 def writeJavaBreakdownItems(sw as CurlyWriter) … … 2746 2923 sw.write('(') 2747 2924 _expr.writeJavaDef(sw) 2748 2925 sw.write(')') 2749 sw.write('!= null')2926 sw.write('!= null') 2750 2927 if parens, sw.write(')') 2751 2928 2752 2929 def writeJavaBreakdownItems(sw as CurlyWriter) … … 2799 2976 #sw.write('typeof(') 2800 2977 sw.write('(') 2801 2978 sw.write(javaRef) 2802 sw.write('.getClass ()')2979 sw.write('.getClassX()') 2803 2980 sw.write(')') 2804 else 2981 else if _requiresRawType() 2982 sw.write(javaRef) # might need to map cobratypes like [u]int{8,16,32,64} 2983 else 2984 javaRef = _mapJavaTypeToClass(javaRef, '.class') 2805 2985 sw.write(javaRef) 2806 2986 2807 2987 def _requiresGetClass as bool 2808 2988 return false # may need to extend later 2809 2989 2990 def _requiresRawType as bool 2991 # In Java some places require class refs amd the Type of any primitives being used 2992 superNode = .superNode 2993 if superNode is nil 2994 return false 2995 if superNode inherits BinaryOpExpr 2996 if this is superNode.right 2997 if superNode inherits InheritsExpr 2998 return false 2999 return true 3000 2810 3001 /# def _requiresTypeOf as bool 2811 3002 # Cobra never requires that you wrap a type reference in typeof(Foo). 2812 3003 # C# requires typeof() in a variety of circumstances and won't accept it in a variety of others. … … 2831 3022 def writeJavaDefForBreakdown(sw as CurlyWriter) is override 2832 3023 #requiresTypeOf = _requiresTypeOf # using C# version currently - chop ? 2833 3024 #if not requiresTypeOf, sw.write('typeof(') 2834 .writeJavaDef(sw)3025 #.writeJavaDef(sw) 2835 3026 #if not requiresTypeOf, sw.write(')') 3027 3028 # Handle mapping primitives to their classes 3029 #javaRef = _containedType.javaRef 3030 javaRef = _mapJavaTypeToClass(_containedType.javaRef, '.class') 3031 sw.write(javaRef) 2836 3032 2837 3033 2838 3034 class UnaryOpExpr … … 3314 3510 javaNot = if(_op=='OR', '', '!') 3315 3511 sw.write(', [src], new cobra.lang.CobraDirectString([javaNot]') 3316 3512 _left.writeJavaDefForBreakdown(sw) 3317 sw.write(' ? "(short-circuited)" : cobra.lang.CobraCore. ToTechString(')3513 sw.write(' ? "(short-circuited)" : cobra.lang.CobraCore.toTechString(') 3318 3514 _right.writeJavaDefForBreakdown(sw) 3319 3515 sw.write('))') 3320 3516 … … 3610 3806 sep = ', ' 3611 3807 sw.write(')') 3612 3808 return 3809 aliasedName = _dotRightExpr.definition.aliasedMethodBacking 3613 3810 # handle static typing 3614 3811 # don't write 'this' for shared members 3615 3812 writeThis = true … … 3626 3823 _left.writeJavaDef(sw, not _left inherits DotExpr) 3627 3824 sw.write('.') 3628 3825 #print 'Dbg: dotExpr::', _left.toCobraSource, _right.toCobraSource 3629 _right.writeJavaDef(sw, false) 3826 if aliasedName 3827 sw.write(aliasedName+'()') # FTM assume no args 3828 else 3829 _right.writeJavaDef(sw, false) 3630 3830 if didSetInInitCall 3631 3831 Stmt.inInitCall = false 3632 3832 … … 3638 3838 is partial 3639 3839 3640 3840 def _writeJavaDef(sw as CurlyWriter) is override 3841 #_left.writeJavaDef(sw) 3842 #sw.write(' instanceof ') 3843 #_right.writeJavaDef(sw, false) 3844 3845 # Compiler generates error with instanceof for non intersecting instance and Type so 3846 # instead use runtime instance lookup 3847 # instead of 'e instanceof T' becomes 'T.class.isInstance(e)' 3848 _right.writeJavaDef(sw, false) 3849 #sw.write('.class.isInstance(') 3850 sw.write('.isInstance(') 3641 3851 _left.writeJavaDef(sw) 3642 sw.write(' instanceof ') 3643 _right.writeJavaDef(sw, false) 3852 sw.write(' )') 3644 3853 3645 3854 3646 3855 class ToExpr is partial -
Source/TestifyRunner.cobra
254 254 options['debugging-tips'] = false 255 255 options['embed-run-time'] = false 256 256 options['verbosity'] = 2 257 # trace options 257 options['back-end'] = .options['back-end'] 258 #trace options 258 259 return options to ! 259 260 260 261 def testifyFinish(message as String) … … 385 386 386 387 _statusWriter.writeLine('([_statusCount]) [baseName]') 387 388 _statusCount += 1 389 388 390 assert File.exists(baseName) 389 390 391 source = File.readAllText(baseName) 391 392 392 393 print … … 470 471 continue 471 472 472 473 if firstLineInsensitive.startsWith('#.require.') 473 rtPlatform = CobraCore.runtimePlatform474 rtPlatform = options['back-end'] # wrongly wuz CobraCore.runtimePlatform 474 475 what = firstLineInsensitive[10:] 475 476 branch what 476 477 on 'mono' … … 738 739 return 1 739 740 740 741 def _testifyRun(c as Compiler) as int 741 if not c.fullExeFileName.endsWith('.exe') 742 if not c.backEnd.isRunnableFile(c.fullExeFileName) 743 # below assumes created file placed in cwd 742 744 if File.exists(c.fullExeFileName) 743 745 print 'Produced file "[c.fullExeFileName]" as expected.' 744 746 return 1 … … 748 750 return 0 749 751 else 750 752 print 'Run:' 751 if .verbosity >= 1 752 print 'c.fullExeFileName = "[c.fullExeFileName]"' 753 if .verbosity >= 1, print 'c.fullExeFileName = "[c.fullExeFileName]"' 753 754 p = c.runProcess 754 if .verbosity >= 2 755 print '[p.startInfo.fileName] [p.startInfo.arguments]' 755 if .verbosity >= 2, print '[p.startInfo.fileName] [p.startInfo.arguments]' 756 756 output = CobraCore.runAndCaptureAllOutput(p).trim 757 757 758 758 print 'Output:' -
Tests/100-basics/034j-set-property.cobra
1 # 1 #.require. jvm 2 2 namespace Test 3 3 class Test 4 4 def main is shared -
Tests/100-basics/052-float.cobra
1 # 1 #.require. clr 2 2 # This is clr specific re inheritance of literals and floats 3 3 namespace Test 4 4 -
Tests/100-basics/110j-while.cobra
1 #.require. jvm 2 @platform jvm 3 namespace Test 4 5 class Test 6 7 def main 8 9 # Note: You wouldn't actually use while loops for counting, 10 # but counting makes a good basic test. 11 12 i as int = 0 13 while i < 100 14 i += 1 15 assert i == 100 16 17 i = 0 18 while i > 0 19 i = -1 20 assert i == 0 21 22 i = 0 23 post while i > 0 24 i = -1 25 assert i == -1 26 27 i = 100 28 while i 29 i -= 1 30 assert i == 0 31 32 # 2006-12-16: there was a bug where post while generates both a while loop and a do-while loop 33 count = 0 34 i = 10 35 post while i > 0 36 i -= 1 37 count += 1 38 assert count == 10 39 40 random = Random() 41 a = 1 42 while a <= 3 43 post while .check(a, b) # using local var `b` which is first assigned below 44 b = random.nextInt(3) + 1 45 a += 1 46 47 def check(a as int, b as int) as bool 48 assert b <> 0 # verifies that the while condition is not checked immediately 49 return a <> b -
Tests/100-basics/030-hello-world.cobra
1 # 1 #.require. clr 2 2 namespace Test 3 3 class Test 4 4 def main -
Tests/100-basics/080-inherits.cobra
1 #.require. clr 1 2 namespace Test 2 3 3 4 class Test -
Tests/100-basics/030j-hello-world1.cobra
1 # 1 #.require. jvm 2 2 namespace Test 3 3 class Test 4 4 def main is shared -
Tests/100-basics/032-get-property-static.cobra
1 # 1 #.require. clr 2 2 namespace Test 3 3 class Test 4 4 def main -
Tests/100-basics/042-int.cobra
44 44 assert 2*3 + 4*5 == 26 45 45 assert (2*3 + 4*5) == 26 46 46 47 # minValue and maxValue48 x = 2_147_483_64749 x = -2_147_483_647 # to-do: should end in 850 assert int.minValue <= -2_147_483_647 # to-do: should end in 851 assert int.maxValue >= 2_147_483_647 -
Tests/100-basics/080j-inherits.cobra
1 #.require. jvm 2 namespace Test 3 4 class Test 5 6 def main 7 is shared 8 9 # string lits make for good tests 10 assert 'aoeu' inherits String # .warning. always 11 # Another Mono bug. New 1.2.6 (or maybe 1.2.5): https://bugzilla.novell.com/show_bug.cgi?id=350977 12 assert 'aeou' inherits Object # .warning. always 13 assert not ('aoeu' inherits Void) # .warning. never 14 assert not ('aoeu' inherits Integer) # .warning. never 15 16 # primitives 17 assert 5 inherits int # .warning. always 18 assert 5 inherits Object # .warning. always 19 assert not (5 inherits String) # .warning. never 20 assert 5 inherits Integer # .warning. always 21 22 assert true inherits bool # .warning. always 23 assert true inherits Object # .warning. always 24 assert not (true inherits String) # .warning. never 25 assert true inherits Boolean # .warning. never 26 27 # try a method 28 assert System.getenv('PATH') inherits Object # .warning. can just check for not nil 29 assert System.getenv('PATH') inherits String # .warning. can just check for not nil 30 assert not (System.getenv('PATH') inherits Thread) # .warning. never 31 -
Tests/100-basics/130-for-enumerable.cobra
1 1 namespace Test 2 2 3 3 class Test 4 shared 5 var fakeCommandLineArgs as List<of String> = ['130-for-enumerable' ] 4 6 5 7 def main 6 8 is shared 7 9 8 10 count as int = 0 9 11 10 for arg as String in Environment.getCommandLineArgs12 for arg as String in .fakeCommandLineArgs 11 13 # Console.WriteLine(arg) 12 14 count += 1 13 15 14 16 assert count>0 15 17 16 for arg in Environment.getCommandLineArgs18 for arg in .fakeCommandLineArgs 17 19 count += 1 18 20 19 21 CobraCore.noOp(arg) … … 22 24 def more 23 25 s = 'aoeu' 24 26 # reuse a local 25 for s in Environment.getCommandLineArgs27 for s in .fakeCommandLineArgs 26 28 assert s # .warning. always 27 29 28 30 .foo('aoeu') … … 31 33 def foo(s as String) 32 34 assert s == 'aoeu' 33 35 # reuse an arg: 34 for s in Environment.getCommandLineArgs36 for s in .fakeCommandLineArgs 35 37 assert s # .warning. always 36 38 37 39 var _b as String = 'aoeu' … … 39 41 def bar 40 42 assert _b == 'aoeu' 41 43 # reuse a class var: 42 for _b in Environment.getCommandLineArgs44 for _b in .fakeCommandLineArgs 43 45 assert _b # .warning. always -
Tests/100-basics/042-int-minValue.cobra
1 #.require. clr 2 @platform clr 3 namespace Test 4 5 class Test 6 7 def main 8 is shared 9 10 # minValue and maxValue 11 x = 2_147_483_647 12 x = -2_147_483_647 # to-do: should end in 8 13 assert int.minValue <= -2_147_483_647 # to-do: should end in 8 14 assert int.maxValue >= 2_147_483_647 -
Tests/100-basics/033j-get-property-instance.cobra
1 # 1 #.require. jvm 2 2 namespace Test 3 3 class Test 4 4 def main -
Tests/100-basics/052j-float.cobra
1 # 1 #.require. jvm 2 2 namespace Test 3 3 4 4 class Test … … 18 18 ff = Float(1.0f) 19 19 assert ff inherits Float # .warning. is always 20 20 ii = Integer(1) 21 #assert not (ii inherits Float) # . warning. is never21 #assert not (ii inherits Float) # . warning. is never 22 22 # above also throws compiler error 23 23 o as Object = ii 24 24 assert not (o inherits Float) -
Tests/100-basics/030j-hello-world.cobra
1 # 1 #.require. jvm 2 2 namespace Test 3 3 class Test 4 4 def main is shared -
Tests/100-basics/110-while.cobra
1 #.require. clr 2 @platform clr 1 3 namespace Test 2 4 3 5 class Test -
Tests/100-basics/065-indexing.cobra
1 #.require. clr 1 2 namespace Test 2 3 3 4 class Test -
Tests/100-basics/034-set-property.cobra
1 # 1 #.require. clr 2 2 namespace Test 3 3 class Test 4 4 def main -
Tests/100-basics/120-for-numeric.cobra
1 #.require. clr 2 @platform clr 1 3 # numeric for loops follow the half-open interval 0 .. N-1 which lines up with the zero indexing used in .NET for arrays, lists and strings. 2 4 # see also Dijkstra's comments at http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF 3 5 namespace Test -
Tests/100-basics/065j-indexing.cobra
1 #.require. jvm 2 namespace Test 3 4 class Test 5 6 def main 7 is shared 8 9 assert CobraCore.commandLineArgs[0].length 10 assert CobraCore.commandLineArgs[0]<>'roembrjkxte,.nune,.ntokmbk' 11 s as String = CobraCore.commandLineArgs[0] 12 t as String = CobraCore.commandLineArgs[0] 13 s = t 14 assert s==t 15 assert CobraCore.commandLineArgs.get(0) == s -
Tests/100-basics/122-for-numeric.cobra
55 55 count = 0 56 56 for x in 1 : 10 57 57 r = x 58 continue58 if x, continue # need conditional, some platforms err on dead code 59 59 count += 1 60 60 assert r == 9 61 61 assert count == 0