Ticket #275: java-jvm-2.patch
File java-jvm-2.patch, 141.1 KB (added by hopscc, 13 years ago) |
---|
-
Source/TypeProxies.cobra
167 167 return _actualType to ! 168 168 169 169 def _recommendBuiltInType 170 if _actualType.parentNameSpace and _actualType.parentNameSpace.fullName == 'System' 171 n = nil to String? 172 branch _actualType.name 173 on 'Boolean', n = 'bool' 174 on 'SByte', n = 'int8' 175 on 'Byte', n = 'uint8' 176 on 'Int16', n = 'int16' 177 on 'UInt16', n = 'uint16' 178 on 'Int32', n = 'int32' 179 on 'UInt32', n = 'uint32' 180 on 'Int64', n = 'int64' 181 on 'UInt64', n = 'uint64' 182 on 'Char', n = 'char' 183 on 'Single', n = 'float32' 184 on 'Double', n = 'float' 185 on 'Decimal', n = 'decimal' 186 if n, .compiler.warning(this, 'Use the builtin type "[n]" instead of the struct "[_actualType.name]".') 187 170 n = .compiler.backEnd.getRecommendedBuiltInType(_actualType.parentNameSpace, _actualType.name) 171 if n, .compiler.warning(this, 'Use the builtin type "[n]" instead of the struct "[_actualType.name]".') 172 188 173 def equals(other as Object?) as bool is override 189 174 if other is nil 190 175 return false -
Source/BackEndObjC/ObjcBackEnd.cobra
6 6 base.init(compiler) 7 7 _name = 'objc' 8 8 _rtlName = 'Cobra.Lang.dll' 9 _rtlSrcFile = 'native.objc' # backEnd source file containing native code support for Cobra.Lang 10 9 11 _tagToTypeName = { # TODO 10 12 'Object': '', 11 13 'Type' : '', … … 15 17 phases.add(GenerateObjcCodePhase(.compiler)) 16 18 phases.add(CompileObjcCodePhase(.compiler)) 17 19 20 def getRecommendedBuiltInType(parentNameSpace as NameSpace?, name as String) as String? is override 21 n = nil to String? 22 if parentNameSpace and parentNameSpace.fullName == '???' 23 branch name 24 on '???', n = 'bool' 25 on '?? SByte', n = 'int8' 26 on '?? Byte', n = 'uint8' 27 on '?? Int16', n = 'int16' 28 on '?? UInt16', n = 'uint16' 29 on '?? Int32', n = 'int32' 30 on '?? UInt32', n = 'uint32' 31 on '?? Int64', n = 'int64' 32 on '?? UInt64', n = 'uint64' 33 on '?? Char', n = 'char' 34 on '?? Single', n = 'float32' 35 on '?? Double', n = 'float' 36 on '?? Decimal', n = 'decimal' 37 return n 38 18 39 def computeOutName as String is override 19 40 return .compiler.computeOutNameObjc 20 41 … … 86 107 assert false, 'ObjcBackEnd ObjcNativeType and objcTypeByName NYI' 87 108 return ClrNativeType(.compiler.clrTypeByName(qualifiedName)) 88 109 89 def addArrayInterfaces( interfaces as List<of ITypeProxy>)is override90 assert false, 'ObjcBackEnd addArrayInterfaces NYI'110 def prepSystemObjectClass(box as Box) is override 111 pass #box.prepSystemObjectClassObjc 91 112 92 113 def scanGenericArgs(box as Box) is override 114 pass # box.scanGenericArgsObjc 93 115 116 def scanNativeType(box as Box) is override 117 pass # box.scanNativeTypeObjc 118 119 def scanNativeType(edcl as EnumDecl) is override 120 pass # edcl.scanNativeTypeObjc 121 122 def setUnderlyingType(edcl as EnumDecl) is override 123 pass # edecl.setUnderlyingTypeObjc 124 125 # implement these if need override 126 #def determineExtnNativeType(extn as Extension, nativeType as NativeType) as NativeType 127 # return extn.objcExtnNativeType(nativeType) 128 129 #def handleNameSpaceNameCollision(ns as NameSpace, token as IToken, name as String) as NameSpace is override 130 131 94 132 class GenerateObjcCodePhase inherits Phase 95 133 96 134 cue init(c as Compiler) -
Source/Snapshot/Cobra.Lang/CobraCore.cobra
385 385 require false 386 386 pass 387 387 388 get runtimePlatform as String 389 return 'clr' 390 #return 'jvm' 391 # return 'objc' 392 388 393 var _isRunningOnMono as bool? 389 394 390 395 get isRunningOnMono as bool -
Source/Snapshot/Cobra.Lang/Tracer.cobra
13 13 var _isActive = true 14 14 var _willAutoFlush = true 15 15 var _dest as TextWriter 16 var _separator = '; 16 var _separator = ';\n -:' 17 17 var _prefix = ' trace: ' 18 18 var _willOutputDirectoryNames = false 19 19 -
Source/Compiler.cobra
64 64 base.init 65 65 _name = '' 66 66 _rtlName = 'rtl' 67 _rtlSrcFile = 'rtlSrc.ext' 67 68 __compiler = compiler 68 69 69 70 get name from var as String 70 71 71 72 get cobraRuntimeLibFile from _rtlName as String 73 """Name of the Cobra RunTime Library file for this backend.""" 72 74 75 get rtlSrcFile from _rtlSrcFile as String 76 """Name of the backEnd source file containing any native code support for Cobra.Lang.""" 77 73 78 get compiler from __compiler as Compiler 74 79 75 80 get tagToTypeName from var … … 88 93 rearrangements if necessary) for this given backend. 89 94 """ 90 95 96 def getRecommendedBuiltInType(parentNameSpace as NameSpace?, name as String) as String? is abstract 97 """ 98 If parentNameSpace is the main system namespace and name is a backEnd builtin type 99 return the Cobra equivalent language type name (or nil). 100 """ 101 91 102 def computeOutName as String is abstract 92 103 """ 93 Return binaryoutput name for compilation of files for this backend.104 Return the binary file output name for compilation of files for this backend. 94 105 """ 95 106 96 107 def genNativeModule(filename as String, verbosity as int) as Module? is abstract 97 108 """ 98 Check if a filename is a Native module and if so return the Native module type for it109 Check if a filename is a Native module and if so generate and return the Native module type for it 99 110 otherwise return nil. 100 111 """ 101 112 … … 117 128 118 129 def loadLibReference(reference as String) as bool is abstract 119 130 """ 120 Load the given lib reference file using the current backend paradigms.131 Load the given library reference file using the current backend paradigms. 121 132 Return true if reference found and loaded correctly, false otherwise 122 133 """ 123 134 124 135 def readSystemTypes is abstract 125 136 """ Read and Load System Types for backend for Compiler to make available""" 126 127 137 128 138 def fixNilableMemberSigs is abstract 129 139 """ … … 167 177 otherwise the qualified names are expected to conform to the platform back end naming. 168 178 """ 169 179 170 def addArrayInterfaces( interfaces as List<of ITypeProxy>) is abstract 171 """Add any additional interfaces the backends support that an ArrayType may need to have.""" 172 180 def prepSystemObjectClass(box as Box) is abstract 181 """Setup additional or convenience members on the System Object class. """ 182 183 def scanGenericArgs(box as Box) is abstract 184 """Scan a loaded Dll (generic) type and translate from native any generic Args.""" 185 186 def scanNativeType(box as Box) is abstract 187 """Scan a loaded Dll type and convert its native Type info to Cobras form """ 188 189 def scanNativeType(edcl as EnumDecl) is abstract 190 """Scan a loaded Dll Enum type and convert its native info to Cobras form """ 191 192 def setUnderlyingType(edcl as EnumDecl) is abstract 193 """Set underlying Storage Type of the value of an Enum.""" 194 195 def determineExtnNativeType(extn as Extension, nativeType as NativeType) as NativeType 196 """ 197 The real extended type is the type of the first argument of any method. 198 Find and make that type from the param list. 199 """ 200 throw Exception('Need implementation of determineExtnNativeType for backend to determine type for an extension') 201 202 def handleNameSpaceNameCollision(ns as NameSpace, token as IToken, name as String) as NameSpace 203 """ 204 What to do if a namespace name collides with an existing symbol. 205 Some backends disallow this situation so its an error. 206 Others keep namespace and symbol tables separate so its perfectly 207 allowable. 208 """ 209 throw Exception('In [ns.name] there is a already non-namespace declaration named "[name]".') 173 210 174 211 class BasicBackEnd inherits BackEnd 175 212 """ Stub BackEnd for tests. """ … … 178 215 base.init(compiler) 179 216 _name = 'c#-clr(basic)' 180 217 _rtlName = 'cobraRTL.libext' 218 _rtlSrcFile = 'cobraRTL.ext' 181 219 182 220 _tagToTypeName = { 183 221 'Object': 'System.Object', … … 187 225 def makePhases(phases as IList<of Phase>) is override 188 226 pass 189 227 228 def getRecommendedBuiltInType(parentNameSpace as NameSpace?, name as String) as String? is override 229 return nil 230 190 231 def computeOutName as String is override 191 232 return 'BasicOut' 192 233 … … 223 264 def cobraNameForNativeBoxName(name as String) as String is override 224 265 return name + '_BBE' 225 266 267 def prepSystemObjectClass(box as Box) is override 268 pass 269 270 def scanGenericArgs(box as Box) is override 271 pass 272 273 def scanNativeType(box as Box) is override 274 pass 275 276 def scanNativeType(edcl as EnumDecl) is override 277 pass 278 279 def setUnderlyingType(edcl as EnumDecl) is override 280 pass 281 226 282 # Types 227 283 get objectTypeProxy as AbstractTypeProxy is override 228 284 return ClrTypeProxy(Object) # for testing … … 239 295 def nativeTypeByName(qualifiedName as String) as NativeType is override 240 296 return ClrNativeType(System.Object) #TODO: fix this to something non BE specific Tmp 241 297 242 def addArrayInterfaces( interfaces as List<of ITypeProxy>) is override243 pass244 245 298 class Compiler implements ITypeProvider, IWarningRecorder, IErrorRecorder, ICompilerForNodes is partial 246 299 """ 247 300 General notes: … … 284 337 285 338 286 339 # caches 287 #var _clrPrimitiveToITypeCache as IDictionary<of System.Type, IType>? 288 var _primitiveToITypeCache as IDictionary<of dynamic, IType>? 340 var _primitiveToITypeCache as IDictionary<of dynamic, IType>? # Key is backend type for a Type ( e.g System.Type) 289 341 290 342 cue init 291 343 .init(0, nil) … … 347 399 _primitiveToITypeCache = value 348 400 349 401 get globalNS from var 402 """ 403 Holds all topLevel decls including refs to Namespaces used and referenced. 404 """ 350 405 351 406 pro mainMethodTypeName from var as String = '' 352 407 … … 846 901 return _nilableDynamicType to ! 847 902 # -- end of ITypeProvider 848 903 849 /#850 overrides replacing above for mixin of BasicTypeProvider851 class Compiler ... includes BasicTypeProvider852 853 var _nilableDynamicType as NilableType?854 855 get numberType as AbstractNumberType is override856 if _numberType is nil857 branch .options['number'] to String858 on 'decimal', _numberType = .decimalType859 on 'float', _numberType = .floatType860 on 'float32', _numberType = .floatType(32)861 on 'float64', _numberType = .floatType(64)862 else, throw FallThroughException(.options['number'])863 return _numberType to !864 904 865 905 866 def nilableType(type as IType) as NilableType is override867 if type inherits NilableType, return type868 if _nilableTypes is nil869 _nilableTypes = Dictionary<of INode, NilableType>()870 if _nilableTypes.containsKey(type)871 return _nilableTypes[type]872 else873 _nilableTypes[type] = nt = NilableType(type)874 nt.bindInh875 if not .isBindingInh, nt.bindInt876 return nt877 878 def defaultType as IType is override879 return .nilableDynamicType880 881 def nilableDynamicType as NilableType882 if _nilableDynamicType is nil883 _nilableDynamicType = .nilableType(.dynamicType)884 return _nilableDynamicType to !885 #/886 887 888 906 get typeType as IType 889 #return _libraryType('System.Type')890 #return _libraryType(.backEnd.tagToTypeName['Type'])891 907 return .libraryType('Type') 892 908 893 909 ## More type stuff … … 1338 1354 ns as IContainer = _globalNS 1339 1355 thing as IContainer? = nil 1340 1356 for name in names 1341 #print (thing ? ns)1342 1357 possible = (thing ? ns).declForName(name) 1358 if not possible 1359 print thing ? ns 1343 1360 assert possible, name 1344 1361 if possible inherits IContainer 1345 1362 thing = possible -
Source/Boxes.cobra
56 56 ensure .needScanNativeType 57 57 _nativeType = t 58 58 _needScanNativeType = true 59 _callNativeScanMethod('ScanGenericArgs')60 61 def _callNativeScanMethod(tag as String)62 """63 Call a backend scan method for native type scan operation desired and backend in use.64 """65 # This is icky - method to call needs to be set directly via backend somehow rather than this check and call code66 # TODO: change to use strategy object set when init backend.67 59 assert .compiler 68 assert tag in ['ScanNativeType', 'ScanGenericArgs', 'prepSysObjClass'] # turn these into an Enum 69 backEnd = .compiler.backEnd 70 branch backEnd.name 71 on 'c#-clr' 72 branch tag 73 on 'ScanNativeType', _scanNativeTypeClr 74 on 'ScanGenericArgs', _scanGenericArgsClr 75 on 'prepSysObjClass', _prepSystemObjectClassClr 76 77 on 'java-jvm' 78 branch tag 79 on 'ScanNativeType', _scanNativeTypeJvm 80 on 'ScanGenericArgs', _scanGenericArgsJvm 81 on 'prepSysObjClass', _prepSystemObjectClassJvm 82 on 'objc' 83 print 'objc back end need method for [tag]' 84 assert false, 'Missing backEnd infrastructure for [backEnd.getType.name]' 85 #branch on tag 86 # on 'ScanNativeType', _scanObjcNativeType 87 # on 'ScanGenericArgs', _scanObjcGenericArgs 88 # on 'prepSysObjClass', _prepSystemObjectClassObjc 89 else 90 throw FallThroughException('No nativeScanMethod code for backend [backEnd.name] [backEnd.getType.name]') 60 .compiler.backEnd.scanGenericArgs(this) # Convert any Generic args fm backend form to Cobra data structures 91 61 92 93 62 def addMinFields 94 63 base.addMinFields 95 64 .addField('didBindInh', .didBindInh) … … 650 619 ## Binding 651 620 def _scanNativeType 652 621 #print '_scanNativeType ', .name 653 _callNativeScanMethod('ScanNativeType') 622 assert .compiler 623 .compiler.backEnd.scanNativeType(this) # Convert library (native) info to Cobra data structures 654 624 655 625 def _stackPush 656 626 base._stackPush … … 730 700 # Therefore, everthing below has already happened for a constructed box's generic def. 731 701 base._bindInt 732 702 if .isSystemObjectClass 733 _callNativeScanMethod('prepSysObjClass') 703 assert .compiler 704 .compiler.backEnd.prepSystemObjectClass(this) # add any improvements to root Object 734 705 errorCount = .compiler.errors.count 735 706 if _needScanNativeType, _scanNativeType 736 707 if _baseClass … … 1104 1075 newDecls.add(nd) 1105 1076 for decl in _declsInOrder 1106 1077 if decl inherits BoxMember 1078 #if not decl.didBindInt # hops: fix for crash with generics and java before changeset 2576 1079 # print 'dbg: ', decl.name 1080 # decl.bindInt 1107 1081 nd = decl.constructedFor(this, gpToType) 1108 1082 assert nd <> decl 1109 1083 newDecls.add(nd) … … 1886 1860 base.init(TokenFix.empty, TokenFix.empty, backend.cobraNameForNativeBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), nil) 1887 1861 _initNativeType(nativeType) 1888 1862 # the real extended type is not this type, but the type of the first argument of any method 1889 branch backend.name 1890 on 'c#-clr', nativeType = .clrExtnNativeType(nativeType) # ScanClrType 1891 on 'java-jvm', nativeType = .jvmExtnNativeType(nativeType) # ScanJvmType 1892 on 'objc' 1893 print 'objc back end need method objcExtnNativeType' 1894 assert false, 'Missing backEnd infrastructure for [backend.getType.name]' 1895 else 1896 throw FallThroughException('No extnNativeType code for backend [backend.name] [backend.getType.name]') 1897 #nativeType = backEnd.determineExtnNativeType(nativeType) 1863 nativeType = backend.determineExtnNativeType(this, nativeType) 1898 1864 _extendedBoxProxy = backend.nativeTypeProxy(nativeType) 1899 1865 (.compiler.curModule to AssemblyModule).addMustBindInh(this) 1900 1866 -
Source/Cobra.Lang/Java/CobraCore.java
17 17 public static Boolean _willCheckAssert = true; 18 18 public static Boolean _willCheckNil = true; 19 19 20 //public static String getRuntimePlatform() { return "jvm"; } // prop 21 public static final String runtimePlatform = "jvm"; 22 20 23 public static int noOp(/* allowNull */ Object... args) { 21 24 /* """ 22 25 No operation. Primarily used in Cobra's own test suite to consume a local variable to avoid undesired warnings. -
Source/Cobra.Lang/Java/CobraLang.jar.sig
1 # PkgSig file for jarfile 'C:\home\hops\src\cobra\wkspace\Source\Cobra.Lang\java\CobraLang.jar'2 # jarfile: C:\home\hops\src\cobra\wkspace\Source\Cobra.Lang\java\CobraLang.jar3 4 cobra.lang.CobraCore5 class # JavaType6 cobra.lang # package7 CobraCore # name8 java.lang.Object # superclass9 - # no Interfaces10 public # modifiers11 var _willCheckInvariant12 static public # modifiers13 java.lang.Boolean # Type14 var _willCheckRequire15 static public # modifiers16 java.lang.Boolean # Type17 var _willCheckEnsure18 static public # modifiers19 java.lang.Boolean # Type20 var _willCheckAssert21 static public # modifiers22 java.lang.Boolean # Type23 var _willCheckNil24 static public # modifiers25 java.lang.Boolean # Type26 ctor cobra.lang.CobraCore27 - # no Parameters28 method noOp[V]29 static public # modifiers30 int # returnType31 [Ljava.lang.Object; # Parameters32 - # no Exceptions33 method runAllTests34 static public # modifiers35 void # returnType36 - # no Parameters37 - # no Exceptions38 method printDebuggingTips39 static public # modifiers40 void # returnType41 - # no Parameters42 - # no Exceptions43 44 cobra.lang.CobraImp45 class # JavaType46 cobra.lang # package47 CobraImp # name48 java.lang.Object # superclass49 - # no Interfaces50 public # modifiers51 var _printStringMaker52 static public # modifiers53 cobra.lang.CobraImp$SimpleStringMaker # Type54 ctor cobra.lang.CobraImp55 - # no Parameters56 method printLine57 static public # modifiers58 void # returnType59 - # no Parameters60 - # no Exceptions61 method printLine62 static public # modifiers63 void # returnType64 java.lang.String # Parameters65 - # no Exceptions66 method printStop67 static public # modifiers68 void # returnType69 - # no Parameters70 - # no Exceptions71 method printStop72 static public # modifiers73 void # returnType74 java.lang.String # Parameters75 - # no Exceptions76 method makeString77 static public # modifiers78 java.lang.String # returnType79 java.lang.String # Parameters80 - # no Exceptions81 method makeString82 static public # modifiers83 java.lang.String # returnType84 [Ljava.lang.String; # Parameters85 - # no Exceptions86 87 cobra.lang.CobraImp$SimpleStringMaker88 class # JavaType89 cobra.lang # package90 CobraImp$SimpleStringMaker # name91 java.lang.Object # superclass92 - # no Interfaces93 static public # modifiers94 ctor cobra.lang.CobraImp$SimpleStringMaker95 - # no Parameters96 method makeString97 public # modifiers98 java.lang.String # returnType99 [Ljava.lang.String; # Parameters100 - # no Exceptions101 method makeString102 public # modifiers103 java.lang.String # returnType104 java.lang.String # Parameters105 - # no Exceptions106 method makeString107 public # modifiers108 java.lang.String # returnType109 int # Parameters110 - # no Exceptions111 method makeString[V]112 public # modifiers113 java.lang.String # returnType114 [Ljava.lang.Object; # Parameters115 - # no Exceptions -
Source/Cobra.Lang/Java/PkgSig.java
15 15 * 16 16 * 17 17 * TODO 18 * add cmdline flag generating pkgSig file w/o redirection: 18 * add cmdline flag generating pkgSig file w/o redirection: 19 19 * java -cp . PkgSig -cobra <pkgname> 20 20 * Cleanup and javadoc this file. 21 21 * Put a PkgSig version and timestamp in the pkgSigFile … … 331 331 public static void usage() { 332 332 System.out.println("Unknown usage"); 333 333 System.out.printf("usage: pkgSig [-p] <pkgName>\n"); 334 System.out.printf("usage: pkgSig -j <jarfile>\n "); 335 System.out.printf(" Display class signatures for a package or contents of a jarfile.\n\n "); 334 System.out.printf("usage: pkgSig -j <jarfile>\n"); 335 System.out.printf("usage: pkgSig -jrt\n "); 336 System.out.printf(" Display class signatures for a package or contents of a jarfile.\n\n"); 336 337 System.out.printf("A class signature is the class name, its superclass and signatures for fields and methods of the class.\n"); 337 338 System.out.printf("Packages are searched for in files and jars in classpath.\n"); 338 339 System.out.printf("Jarfiles are specified as relative or absolute pathnames. Relative pathname Jarfiles not found are searched for in the classpath\n"); 340 System.out.printf("The -jrt invocation displays class Signatures for the java runtime jarfile(s)\n"); 339 341 System.out.printf("Output format is suitable for parsing and use by the cobra java backend (cross) compiler.\n"); 340 342 System.exit(2); 341 343 } … … 369 371 return jarFile; 370 372 } 371 373 374 public static void sigForJarFile(String fileName, Set<String> suppressFilter) throws ClassNotFoundException 375 { 376 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 377 assert loader != null; 378 File jarFile = PkgSig.lookForJarFile(fileName, loader); 379 if ( !jarFile.exists()) { 380 System.out.printf("File '%s' does not exist.\n", jarFile.getAbsolutePath()); 381 System.exit(1); 382 } 383 384 //System.out.printf( "DBG: jarfile=%s\n", jarFile.getAbsolutePath()); 385 Set<Class> clsSet = new java.util.concurrent.ConcurrentSkipListSet<Class>(new PkgSig.ClassComparator()); 386 387 System.out.printf("# PkgSig file for jarfile '%s'\n", jarFile.getAbsolutePath()); 388 processJarFile(jarFile.getAbsolutePath(), loader, null, suppressFilter, clsSet); 389 390 for ( Class cls : clsSet) { 391 new ClassSig(cls).emit(); 392 } 393 } 372 394 373 395 public static void main( String[] args) throws Exception { 374 396 if (args.length ==0 ) 375 397 usage(); 376 398 377 if (args.length == 1 ) { // default -p pkgname [...] 378 if ( args[0].startsWith("-")) usage(); 379 399 if (args.length == 1 && !args[0].startsWith("-") ) { // default -p pkgname [...] 380 400 String pkg = args[0]; 381 401 Set<Class> clsSet = PkgSig.findClassesForPkg(pkg); 382 402 if (clsSet.size() == 0 ) … … 386 406 } 387 407 388 408 for ( Class cls : clsSet) { 389 //Class cls = (Class)o;390 //System.out.println(cls.getName());391 409 ClassSig classSig = new ClassSig(cls); 392 410 classSig.emit(); 393 411 } … … 396 414 String pkg = args[1]; 397 415 Set<Class> clsSet = PkgSig.findClassesForPkg(pkg); 398 416 for ( Class cls : clsSet) { 399 //ClassSig classSig = new ClassSig(cls);400 //classSig.emit();401 417 new ClassSig(cls).emit(); 402 418 } 403 419 } 404 420 else if (args[0].equals("-j")) { 405 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 406 assert loader != null; 407 String fileName = args[1]; 408 File jarFile = PkgSig.lookForJarFile(fileName, loader); 409 if ( !jarFile.exists()) { 410 System.out.printf("File '%s' does not exist.\n", jarFile.getAbsolutePath()); 411 System.exit(1); 412 } 421 PkgSig.sigForJarFile(args[1], null); 422 } 423 else if (args[0].equals("-jrt")) { // java runtime 424 Set<String> suppressFilter = new HashSet<String>(); 413 425 414 //System.out.printf( "DBG: jarfile=%s\n", jarFile.getAbsolutePath());415 Set<Class> clsSet = new java.util.concurrent.ConcurrentSkipListSet<Class>(new PkgSig.ClassComparator());416 Set<String> suppressFilter = new HashSet<String>();417 426 // Theres upwards of 8000 classes in rt.jar most of which we dont care about 418 427 // suppress internal implementation classes which shouldnt be using anyway 419 428 suppressFilter.add("com.sun"); 420 429 suppressFilter.add("com.sunw"); 421 430 suppressFilter.add("sun"); 422 431 suppressFilter.add("sunw"); 432 423 433 // suppress some biggies we 'probably' wont ever use - may want to revisit these 424 suppressFilter.add("org.omg"); 425 suppressFilter.add("javax.swing.plaf"); 434 suppressFilter.add("org.omg"); // Corba Sh*t - cos *everybody* needs this in the base RTL 435 suppressFilter.add("javax.swing.plaf"); // swing platform GUI implementations - ditto 426 436 suppressFilter.add("javax.print.attribute.standard"); 427 suppressFilter.add("org.jcp.xml.dsig"); 437 suppressFilter.add("org.jcp.xml.dsig"); // bloat in the RTL - why should we worry about that? 428 438 429 System.out.printf("# PkgSig file for jarfile '%s'\n", jarFile.getAbsolutePath()); 430 processJarFile(jarFile.getAbsolutePath(), loader, null, suppressFilter, clsSet); 431 432 for ( Class cls : clsSet) { 433 new ClassSig(cls).emit(); 434 } 439 PkgSig.sigForJarFile("rt.jar", suppressFilter); 435 440 } 436 441 else { 437 442 usage(); … … 448 453 Class cls; 449 454 TypeVariable<?>[] genericParams = {}; 450 455 int indent= 0; 451 456 static String TYPE_SEP = ","; 457 452 458 public ClassSig(Class cls) { 453 459 this.cls = cls; 454 460 } … … 486 492 System.out.printf( "%-30s %s\n", t, "# JavaType"); 487 493 488 494 printIndent(); 489 System.out.printf("%-30s %s\n", this.cls.getPackage().getName(), "# package"); 495 String pkgName = this.cls.getPackage().getName(); 496 System.out.printf("%-30s %s\n", pkgName, "# package"); 490 497 491 // Name of the class, dotNet form for Generic class 492 String clsName = this.cls.getSimpleName(); 493 Class enclClass = this.cls.getEnclosingClass(); 494 if ( enclClass != null) { 495 clsName = enclClass.getSimpleName() + "$" + this.cls.getSimpleName(); 496 flags += "N"; 497 } 498 // Name of the class(without pkgname), dotNet form for Generic class 499 String clsName = this.cls.getName(); 500 if (clsName.startsWith(pkgName+".")) 501 clsName = clsName.substring(pkgName.length()+1); 498 502 String gName = this.dotNetGenericsName(this.cls, clsName); 499 503 if (! gName.isEmpty()) { 500 504 clsName = gName; … … 524 528 // Interfaces 525 529 //System.out.printf("%-30s %s\n", '-', " # interfaces"); 526 530 //Class[] interfaces = this.cls.getInterfaces(); 527 //emitClassList(interfaces, "interfaces"); 528 Type[] gInterfaces = this.cls.getGenericInterfaces(); 531 //emitClassList(interfaces, "nonG interfaces"); 532 Type[] gInterfaces = getAllGenericInterfaces(this.cls); 533 //Type[] gInterfaces = this.cls.getGenericInterfaces(); 529 534 emitTypesList(gInterfaces, " Interfaces"); 535 //System.out.printf("### nIfcs %d, ngIfcs %d\n", interfaces.length, gInterfaces.length); 530 536 531 537 // Modifiers 532 538 //System.out.printf("%-30s %s\n", '-', " # modifiers"); … … 709 715 for (Class c : clsList) { 710 716 sb.append(sep); 711 717 sb.append(c.getName()); 712 sep = ",";718 sep = TYPE_SEP; 713 719 } 714 720 if (clsList.length == 0 ) 715 721 sb.append("-"); … … 732 738 for (TypeVariable<?> p : this.genericParams) { // 733 739 sb.append(sep); 734 740 sb.append(p.getName()); 735 sep = ","; 741 sep = TYPE_SEP; 742 736 743 } 737 744 //if (this.genericParams.length == 0 ) 738 745 // return; //sb.append("-"); … … 751 758 sb.append(sep); 752 759 String tStr = this.makeTypeStr(t); 753 760 sb.append(tStr); 754 sep = ","; 761 sep = TYPE_SEP; 762 755 763 } 756 764 if (typList.length == 0 ) { 757 765 //if (isOptional) … … 774 782 775 783 /* 776 784 * Cleanup a (Generic) Type name to be 'consistant' with class naming. 785 * 786 * @param t Type to do name cleanup on 787 * @return String representation of 'cleaned' Type 777 788 */ 778 789 public String makeTypeStr(Type t) { 779 790 String tStr = t.toString(); 791 //System.out.printf("### %-50s \n", tStr); 792 tStr = tStr.replace("java.util.Map.java.util.Map", "java.util.Map"); // EntrySets screwed for some reason 793 780 794 tStr = tStr.replace("class ", ""); // sometimes puts on leading 'type ' 781 795 tStr = tStr.replace("interface ", ""); 782 796 // possibly others - enum ? … … 794 808 } 795 809 return tStr; 796 810 } 811 812 /* Walk class inheritance hierachy from a class up, accumulate and return all the 813 * interfaces (generic and not) supported. 814 * Uses getGenericInterfaces to lookup interfaces for each class. 815 * 816 * @param cls Class to obtain all interfaces for. 817 * @return Array of Types containing all generic interfaces found 818 */ 819 public Type[] getAllGenericInterfaces(Class cls) { 820 List<Type> ifcs = new ArrayList<Type>(); 821 while ( cls != null ) { 822 for ( Type t : cls.getGenericInterfaces() ) 823 ifcs.add(0, t); // insert at front so list is in superclass downwards order 824 cls = cls.getSuperclass(); 825 } 826 827 // remove any dups using a Set 828 Set<Type> ifcSet = new LinkedHashSet<Type>(); 829 for ( Type t : ifcs ) 830 ifcSet.add(t); 831 return ifcSet.toArray(new Type[0]); 832 } 797 833 } -
Source/Cobra.Lang/Java/mkjar
10 10 [ $? == 0 ] || exit 11 11 cp CobraLang.jar ../.. 12 12 13 #java -cp '.;CobraLang.jar' PkgSig -j CobraLang.jar > CobraLang.jar.sig 13 #echo 'pkgSig for CobraLang.jar' 14 java -cp '.;CobraLang.jar' PkgSig -j CobraLang.jar > CobraLang.jar.sig 15 cp CobraLang.jar.sig ../.. 16 17 14 18 ## assume rt.jar, java.util and java.lang sigfiles already exist and are static 15 19 #cp CobraLang.jar.sig rt.jar.sig java.util.sig java.lang.sig ../.. -
Source/Cobra.Lang/Java/mkjarAll
20 20 java -cp '.;CobraLang.jar' PkgSig -j CobraLang.jar > CobraLang.jar.sig 21 21 22 22 echo 'Gen pkgSig file for rt.jar' 23 java -cp . PkgSig -j rt.jar> rt.jar.sig23 java -cp . PkgSig -jrt > rt.jar.sig 24 24 echo 'Gen pkgSig file for java.lang' 25 25 java -cp . PkgSig java.lang > java.lang.sig 26 26 echo 'Gen pkgSig file for java.util' -
Source/Cobra.Lang/CobraCore.cobra
385 385 require false 386 386 pass 387 387 388 get runtimePlatform as String 389 return 'clr' 390 #return 'jvm' 391 # return 'objc' 392 388 393 var _isRunningOnMono as bool? 389 394 390 395 get isRunningOnMono as bool -
Source/Cobra.Lang/Tracer.cobra
13 13 var _isActive = true 14 14 var _willAutoFlush = true 15 15 var _dest as TextWriter 16 var _separator = '; 16 var _separator = ';\n -:' 17 17 var _prefix = ' trace: ' 18 18 var _willOutputDirectoryNames = false 19 19 -
Source/Node.cobra
1188 1188 ## More types 1189 1189 # TODO: move up to ITypeProvider? 1190 1190 1191 #get clrPrimitiveToITypeCache as IDictionary<of System.Type, IType>?1192 1191 get primitiveToITypeCache as IDictionary<of dynamic, IType>? 1193 1192 1194 1193 get basicTypes as IList<of PrimitiveType> -
Source/Module.cobra
37 37 var _topNameSpace as NameSpace 38 38 var _mustBindInhList = List<of INameSpaceMember>() 39 39 40 #cue init(ass as Assembly, globalNS as NameSpace)41 # .init(ass, 0, globalNS)42 43 #cue init(ass as Assembly, verbosity as int, globalNS as NameSpace)44 # base.init(ass.location, verbosity, '')45 # _topNameSpace = NameSpace(globalNS, '(top namespace for assembly [ass])')46 47 40 cue init(location as String, globalNS as NameSpace) 48 41 .init(location, 0, globalNS) 49 42 … … 63 56 64 57 def _bindInh 65 58 base._bindInh 66 # .topNameSpace.bindInh - It's too expensive to scan all types in a DLL. Do them as needed. 59 # .topNameSpace.bindInh - It's too expensive to scan all types in a DLL. Do them as needed. (See Box._prepIfNeeded) 67 60 for item in _mustBindInhList, item.bindInh 68 61 69 62 def _bindInt 70 63 base._bindInt 71 # .topNameSpace.bindInt - It's too expensive to scan all types in a DLL. Do them as needed. 64 # .topNameSpace.bindInt - It's too expensive to scan all types in a DLL. Do them as needed. (See Box._prepIfNeeded) 72 65 73 66 74 67 class CobraModule inherits Module is partial 68 """ 69 Module for a cobra source File. 70 Holds name, docString and the topLevelNamespace as the root of the parsed AST nodes. 71 Also handles binding by passing bind invocation onto its namespace to action. 72 """ 75 73 76 74 cue init(fileName as String, verbosity as int, docString as String, globalNS as NameSpace) 77 75 base.init(fileName, verbosity, docString) -
Source/NameSpace.cobra
13 13 is partial 14 14 inherits Container<of INameSpaceMember> 15 15 implements IParentSpace, INameSpaceMember 16 16 17 """ 18 Two flavours of NameSpace 19 Unified - holds decls + NameSpaces 20 Non-unified - holds decls + NameSpaces and list of Use Directives done in the namespace. 21 - points to its corresponding unified namespace 22 23 (Most) modules have a topLevel namespace that holds the modules contents 24 The compiler holds a global namespace for the program containing all top level namespaces and (system) namespaces referenced. 25 """ 26 17 27 var _unifiedNameSpace as NameSpace? 18 28 var _superNameSpace as NameSpace? 19 29 var _subNameSpacesByName as Dictionary<of String, NameSpace> … … 131 141 ns = _subNameSpacesByName[name] 132 142 else 133 143 if _declsByName.containsKey(name) 134 throw Exception('There is a non-namespace declaration named "[name]".')144 return .compiler.backEnd.handleNameSpaceNameCollision(this, token, name) 135 145 ns = NameSpace(token, name, this) 136 146 if not .isUnified 137 147 # mirror in the unified namespace … … 267 277 m = ud.extensionMemberFor(box, name) 268 278 if m, return m 269 279 return if(_superNameSpace, _superNameSpace._extensionMemberFromUseDirectives(box, name), nil) 270 280 271 281 def symbolForName(name as String) as IMember? 272 282 if not .isUnified 273 283 x = _unifiedNameSpace.symbolForName(name) … … 291 301 # our decl? 292 302 # TODO: should this come before checking our name? what does C# do? 293 303 x = .declForName(name) 294 if x, return x 304 if x 305 return x 295 306 /# 296 307 # wrong. see ticket:128 297 308 # a parent namespace? -
Source/Phases/BindUsePhase.cobra
87 87 # curNS = nil # force reference attempt 88 88 if curNS is nil and not didAutoLoad 89 89 if _fileName <> '' 90 #if .compiler.loadReference(_fileName + '.dll')91 90 if .compiler.loadReference(_fileName, true) 92 91 _bindUse(true) 93 92 if .boundNameSpace is nil … … 99 98 return 100 99 .throwError('Cannot find library file "[_fileName]".') 101 100 else 102 if _fullName.endsWith('.dll') 103 .throwError('Do not end a namespace name in a "use" directive with ".dll".') 104 #if .compiler.loadReference(_fullName + '.dll') 101 if _fullName.endsWith('.dll') or _fullName.endsWith('.jar') 102 .throwError('Do not end a namespace name in a "use" directive with an extension (like ".dll" or ".jar").') 105 103 if .compiler.loadReference(_fullName, true) 106 104 _bindUse(true) 107 105 if .boundNameSpace is nil … … 119 117 if curNS is nil, break 120 118 partialName += '.' + name 121 119 if partialName == '' 120 #assert false 122 121 .throwError('Cannot find namespace "[_fullName]".') 123 122 else 124 123 .throwError('Cannot find namespace "[name]" in "[partialName[1:]]".') -
Source/Phases/BindInterfacePhase.cobra
1 1 class BindInterfacePhase inherits Phase 2 2 """ 3 Set the typing of interfacing or API items. 3 4 Bind the AST nodes for var types, parameter types, return types, etc. to their actual types. 4 5 Does not look inside implementations of methods and properties; only at the interface/API of the types. 5 6 """ -
Source/Phases/BindRunTimeLibraryPhase.cobra
38 38 filesPath = Path.combine(Path.combine(.cobraExeDir, 'Cobra.Lang'), 'files.text') 39 39 runTimePaths = c.commandLineArgParser.readFilesFile(filesPath) 40 40 runTimePaths.reverse 41 rtlSrcFile = c.backEnd.rtlSrcFile #'Native.cs' 42 assert rtlSrcFile.count(c'.') == 1 41 43 for runTimePath in runTimePaths 42 if Path.getFileName(runTimePath) == 'Native.cs'44 if Path.getFileName(runTimePath) == rtlSrcFile 43 45 suffix = .options.embedRunTimeSuffix 44 46 nativeCode = File.readAllText(runTimePath) 45 47 nativeCode = nativeCode.replace('namespace Cobra.Lang', 'namespace Cobra.Lang'+suffix) 46 newPath = Path.getFullPath( 'Native[suffix].cs')48 newPath = Path.getFullPath(rtlSrcFile.before('.') + suffix + '.' + rtlSrcFile.after('.')) 47 49 File.writeAllText(newPath, nativeCode) 48 50 c.addIntermediateFile(newPath) 49 51 pathsToCompile.insert(0, newPath) -
Source/Utils.cobra
54 54 extend String 55 55 56 56 # These should go in String Extensions 57 def before L(sep as String) as String57 def before(sep as String) as String 58 58 test 59 59 s = 'abc|de' 60 assert s.before L('|') == 'abc'61 assert s.before L('=') == 'abc|de'62 assert '|abcde'.before L('|') == ''63 assert 'abcde|'.before L('|') == 'abcde'60 assert s.before('|') == 'abc' 61 assert s.before('=') == 'abc|de' 62 assert '|abcde'.before('|') == '' 63 assert 'abcde|'.before('|') == 'abcde' 64 64 body 65 65 idx = .indexOf(sep) 66 66 if idx < 0 67 67 return this 68 68 return this[0:idx] 69 69 70 def after L(sep as String) as String70 def after(sep as String) as String 71 71 test 72 72 s = 'abc|de' 73 assert s.after L('|') == 'de'74 assert s.after L('=') == ''75 assert '|abcde'.after L('|') == 'abcde'76 assert 'abcde|'.after L('|') == ''73 assert s.after('|') == 'de' 74 assert s.after('=') == '' 75 assert '|abcde'.after('|') == 'abcde' 76 assert 'abcde|'.after('|') == '' 77 77 body 78 78 idx = .indexOf(sep) 79 79 if idx < 0 -
Source/BackEndClr/ClrType.cobra
193 193 # clrPrimitiveToIType = Dictionary<of dynamic, IType>() 194 194 for bt in .compiler.basicTypes 195 195 if bt.systemAliasProxy 196 key = (.compiler.nativeType((bt.systemAliasProxy to LibraryTypeProxy).qualifiedName) to ClrNativeType).clrType # TODO: hops cleanup no ClrNativeType196 key = (.compiler.nativeType((bt.systemAliasProxy to LibraryTypeProxy).qualifiedName) to ClrNativeType).clrType 197 197 clrPrimitiveToIType[key] = bt 198 198 assert clrPrimitiveToIType.count == 0 or clrPrimitiveToIType.count > 9 199 199 return clrPrimitiveToIType -
Source/BackEndClr/ScanClrType.cobra
239 239 finally 240 240 _curModule = saveModule 241 241 242 def dotNetfixNilableMemberSigs 242 def dotNetFixNilableMemberSigs 243 # Fix the listed members to be non Nilable 243 244 # TODO: this really needs to go in a separate file that the compiler reads each time 244 245 245 # TODO: look to see if what the Spec# team put together can be leveraged instead of recreating all this work! 246 # fix up member sigs regarding nilable247 246 # hard coded below. TODO: read from a Cobra config file 248 247 _fix('System.Object', 'toString getType memberwiseClone') 249 248 # ^ regarding .toString, not technically true, but common enough and life is too painful when the return type is nilable … … 433 432 def isClrSystemExceptionClass as bool 434 433 return .name == 'Exception' and .parentNameSpace and .parentNameSpace.fullName == 'System' 435 434 436 def _prepSystemObjectClassClr435 def prepSystemObjectClassClr 437 436 # Pretend .NET is a bit more OO, consistent and elegant. 438 437 # C#'s typeof(X) is X.getType in Cobra. 439 438 existing = .declForName('getType') to BoxMember … … 443 442 meth.sharedMethodBacking = 'typeof' 444 443 overload.addMember(meth) 445 444 446 def _scanNativeTypeClr445 def scanNativeTypeClr 447 446 """ 448 447 Subclasses should invoke base and then invoke the various _scanFoo methods that are appropriate for them. 449 448 """ … … 452 451 # print '<> _scanNativeType for [.name] in [_parentNameSpace.fullName], class is [.getType.name]' 453 452 454 453 455 def _scanGenericArgsClr454 def scanGenericArgsClr 456 455 if _clrType.isGenericType 457 456 for genArg in _clrType.getGenericArguments 458 457 t = (.compiler to Compiler).typeForClrType(genArg) … … 818 817 class Class 819 818 is partial 820 819 821 def _scanNativeTypeClr822 base. _scanNativeTypeClr820 def scanNativeTypeClr 821 base.scanNativeTypeClr 823 822 _scanClrIsNames 824 823 _scanClrImplements 825 824 _scanClrNestedTypes … … 835 834 class Interface 836 835 is partial 837 836 838 def _scanNativeTypeClr839 base. _scanNativeTypeClr837 def scanNativeTypeClr 838 base.scanNativeTypeClr 840 839 _scanClrIsNames 841 840 _scanClrImplements 842 841 _scanClrNestedTypes … … 849 848 class Struct 850 849 is partial 851 850 852 def _scanNativeTypeClr853 base. _scanNativeTypeClr851 def scanNativeTypeClr 852 base.scanNativeTypeClr 854 853 _scanClrIsNames 855 854 _scanClrImplements 856 855 _scanClrNestedTypes … … 863 862 864 863 class Extension is partial 865 864 866 def _scanNativeTypeClr865 def scanNativeTypeClr 867 866 # this only for Cobra specific extensions. Example: class Extend_String_1939 868 base. _scanNativeTypeClr867 base.scanNativeTypeClr 869 868 _scanClrIsNames 870 869 #_scanClrImplements 871 870 #_scanClrNestedTypes … … 894 893 895 894 class EnumDecl is partial 896 895 897 def _setUnderlyingTypeClr 896 cue init(parent as IParentSpace?, nativeType as NativeType) 897 .init(parent, nativeType, List<of String>(), '') 898 899 def setUnderlyingTypeClr 898 900 _storageTypeNode = ClrTypeProxy(Enum.getUnderlyingType((_nativeType to ClrNativeType).backEndType)) 899 901 900 def _scanNativeTypeClr902 def scanNativeTypeClr 901 903 # TODO: read attribs 902 904 _needScanNativeType = false 903 905 clrType = (_nativeType to ClrNativeType).clrType -
Source/BackEndClr/ClrBackEnd.cobra
13 13 _typeTypeProxy = ClrTypeProxy(Type) 14 14 _name = 'c#-clr' 15 15 _rtlName = 'Cobra.Lang.dll' 16 _rtlSrcFile = 'Native.cs' # backEnd source file containing native code support for Cobra.Lang 16 17 17 18 _tagToTypeName = { 18 19 'Object' : 'System.Object', … … 51 52 'uint32': 'System.UInt32', 52 53 'uint64': 'System.UInt64', 53 54 } 54 55 55 56 def makePhases(phases as IList<of Phase>) is override 56 57 phases.add(GenerateSharpCodePhase(.compiler)) 57 58 phases.add(CompileSharpCodePhase(.compiler)) 58 59 60 def getRecommendedBuiltInType(parentNameSpace as NameSpace?, name as String) as String? is override 61 n = nil to String? 62 if parentNameSpace and parentNameSpace.fullName == 'System' 63 branch name 64 on 'Boolean', n = 'bool' 65 on 'SByte', n = 'int8' 66 on 'Byte', n = 'uint8' 67 on 'Int16', n = 'int16' 68 on 'UInt16', n = 'uint16' 69 on 'Int32', n = 'int32' 70 on 'UInt32', n = 'uint32' 71 on 'Int64', n = 'int64' 72 on 'UInt64', n = 'uint64' 73 on 'Char', n = 'char' 74 on 'Single', n = 'float32' 75 on 'Double', n = 'float' 76 on 'Decimal', n = 'decimal' 77 return n 78 59 79 def computeOutName as String is override 60 80 return .compiler.computeOutNameSharp 61 81 … … 119 139 .compiler.clrReadAssembly(t.assembly) # System.dll 120 140 121 141 def fixNilableMemberSigs is override 122 .compiler.dotNet fixNilableMemberSigs # in ScanClrType142 .compiler.dotNetFixNilableMemberSigs # in ScanClrType 123 143 124 144 # Types 125 145 get objectTypeProxy from var is override … … 160 180 def installNativeMethods(box as Box, nativeType as NativeType) is override 161 181 .compiler.installClrNativeMethods(box, nativeType) # in ScanClrType 162 182 163 def addArrayInterfaces( interfaces as List<of ITypeProxy>) is override 164 iclone = .compiler.libraryType('ICloneable') 165 interfaces.insert(0, iclone to ITypeProxy) 183 184 def prepSystemObjectClass(box as Box) is override 185 box.prepSystemObjectClassClr 186 187 def scanGenericArgs(box as Box) is override 188 box.scanGenericArgsClr 189 190 def scanNativeType(box as Box) is override 191 """ Do scan/Load of Types from a dll """ 192 box.scanNativeTypeClr 193 194 def scanNativeType(edcl as EnumDecl) is override 195 edcl.scanNativeTypeClr 196 197 def setUnderlyingType(edcl as EnumDecl) is override 198 edcl.setUnderlyingTypeClr 166 199 167 200 def determineExtnNativeType(extn as Extension, nativeType as NativeType) as NativeType is override 201 return extn.clrExtnNativeType(nativeType) # ScanClrType 202 203 def handleNameSpaceNameCollision(ns as NameSpace, token as IToken, name as String) as NameSpace is override 204 """Clr doesnt allow colliding names.""" 205 throw Exception('In [ns.name] there is a already non-namespace declaration named "[name]".') 168 206 207 208 169 209 class GenerateSharpCodePhase inherits Phase 170 210 171 211 cue init(c as Compiler) -
Source/Types.cobra
1095 1095 base.init(superType) 1096 1096 _size = size 1097 1097 branch size 1098 on 32, _nativeType = .typeProvider.nativeType('single')1099 on 64, _nativeType = .typeProvider.nativeType('double')1098 on 32, tag = 'single' 1099 on 64, tag = 'double' 1100 1100 else, throw FallThroughException(size) 1101 _systemAliasProxy = LibraryTypeProxy(_nativeType.fullName) 1101 _nativeType = .typeProvider.nativeType(tag) 1102 _systemAliasProxy = LibraryTypeProxy(tag) 1102 1103 1103 1104 def addMinFields 1104 1105 base.addMinFields … … 1202 1203 _size = size 1203 1204 if signed 1204 1205 branch size 1205 on 8, _nativeType = .typeProvider.nativeType('sbyte')1206 on 16, _nativeType = .typeProvider.nativeType('int16')1207 on 32, _nativeType = .typeProvider.nativeType('int32')1208 on 64, _nativeType = .typeProvider.nativeType('int64')1206 on 8, tag = 'sbyte' 1207 on 16, tag = 'int16' 1208 on 32, tag = 'int32' 1209 on 64, tag = 'int64' 1209 1210 else, throw FallThroughException(size) 1210 1211 else 1211 1212 branch size 1212 on 8, _nativeType = .typeProvider.nativeType('byte')1213 on 16, _nativeType = .typeProvider.nativeType('uint16')1214 on 32, _nativeType = .typeProvider.nativeType('uint32')1215 on 64, _nativeType = .typeProvider.nativeType('uint64')1213 on 8, tag = 'byte' 1214 on 16, tag = 'uint16' 1215 on 32, tag = 'uint32' 1216 on 64, tag = 'uint64' 1216 1217 else, throw FallThroughException(size) 1217 _systemAliasProxy = LibraryTypeProxy(_nativeType.fullName) 1218 _nativeType = .typeProvider.nativeType(tag) 1219 _systemAliasProxy = LibraryTypeProxy(tag) 1218 1220 1219 1221 def addMinFields 1220 1222 base.addMinFields … … 1731 1733 ienum = .compiler.enumerableOfType.constructedTypeFor([.theWrappedType]) 1732 1734 _ilistOf = .compiler.ilistOfType.constructedTypeFor([.theWrappedType]) to Interface 1733 1735 interfaces = [icoll to ITypeProxy, ienum] # TODO:, _ilistOf] -- problems with cobra -ert:yes hello and extension method String.split 1734 .compiler.backEnd.addArrayInterfaces(interfaces) 1736 iclone = .compiler.libraryType('ICloneable') 1737 interfaces.insert(0, iclone to ITypeProxy) 1735 1738 _box = Class(Token.empty, Token.empty, '[.getType.name]_[.serialNum]', List<of IType>(), List<of String>(), AttributeList(), nil, interfaces, List<of ITypeProxy>(), nil) 1736 1739 # TODO: make members based on System.Array 1737 1740 indexer = Indexer(Token.empty, Token.empty, _box, r'[]', [Param(Token('', 1, 1, 1, 'ID', 'index', nil), .compiler.intType)], _wrappedType, List<of String>(), AttributeList(), '') -
Source/BackEndJvm/JvmJarSig.cobra
25 25 var classByNameCache = Dictionary<of String, JavaClassType>() 26 26 """All classes found in all jars keyed by canonical/full name.""" 27 27 28 def lookupClassByCobraName(fullCobraName as String) as JavaClassType 29 """ 30 This is the only way to access the JarSig classCache contents from outside this file. 31 """ 32 assert fullCobraName[0].isUpper 33 parts = fullCobraName.split('.') 34 for i in 0: parts.length-1 35 parts[i] = parts[i][0].toLower.toString + parts[i][1:] 36 fullName = parts.join('.') 37 #print 'Lookup "[fullCobraName]" as "[fullName]"' 38 return JarSig.classByNameCache[fullName] 39 28 40 def lookupClass(fullName as String) as JavaClassType 29 41 """ Lookup class by full/canonicalName.""" 30 42 if not JarSig.classByNameCache.containsKey(fullName) 31 if fullName.startsWith(r'['), .addArrayClass(fullName) 32 else if fullName.contains(r'<'), .addGenericInstClass(fullName) 33 else if not fullName.contains('.'), .addGenericParamClass(fullName) 43 if fullName.startsWith(r'[') # [a.b.c; 44 .addArrayClass(fullName) 45 else if fullName.contains(r'<') # Generic a.b.c<a.b.c,..> or a.b.c<T> or a.b.c<?...> 46 paramList = fullName.after('<') 47 if _hasBoundParam(paramList), .addGenericInstClass(fullName) # shld this be a genericDefn ? 48 else if paramList.contains('.'), .addGenericInstClass(fullName) 49 else, return .findAliasGenericDefnClass(fullName) 50 else if fullName.startsWith('?') or _hasBoundParam(fullName) or not fullName.contains('.') 51 .addGenericParamClass(fullName) 34 52 else 35 print 'Dbg:JarSig.lookupClass - unknown class: [fullName]'53 print 'Dbg:JarSig.lookupClass - unknown class:"[fullName]".' 36 54 #print 'Lookup class', fullName 37 55 return JarSig.classByNameCache[fullName] 38 56 57 # java bounded generic param '<? extends TYPE>' or '<? super TYPE>' 58 def _hasBoundParam(name as String) as bool 59 return name.contains(' extends ') or name.contains(' super ') or name.contains('?') 60 39 61 def addArrayClass(aName as String) 40 62 """Array classes are synthesized on reference assuming element class already exists.""" 41 print 'Dbg crt ArrayClass "[aName]"'63 #print 'Dbg crt ArrayClass "[aName]"' 42 64 elName = aName.replace(r'[','') 43 65 branch elName 44 66 on 'Z', elName = 'boolean' … … 61 83 elType = JarSig.lookupClass(elName) 62 84 arrayCls = JavaClassType(aName, elType) # ArrayType 63 85 JarSig.classByNameCache[aName] = arrayCls 64 print 'Dbg: added ArrayOf_[elName] "[aName]"'86 #print 'Dbg: added ArrayOf_[elName] "[aName]"' 65 87 66 88 def addGenericInstClass(fullName as String) 67 89 """ … … 69 91 e.g. com.x.MyClass<com.x.Inst, java.lang.String> 70 92 Synthesized (here) as a result of being referenced. 71 93 """ 72 print 'Dbg crt GenericInstClass "[fullName]"'94 #print 'Dbg crt GenericInstClass "[fullName]"' 73 95 assert fullName.contains('<') and fullName.endsWith('>') 74 canonName = fullName.before L('<')96 canonName = fullName.before('<') 75 97 assert canonName.contains('.') 76 98 idx = canonName.lastIndexOf('.') 77 99 gName = canonName[idx+1:] 78 100 pkg = canonName[0:idx] 79 paramTypes = fullName.after L('<')[0:-1] # drop end '>'80 print 'Dbg: GenericInstanceClass "[pkg]" "[gName]" "[paramTypes]'101 paramTypes = fullName.after('<')[0:-1] # drop end '>' 102 #print 'Dbg: GenericInstanceClass "[pkg]" "[gName]" "[paramTypes]' 81 103 giCls = JavaClassType(gName, pkg, paramTypes) 82 104 JarSig.classByNameCache[fullName] = giCls 83 # JarSig.registerClassType(pkg, giCls)84 print 'Dbg: added GenericInstanceClass "[fullName]"'105 #JarSig.registerClassType(fullName, giCls) 106 #print 'Dbg: added GenericInstanceClass "[fullName]"' 85 107 108 def findAliasGenericDefnClass(fullName as String) as JavaClassType 109 """ 110 Generic class being used as a param where declared with different param list 111 Generic class defn redeclared with a specific bound paramList 112 e.g. com.x.MyClass<? extends a.b.c>, com.x.MyClass<? super d.e> 113 com.x.myClass<V>, vs dcl as com.x.myClass<TValue> 114 Synthesized (here) as a result of being referenced. 115 """ 116 assert fullName.contains('<') and fullName.endsWith('>') 117 canonName = fullName.before('<') 118 #params = fullName.after('<')[0:-1] # drop end '>' 119 #nParams = 1 + params.count(c',') # params.countOf(c',') 120 #assert canonName.contains('.') 121 #idx = canonName.lastIndexOf('.') 122 #gDefName = canonName[idx+1:] + '`[nParams]' 123 #pkg = canonName[0:idx] 124 #print 'Dbg: GenericDefnClass "[canonName]" "[params]"' 125 return JarSig.lookupClass(canonName) 126 # Shld already exist but prob with different paramNames in paramList 127 #gDefCls = JavaClassType(gDefName, pkg, params) 128 #JarSig.classByNameCache[fullName] = gDefCls 129 #JarSig._registerClassType(fullName, giCls) 130 #print 'Dbg: added GenericDefinitionClass "[fullName]"' 131 86 132 def addGenericParamClass(name as String) 87 print 'Dbg crt Generic Param Class "[name]"'133 #print 'Dbg crt Generic Param Class "[name]"' 88 134 gparamCls = JavaClassType(name, JavaType.GenericParam, '') 89 135 JarSig.classByNameCache[name] = gparamCls 90 print 'Dbg: added Generic Parameter Class "[name]"'136 #print 'Dbg: added Generic Parameter Class "[name]"' 91 137 92 138 def sigFile(name as String) as String is shared 93 139 """ … … 136 182 _registerClassType(jct) 137 183 138 184 def _registerClassType(jct as JavaClassType) 139 _javaTypes.add(jct)140 185 canonName = jct.canonicalName 141 186 if '`' in canonName # jct.isGeneric 142 canonName = canonName.beforeL('`') 143 #parts = canonName.split('`') 144 #canonName = parts[0] 187 canonName = canonName.before('`') # canonName = canonName.split('`')[0] 188 _registerClassType(canonName, jct) 189 190 def _registerClassType(canonName as String, jct as JavaClassType) 191 _javaTypes.add(jct) 145 192 JarSig.classByNameCache[canonName] = jct 146 193 #print 'Dbg: register [canonName]' 194 147 195 def _aliasPrimitives 148 196 if JarSig.classByNameCache.containsKey('void') 149 197 return … … 155 203 JarSig.classByNameCache['short'] = JarSig.classByNameCache['java.lang.Short'] 156 204 JarSig.classByNameCache['int'] = JarSig.classByNameCache['java.lang.Integer'] 157 205 JarSig.classByNameCache['long'] = JarSig.classByNameCache['java.lang.Long'] 206 #l = JarSig.classByNameCache['java.lang.Long'] 207 #l = l.copy('long','') 208 #JarSig.classByNameCache['long'] = l 209 #_javaTypes.add(l) 158 210 JarSig.classByNameCache['float'] = JarSig.classByNameCache['java.lang.Float'] 159 211 JarSig.classByNameCache['double'] = JarSig.classByNameCache['java.lang.Double'] 160 212 … … 196 248 197 249 198 250 var name = '' 199 var package = '' 251 var package = '' # ->? FlyWeight this - save some string space? 200 252 var type = JavaType.NoType #class,interface, enum 201 253 var superclass = '' 202 254 var modifiers as List<of String> 203 255 var interfaceNames as List<of String> 204 256 var _interfaces as List<of JavaClassType> = JavaClassType.emptyClassList 257 var _nestedTypes as List<of JavaClassType> = JavaClassType.emptyClassList 205 258 206 259 var _fields as List<of JavaFieldInfo> = JavaClassType._emptyFieldList # JavaFieldInfo* 207 260 var _props as List<of JavaFieldInfo> = JavaClassType._emptyFieldList # JavaFieldInfo* … … 262 315 263 316 # header - fixed length and format; absName, type, pkg, name, superclass, interfacesList, ModifiersList 264 317 absName = _popTop(lines) # absolute class name 265 CobraCore.noOp(absName)318 #CobraCore.noOp(absName) 266 319 branch _popTop(lines).toLower 267 320 on 'class', type = JavaType.JavaClass 268 321 on 'interface', type = JavaType.JavaInterface … … 273 326 isGen = name.contains('`') 274 327 super = _popTop(lines) 275 328 if super == '-', super = '' 276 interfaces = _parseList(_popTop(lines) , [c','])329 interfaces = _parseList(_popTop(lines)) 277 330 modifiers = _parseList(_popTop(lines), [c' ']) 278 if isGen, gParamNames = _parseList(_popTop(lines) , [c','])331 if isGen, gParamNames = _parseList(_popTop(lines)) 279 332 while true 280 333 et = _popTop(lines) 281 334 if et.length == 0, break … … 289 342 # procField(et, subline, field, fieldList) 290 343 field.modifiers = _parseList(_popTop(lines), [c' ']) 291 344 field.typeName = _popTop(lines) 292 if type == JavaType.JavaEnum 345 if type == JavaType.JavaEnum and field.typeName == absName #'[pkg].[name]' 293 346 field.value = _popTop(lines) 294 #field.attributes = _parseList(_popTop(lines) , [c','])347 #field.attributes = _parseList(_popTop(lines)) 295 348 fieldList.add(field) 296 349 297 350 else if et.startsWith('ctor ') … … 299 352 ctor = JavaCtorInfo() 300 353 ctor.name = ctorName 301 354 assert lines.count >= 1 302 ctor.paramNames = _parseList(_popTop(lines) , [c','])355 ctor.paramNames = _parseList(_popTop(lines)) 303 356 # attributes ?? 304 357 ctorList.add(ctor) 305 358 … … 313 366 method.modifiers = _parseList(_popTop(lines), [c' ']) 314 367 method.returnTypeName = _popTop(lines) 315 368 assert method.returnTypeName <> '-' 316 method.paramNames = _parseList(_popTop(lines) , [c','])317 method.throwsList = _parseList(_popTop(lines) , [c','])369 method.paramNames = _parseList(_popTop(lines)) 370 method.throwsList = _parseList(_popTop(lines)) 318 371 # attributes ?? 319 372 if isVari, method.attributes = ['IsVari'] 320 373 methodList.add(method) … … 334 387 jct._methods = methodList 335 388 return jct 336 389 390 def _parseList(et as String) as List<of String> is shared 391 return _parseList(et, [c',']) 392 337 393 def _parseList(et as String, seps as List<of char> ) as List<of String> is shared 338 if et == '-' 339 l = List<of String>() 340 else 341 l = et.split(seps.toArray).toList 394 l = List<of String>() 395 if et == '-' 396 return l 397 if et.contains('<') 398 start = gCnt = 0 399 for i in 0 : et.length 400 c = et[i] 401 if c == c'<', gCnt += 1 402 if c == c'>', gCnt -= 1 403 if gCnt == 0 and c in seps 404 l.add(et[start:i].trim) 405 start = i+1 406 if start < et.length, l.add(et[start:].trim) 407 else 408 a = et.split(seps.toArray) 409 for s in a, l.add(s.trim) 342 410 return l 343 411 344 412 def _popTop(content as List<of String>) as String is shared … … 373 441 374 442 # indexer: get<Propname> and has params - first param in paramList is index (retType is Property Type) 375 443 # or set<PropName> and more than value in paramList, 1st parameter is index and second is value to set. 444 # hops: this isnt goanna work - too many false positives 445 # may work to hard case Collections, Lists and special case Maps... recognise annotation for user written code 376 446 def isIndexer(methodName as String, method as JavaMethodInfo, isSetProp) as bool is shared 377 447 if methodName.startsWith('is') 378 448 return false … … 392 462 prop = JavaFieldInfo() # JavaPropInfo 393 463 prop.name = propName 394 464 prop.isProp = true 395 prop.isIndexer = .isIndexer(method.name, method, isSetProp) 465 #prop.isIndexer = .isIndexer(method.name, method, isSetProp) 466 prop.isIndexer = false # TODO support indexers 396 467 prop.isReadable = prop.isWritable = false 397 468 props[propName] = prop 398 469 propList.add(prop) … … 426 497 .interfaceNames = ifcs 427 498 .modifiers = modifiers 428 499 429 _isGenericDefn = name.contains('`') # Generic types have name suffix `<nGenericArgs>500 _isGenericDefn = name.contains('`') # Defn Generic types have name suffix `<nGenericArgs> 430 501 431 502 #print '[type] [pkg].[name]' 432 503 assert .name.length … … 498 569 assert .name.contains(r'[') 499 570 500 571 cue init(name as String, pkg as String, paramTypes as String) 501 """Create a Generic Instantiation Type. Like MyClass<java.Lang.String>""" 572 """ 573 Create a Generic Instantiation Type. Assumes Generic Defn Type already exists 574 Like MyClass<java.Lang.String> for MyClass<T>. 575 """ 502 576 base.init 503 print 'JavaClassType.init([name])'577 #print 'JavaClassType.init([name])' 504 578 assert not name.contains('.') 505 579 #assert pkg.contains('.') 506 580 gPart = '[pkg].[name]' 507 paramList = JavaClassType._parseList(paramTypes , [c','])508 print 'Looking for Generic Class [gPart]'581 paramList = JavaClassType._parseList(paramTypes) 582 #print 'Looking for Generic Class [gPart]' 509 583 genType = JarSig.lookupClass(gPart) 510 584 assert genType.isGenericTypeDefinition 511 585 … … 522 596 _genParamNames= paramList 523 597 524 598 #print '[type] [pkg].[name]' 599 # print paramList 525 600 assert .name.length 526 601 assert .type <> JavaType.NoType 527 602 assert '`' in .superclass # fake parentage to the Generic Definition 528 603 assert .package.length 604 assert genType.genericArgsCount == _genParamNames.count 529 605 606 530 607 cue init(name as String, jType as JavaType, pkg as String) 531 608 """Create a Generic Parameter Type. Like the T of MyClass<T>""" 532 609 base.init 533 610 assert jType == JavaType.GenericParam 534 611 assert not name.contains("<") and not name.contains(">") 535 assert not name.contains(".")536 #assert name[0].isUpper # ??537 612 538 613 .name = name 539 614 .type = jType … … 551 626 assert .type <> JavaType.NoType 552 627 assert 'Object' in .superclass 553 628 assert .package.length 554 629 630 def copy( name as String, package as String) as JavaClassType 631 c = .memberwiseClone to JavaClassType 632 c.name = name 633 c.package = package 634 return c 555 635 556 636 #pro name from var 557 637 #pro package from var … … 561 641 """package and name""" 562 642 assert .name.length 563 643 return if(.package.length, '[.package].[.name]', .name) 564 644 645 get packageAsCobra as String 646 """ package name in Cobra Form - i.e each element Capitalized""" 647 # cache this map in a class var rather than recalc each time 648 parts = .package.split(c'.') 649 cobraParts = List<of String>() 650 for p in parts 651 cobraParts.add(p.capitalized) 652 return cobraParts.join('.') 653 565 654 get isClass as bool 566 655 return .type == JavaType.JavaClass 567 656 … … 575 664 #return .flags.contains('N') 576 665 return .name.contains('$') and not .name.startsWith('$') # temporary hack 577 666 667 def addNestedType(type as JavaClassType) 668 if _nestedTypes == JavaClassType.emptyClassList 669 _nestedTypes = List<of JavaClassType>() 670 _nestedTypes.add(type) 671 672 def getNestedTypes as JavaClassType* #List<of JavaClassType> 673 return _nestedTypes 674 578 675 get declaringType as JavaClassType? 579 676 if .isNested 580 677 assert .name.contains('$') 581 declName = .name.beforeL('$') 582 #idx = .name.indexOf('$') 583 #declName = .name[:idx] 584 trace declName 585 # return JarSig.classByNameCache[declName] 586 return JarSig.lookupClass(declName) 678 lidx = .canonicalName.lastIndexOf('$') 679 declName = .canonicalName[:lidx] 680 #trace .canonicalName, declName 681 if JarSig.classByNameCache.containsKey(declName) 682 return JarSig.lookupClass(declName) 587 683 return nil 588 684 685 get nestedName as String 686 require .isNested 687 assert .name.contains('$') 688 lidx = .canonicalName.lastIndexOf('$') 689 nestName = .canonicalName[lidx+1:] 690 #trace .canonicalName, declName 691 return nestName 692 589 693 get isPublic 590 694 return .modifiers.contains('public') 591 695 get isProtected … … 607 711 #return JvmNativeType(_type.getSuperClass) 608 712 if JarSig.classByNameCache.containsKey(.superclass) 609 713 return JarSig.lookupClass(.superclass) 610 #return JarSig.classByNameCache[.superclass]611 714 else 612 #return JarSig.classByNameCache['java.lang.Object']613 715 return JarSig.lookupClass('java.lang.Object') 614 716 # e.g. Abstract base classes with default access - java.lang.AbstractStringBuilder 615 717 #else … … 620 722 get isValueType as bool 621 723 return false # TODO true for unboxed primitives... 622 724 623 # TODO hops array handling624 725 get isArray as bool 625 726 return _isArray 626 727 627 728 get arrayComponentType as JavaClassType? 628 729 #if not .isArray, return nil 629 730 assert .isArray 630 print 'JavaClassType Array support NYI [.canonicalName]'631 731 return _arrayComponentType 632 732 633 733 get arrayDimension as int … … 635 735 assert _arrayDimension > 0 636 736 return _arrayDimension 637 737 638 # TODO hops Generics handling 639 # Two forms of Generic Types: Definition ( MyClass<T>) and Instantiation ( MyClass<java.lang.String>) 738 # Three forms of Generic Types: Definition ( MyClass<T>) and Instantiation ( MyClass<java.lang.String>) and Param ( T, java.lang.String) 640 739 # In java with runtime generic Type instantiation all we see from the jarfile directly are definitions (:-( 641 740 # Walking the classes and getting the class(names) referenced (params, intefaces, returnTypes,...) 642 741 # gives us the names of the instantiations which we synthesize as Types or Params for our purposes... 643 742 # or at least thats the plan 644 743 get isGenericType as bool 645 return _isGenericDefn or _isGenericInst or _isGenericParam744 return _isGenericDefn or _isGenericInst #or _isGenericParam 646 745 647 746 get genericArgsCount as int 648 747 assert .isGenericType … … 659 758 get isGenericParameter as bool 660 759 """ 661 760 assumes generic parameters are instantiated as Types. 662 Things like T,U,E,.. - basically simple names not package specified - probably 1 Upcase char 761 Things like T,U,E,.. - basically simple names 762 or qualified name java.lang.String 763 or bounded (possibly wildcard) type - ? extends Type, T super Type , T extends Type 663 764 """ 664 765 return _isGenericParam 665 766 666 767 get isGenericTypeDefinition as bool 667 768 """ 668 Can use this generic type to create new types if this type is a template form.769 Can use this generic type to create new types if this type is a template/Defn form. 669 770 e.g myClass<T, U> defn allows creating new type like MyClass<String, int> 771 myClass<T, U> is a generic definition 772 new type like MyClass<String, int> is a generic instance 773 T,U and String, int are their respective generic params 670 774 """ 671 775 assert .isGenericType 672 776 return _isGenericDefn 673 777 674 778 def getGenericArguments as JavaClassType* #List<of JavaClassType> 675 779 assert .genericArgsCount 676 if false # tmp pending jarSig gen and loading of generic args list 677 assert _genParamNames.count 780 assert _genParamNames.count 678 781 if _genParamNames.count and not _genParams.count 679 782 _genParams = JavaClassType.genClassTypeList(_genParamNames) 680 783 return _genParams … … 753 856 print prop 754 857 755 858 def dumpIndexers 756 assert false, ' Indexers NYI'859 assert false, 'dump Indexers NYI' 757 860 758 861 class JavaMemberInfo 759 862 var name = '' … … 817 920 get type as JavaClassType 818 921 assert .typeName.length 819 922 if .typeName.length and not _type 820 #_type = JarSig.classByNameCache[.typeName]821 923 _type = JarSig.lookupClass(.typeName) 822 924 return _type to ! 823 925 … … 892 994 def returnType as JavaClassType? 893 995 if not .returnTypeName.length 894 996 return nil 895 #return JarSig.classByNameCache[.returnTypeName]896 997 return JarSig.lookupClass(.returnTypeName) 897 998 898 999 def getGenericArguments as List<of JavaClassType> 899 return JavaClassType.emptyClassList # TODO: support generics 1000 #print 'TODO getGenArgs on method [.name]' 1001 return JavaClassType.emptyClassList # TODO: support generics on Method 900 1002 901 1003 def toString as String is override 902 1004 nampar = base.toString -
Source/BackEndJvm/JvmType.cobra
5 5 6 6 class JvmNativeType inherits NativeType 7 7 8 var _type as JavaClassType 9 #var _type as java.lang.Class8 var _type as JavaClassType # java.lang.Class eventually 9 var nestedName as String? 10 10 11 #cue init(type as java.lang.Class)12 11 cue init(type as JavaClassType) 13 12 base.init 14 13 _type = type … … 28 27 return _type 29 28 30 29 get name as String is override 31 #return _type.getSimpleName 32 return _type.name 30 return .nestedName ? _type.name 33 31 34 32 get fullName as String is override 35 33 return _type.canonicalName … … 146 144 return .typeProvider.arrayType(_realTypeWithCache(jvmType.arrayComponentType to !)) 147 145 else if jvmType.isNested and not jvmType.isGenericParameter 148 146 declaringType = _realTypeWithCache(jvmType.declaringType to !) 149 potential = declaringType.memberForName(jvmType.name) 147 cobraTypeName = .cobraNameForJvmBoxName(jvmType.nestedName) 148 potential = declaringType.memberForName(cobraTypeName) #(jvmType.name) 150 149 if potential is nil 151 .throwError('Cannot locate nested Jvm type "[jvmType]" (simple name is "[jvmType.name]").') 150 (declaringType to dynamic).dumpDeclNames 151 .throwError('JvmType: Cannot locate nested Jvm type "[jvmType]" (simple name is "[jvmType.name], cobraName is [cobraTypeName]").') 152 152 else if potential inherits IType 153 153 return potential 154 154 else 155 .throwError(' Located Jvm type spec "[jvmType]" but got a [potential.englishName] instead of a type.')155 .throwError('JvmType:Located Jvm type spec "[jvmType]" but got a [potential.englishName] instead of a type.') 156 156 157 157 # generic parameters 158 158 if jvmType.isGenericParameter … … 162 162 missing = false 163 163 curNS = _computeNameSpace(jvmType, level, out missing) 164 164 if missing 165 .throwError(' Cannot find Jvm type "[jvmType.canonicalName]" in package "[jvmType.package]".')165 .throwError('JvmType: Cannot find Jvm type "[jvmType.canonicalName]" in package "[jvmType.package]".') 166 166 # since the type exists, but cannot be located in our namespaces, 167 167 # it must be pulled from a dependent DLL that was not directly referenced 168 168 # but maybe it was already attempted … … 179 179 # So we have something like ICollection<of KeyValuePair<of TKey,TValue>> which is all Generic types. 180 180 # We need the Cobra types of those args so we can construct the Cobra type from the generic cobra type 181 181 # otherwise, we would just end up returning the generic definition. 182 print 'Dbg: JvmType.realTypeWithoutCache generic type [jvmType.canonicalName] [member.name].' 183 #.throwError('TODO support for Generic Types in JvmType _realTypeWithoutCache') 184 #member = _typeForArgsOfGeneric(jvmType, member) 182 #print 'Dbg: JvmType.realTypeWithoutCache generic type [jvmType.canonicalName] [member.name].' 183 member = _typeForJvmArgsOfGeneric(jvmType, member) 185 184 return member 186 185 else 187 186 print '[typeName] not in [curNS.name] declsforName' 188 msg = 'Cannot locate jvm type "[jvmType]".' 187 #curNS.dumpDeclNames 188 msg = 'JvmType: Cannot locate jvm type "[jvmType]".' 189 189 if jvmType.package.length and jvmType.package.startsWith('java.lang') 190 190 if .compiler and .compiler.verbosity > 1, print msg 191 191 # TODO: .compiler.warning(msg) … … 219 219 assert r'[' not in typeName 220 220 typeName = .cobraNameForJvmType(jvmType) 221 221 else if not typeName[typeName.length-1].isLetterOrDigit 222 .throwError(' Cannot locate JVM type "[jvmType.canonicalName]".')222 .throwError('JvmType: Cannot locate JVM type "[jvmType.canonicalName]".') 223 223 return typeName 224 224 225 225 def _computeNameSpace(jvmType as JavaClassType, level as int, missing as out bool) as NameSpace 226 226 missing = false 227 227 if not jvmType.package.length, return .compiler.globalNS 228 nameParts = jvmType.package .split(c'.')228 nameParts = jvmType.packageAsCobra.split(c'.') 229 229 member = .compiler.globalNS.symbolForName(nameParts[0]) 230 230 if member inherits NameSpace, curNS = member 231 231 else, missing = true … … 240 240 else if possible inherits NameSpace 241 241 curNS = possible 242 242 else 243 .throwError(' Found "[namePart]" at component [i+1] of JVM type "[jvmType.canonicalName]", but it is a [possible.englishName].')243 .throwError('JvmType: Found "[namePart]" at component [i+1] of JVM type "[jvmType.canonicalName]", but it is a [possible.englishName].') 244 244 i += 1 245 245 return curNS 246 246 … … 257 257 member = boxMember.constructedTypeFor(args) 258 258 return member 259 259 #/ 260 def _typeFor ArgsOfGeneric(jvmType as JavaClassType, member as IType) as IType260 def _typeForJvmArgsOfGeneric(jvmType as JavaClassType, member as IType) as IType 261 261 args = List<of IType>() 262 262 for genArg in jvmType.getGenericArguments 263 263 args.add(_realTypeWithCache(genArg)) 264 264 boxMember = member to Box 265 #trace jvmType, boxMember, args 265 266 member = boxMember.constructedTypeFor(args) 266 267 return member 267 268 -
Source/BackEndJvm/to-do.text
3 3 include-tests:no - remove Test invocation call 4 4 5 5 6 _fixNativeMethods - static method entries on box instance 7 8 6 9 fixup Object namespace for X-compile so items like System.Object are rooted off 7 10 java.lang namespace ( rather than .Net system) 8 11 DONE June-2011 … … 19 22 cobra namespaces capitalized (as .Net) Java all lowercase 20 23 - convert namespaces in java code to lowcase 21 24 DONE 31-Jan-2011 25 Unworkable Jul-2011 - cobra assumptions in code 26 Change to cobra casing 8-Jul-2011 22 27 23 28 24 29 java names lowcase 25 30 method Names - DONE 31-Jan-2011 26 31 var names - DONE 31-Jan-2011, corrected 10-Feb-2011 BoxField._backendName -> BoxField.{sharp,java}BackEndName 32 properties 27 33 params 28 34 events 29 35 local variables … … 42 48 <indexedT> getIndexer<T, indexedT>(T) and 43 49 setIndexer<T, indexedT>(T, indexedT) 44 50 DONE 45 51 52 codegen for props: 'propName' -> getPropName and setPropName 53 54 AutoMap map indexers '[]' to methods X.get(idx) v = X[idx] , X.set(idx,val) and X.put(idx,val) -> X[idx] = val 55 - unworkable - too many false positives 56 57 Handling of indexing '[]' on Maps and Lists 58 x[i]=v : map: x.put(i,v) list: x.set(i,v) 59 v = x[i]: map: v = map.get(i) list: v = list.get(i) 46 60 Events 47 61 - auto add boiler plate for listener (de)registration 48 62 - event firing … … 63 77 to the generating cobra code line. 64 78 - start with just spew the javac lines to output 65 79 - assemble into ErrorMessage Line and 'supporting lines associated with it - keeps error line count in sync 66 80 DONE 67 81 68 82 69 83 single file: … … 78 92 Leave jar file at root of hierarchy 79 93 80 94 81 ensure support ( as builtin alternative) for jikes compiler.82 https://sourceforge.net/projects/jikes/files/Jikes/83 84 85 95 add synonym for sharp''/sharp"" -> java''/java"" 86 or general be''/be"" (for backend)96 or general be''/be""/backend'' (for backend) 87 97 88 98 89 99 see http://www.25hoursaday.com/CsharpVsJava.html … … 95 105 In Java, the same effect is achieved by appending the string "..." to the typename of the last argument to the method. 96 106 97 107 Attributes 98 C# extend Att tribute - metainfo also ([AttributeUsage(AttributeTargets.Class)])108 C# extend Attribute - metainfo also ([AttributeUsage(AttributeTargets.Class)]) 99 109 java specify with @interface and Metainfo 100 110 e.g @Documented //we want the annotation to show up in the Javadocs 101 111 @Retention(RetentionPolicy.RUNTIME)) … … 116 126 x = xRef 117 127 // use x here 118 128 129 Or 130 in call wrap arg in a SoftRef (or make own version HardRef subclass j.l.ref.Reference) 131 Chg param to be a SoftRef to the arg passed (e.g. 'arg_Ref') 132 In the method pull it out from the softref as a local name ('arg') 133 119 134 120 Cobra backend targetting stab language (explicitly) ?? 121 backend 'stab-jvm' 135 Add new compiler directive 136 @platform portable|jvm|clr|objc 137 138 Where down the road, portable would be the default and would have its 139 own libs (which would need impls for each of the other supported 140 platforms). For now the default will be clr, obviously. 141 142 And then possibly rename -back-end to -platform. 122 143 123 124 144 Decimal Type 125 145 Initially wrap it as new type thats is a Double with an associated DecimalFormatter 126 146 (giving same precision as .Net). 127 147 Calcs are all as doubles, toString uses formatter... 128 148 still get rounding error etc... 129 149 Decimal Type internally and emit as BigDecimal, trap math ops and map 150 -> try and use BigDecimal and convert all calls (:-( 130 151 131 152 Maybe easier to just default to Integer and ignore Decimal (initially) 132 153 … … 150 171 static String[] readAllLines(String path) 151 172 static IEnumerable<of String> readLines(String path) 152 173 174 Instead use google collections/Guava 175 - support for List, Set and Map literals 176 - Simple file reading API 153 177 178 ensure support ( as builtin alternative) for jikes compiler. 179 https://sourceforge.net/projects/jikes/files/Jikes/ 180 181 Cobra backend targetting stab language (explicitly) ?? 182 backend 'stab-jvm' 183 184 185 ----------------------------------------------------------------- 186 187 = Decisions = 188 189 Look for and use java and javax in path. 190 - verify version >= 1.6 191 192 Loading external jars 193 Rely on jar or Package PkgSig files for description of Class publicly accessible contents 194 Structure so can revisit later (IKVM) if need be 195 PkgSig tool for generating pkgSig files 196 197 start: explicitly load rtl jar up front (rt.jar.sig cf mscorlib.dll) 198 - but vv big, contents mostly unused 199 -> chg to load packages separately (separate pkgsig files) 200 initial default 201 java.lang 202 java.io 203 java.util 204 java.text 205 cobra.lang 206 smaller + faster ?? 207 208 Java Source 209 Turn Cobra source file into Java Source file named per first class in file. 210 - possible issues with multiple public classes ( javac warn-and-quit) 211 -> Cobra Source file into Java Source files one for each class 212 -> place all generated java source in own (sub) dir ( ./java) 213 214 Running Generated/compiled classfiles 215 Assume compiled classfiles in same cwd as cobra source, 216 - run java specifying -cp . so java can find rest of classfiles (if >1) 217 ( java -cp '.;<otherRefs...>' AppMainClass args....) 218 -> roll all generated source into own jar file ( cf .Net exe) with autogen manifest describing main class 219 - run with classpath specifying name of jarfile 220 ( java -cp '<otherRefs...>' -jar App.jar args....) 221 222 223 Namespaces: 224 0: namespaces low cased in cobra-jvm as per java. 225 Unworkable with Cobra assumptions 226 Change to CapCase as per cobra-clr 227 translate case on jar load (in) and JavaGeneration (out) 228 229 Testing 230 Implement Test support i/fstructure 231 Add new 'require' forms so can wire tests clr or jvm 232 233 Passthrough to BackEnd 234 ensure java Native modules compile 235 -> support determination of main class/method on pure java modules 236 237 Syntax - support sharp'' as currently 238 add additional: 239 be'' or backEnd'' for any others/more, deprecate sharp'' 240 241 Indexes '[]' 242 0:autodetect from method sig 243 - Unworkable, too many false positives 244 -> Wire Maps/Lists/... - is that sufficient? 245 246 -> For default packages generate fm internal description as per fixNilable 247 may need to expose this data structure for augmentation? 248 - allow faked/added attrib placed in pkgsig file. 249 250 251 Vari params 252 Use java vari args 253 254 In and Inout parameters 255 Inline wrap and post call unwrap - Invent java RefType class 256 Use java SoftRef as Param, pack and unpack in call/callee 257 258 Decimal support 259 0: Treat default as Integer, map explicit decimal to float 260 261 262 Delegates 263 264 Events 265 wot to do 266 267 268 Exception Adaption 269 ? See if can get any clever hack working as detailed below 270 ? JavaGenerater auto wrap with try/catch exception block at place of use 271 probably unworkable for deeply embedded expressions 272 ->? make call to individual adaptor that does wrapping, 273 autogenerate the adaptor on demand 274 ( see if can cobble a genera adaptor that does wrapping and pass ref 275 to method and args to it ... Dynamic Delegate??) 276 277 ------------------------------------------------------------------------- 278 154 279 = Issues = 155 280 281 282 RTL name mangling 283 284 156 285 How support yield and conversion to enumerator/iterator? 157 286 ------------------------------------------------------------------------- 158 287 -
Source/BackEndJvm/ScanJvmType.cobra
2 2 3 3 class Compiler is partial 4 4 5 #var _didLoadJars = Set<of String>()6 7 5 var _didReadJars = Set<of String>() 8 6 9 var _jvmTypeTo Type = Dictionary<of JavaClassType, IType>()7 var _jvmTypeToIType = Dictionary<of JavaClassType, IType>() 10 8 11 9 var _jvmTypeCache = Dictionary<of String, JavaClassType>() 12 10 … … 111 109 namespaceQualNameToNameSpaceObject = Dictionary<of String, NameSpace>() 112 110 module = AssemblyModule(jSig.location, .globalNS) 113 111 saveModule, _curModule = _curModule, module 112 nestedTypes = List<of JavaClassType>() 114 113 try 115 114 _modules.add(module) 116 for type in jSig.getExportedTypes 117 if type.isNested #or type.declaringType 118 # these will be scanned by Box._scanNestedTypes 119 # print '### skipping [type.name] in [type.namespace]. isNested=[type.isNested], declaringType=[type.declaringType]' 115 for jvmType in jSig.getExportedTypes 116 if jvmType.isNested #or jvmType.declaringType 117 nestedTypes.add(jvmType) 120 118 continue 121 typeNamespace = type.package119 typeNamespace = jvmType.packageAsCobra #Capitalized 122 120 if typeNamespace.length == 0 123 121 # happens for classes etc. that are not declared in a namespace 124 122 curNameSpace = module.topNameSpace … … 133 131 assert not curNameSpace.isUnified 134 132 namespaceQualNameToNameSpaceObject[namespaceName] = curNameSpace 135 133 if verbosity >= 4 136 print ' Reading type [ type.name] in namespace "[namespaceName]"'137 jvm Type = JvmNativeType(type)138 if curNameSpace.unifiedNameSpace.declForName(jvm Type.name)139 .warning(CobraWarning('Already have declaration "[jvm Type.name]" in namespace "[curNameSpace.fullName]".'))134 print ' Reading type [jvmType.name] in namespace "[namespaceName]"' 135 jvmNative = JvmNativeType(jvmType) 136 if curNameSpace.unifiedNameSpace.declForName(jvmNative.name) 137 .warning(CobraWarning('Already have declaration "[jvmNative.name]" in namespace "[curNameSpace.fullName]".')) 140 138 else 141 if type.isClass142 if type.name.startsWith('Extend_') and type.name.count(c'_') >= 2139 if jvmType.isClass 140 if jvmType.name.startsWith('Extend_') and jvmType.name.count(c'_') >= 2 143 141 # e.g.Extend_String - TODO 144 curNameSpace.addDecl(Extension(jvm Type, .backEnd))142 curNameSpace.addDecl(Extension(jvmNative, .backEnd)) 145 143 else 146 curNameSpace.addDecl(Class(jvmType, .backEnd)) 147 else if type.isInterface 148 curNameSpace.addDecl(Interface(jvmType, .backEnd)) 149 else if type.isEnum 150 #print jvmType.name 151 curNameSpace.addDecl(EnumDecl(curNameSpace, jvmType, type.modifiers, '')) # TODO: isNames; docString? 152 else if type.isValueType 153 curNameSpace.addDecl(Struct(jvmType, .backEnd)) 144 curNameSpace.addDecl(Class(jvmNative, .backEnd)) 145 else if jvmType.isInterface 146 curNameSpace.addDecl(Interface(jvmNative, .backEnd)) 147 else if jvmType.isEnum 148 curNameSpace.addDecl(EnumDecl(curNameSpace, jvmNative, jvmType.modifiers, '')) # TODO: isNames; docString? 149 else if jvmType.isValueType 150 curNameSpace.addDecl(Struct(jvmNative, .backEnd)) 154 151 else 155 throw FallThroughException( type)152 throw FallThroughException(jvmType) 156 153 finally 154 if nestedTypes.count 155 _setNestedTypes(nestedTypes)# store nestedTypes in parenting type. 157 156 _curModule = saveModule 158 157 158 def _setNestedTypes(nestedTypes as List<of JavaClassType>) 159 for nt in nestedTypes 160 enclType = nt.declaringType 161 if enclType 162 # Hack below suppressing adding nested classes in java.lang Character. (or any Primitive) 163 # boxes.baseBind on primitives with nested classes dies due call fm bindh 164 # and memberName lookup needs .didBindInt - doesnt happen in CLR. (FIXME) 165 if enclType.canonicalName <> 'java.lang.Character' 166 enclType.addNestedType(nt) 167 #if enclType.isInterface, print 'EnclINTERFACE [enclType.canonicalName] [nt.name]' 168 else 169 if .verbosity >= 3, print 'NO class found for enclosing class of nested class [nt.canonicalName]' 170 # just ignore/drop any nested class cant find parent for 171 172 159 173 def jvmFixNilableMemberSigs 174 # fix the listed members below to be non Nilable 175 # called from bindInterface phase so this can only refer to top level Classes in a package. 160 176 # TODO: this really needs to go in a separate file that the compiler reads each time 161 177 162 178 # fix up member sigs regarding methods returning nilable values 163 179 # hard coded below. TODO: read from a Cobra config file 164 180 # _fix is defined in ScanClrType 165 181 166 # These are just reflected over from the .Net ones since I dont know what the basis for inclusion is/was182 # Included by comparison from .Net ones and examination of javaDoc - INCOMPLETE 167 183 168 _fix(' java.lang.Object', 'toString getClass clone')184 _fix('Java.Lang.Object', 'toString getClass clone') 169 185 # ^ regarding .toString, not technically true, but common enough and life is too painful when the return type is nilable 170 186 #_fix('java.lang.System', 'out') #stdout 171 _fix(' java.lang.String', 'padLeft padRight remove replace substring toLower toUpper trim')187 _fix('Java.Lang.String', 'concat remove replace replaceAll replaceFirst substring toLowerCase toUpperCase trim format') 172 188 #_fix('System.Type', 'assembly name toString') 173 189 # namespace can return nil if the Type is a generic parameter 174 190 #_fix('System.Environment', 'commandLine currentDirectory newLine version') 175 _fix('java.lang.Exception', 'message') 191 _fix('Java.Lang.Exception', 'message') 192 #_fix('java.util.Enumeration<of>', r'getNext') 193 _fix('Java.Lang.Iterable<of>', r'iterator') 194 _fix('Java.Util.Iterator<of>', r'next') 195 _fix('Java.Util.ListIterator<of>', r'next previous') 196 _fix('Java.Util.Collection<of>', r'toArray') 176 197 #_fix('System.Collections.Generic.IEnumerable<of>', r'getEnumerator') 177 #_fix('java.util.Enumeration<of>', r'getNext') 178 _fix('java.util.Iterator<of>', r'next') 179 _fix('java.util.ListIterator<of>', r'next previous') 180 _fix('java.util.Collection<of>', r'toArray') 181 198 199 # work out what doing with indexor and apply to [] 182 200 #_fix('System.Collections.Generic.List<of>', r'[]') 183 _fix(' java.util.List<of>', r'[] get set remove')184 _fix(' java.util.AbstractList<of>', r'[] get set remove')185 _fix(' java.util.AbstractSequentialList<of>', r'[] get set remove')186 _fix(' java.util.ArrayList<of>', r'[] get set remove')187 #_fix(' java.util.CopyOnWriteArrayList<of>', r'[] get set remove')188 #_fix(' java.util.LinkedList<of>', r'[] get set remove element getFirst getLast peek peekFirst peekLast poll pollFirst pollLast pop removeFirst removeLast')189 #_fix(' java.util.Vector<of>', r'[] get set elementAt firstElement lastElement remove')190 #_fix(' java.util.Stack<of>', r'[] peek pop push')201 _fix('Java.Util.List<of>', r'[] get set remove') 202 _fix('Java.Util.AbstractList<of>', r'[] get set remove') 203 _fix('Java.Util.AbstractSequentialList<of>', r'[] get set remove') 204 _fix('Java.Util.ArrayList<of>', r'[] get set remove') 205 #_fix('Java.Util.CopyOnWriteArrayList<of>', r'[] get set remove') 206 #_fix('Java.Util.LinkedList<of>', r'[] get set remove element getFirst getLast peek peekFirst peekLast poll pollFirst pollLast pop removeFirst removeLast') 207 #_fix('Java.Util.Vector<of>', r'[] get set elementAt firstElement lastElement remove') 208 #_fix('Java.Util.Stack<of>', r'[] peek pop push') 191 209 192 210 #_fix('System.Collections.Generic.IDictionary<of,>', r'[] keys values') 193 _fix(' java.util.Map<of,>', r'[] get')211 _fix('Java.Util.Map<of,>', r'[] get') 194 212 # _fix('System.Collections.Generic.Dictionary<of,>', r'[]') 195 _fix('java.util.AbstractMap<of,>', r'[] get') 196 _fix('java.util.HashMap<of,>', r'[] get') 197 #_fix('java.util.ConcurrentHashMap<of,>', r'[] get') 198 #_fix('java.util.ConcurrentSkipListHashMap<of,>', r'[] get') 199 #_fix('java.util.EnumMap<of,>', r'[] get') 200 #_fix('java.util.IdentityHash<of,>', r'[] get') 201 #_fix('java.util.TreeMap<of,>', r'[] get') 202 #_fix('java.util.WeakHashMap<of,>', r'[] get') 203 _fix('java.util.Map.Entry<of,>', r'getKey getValue') 204 #_fix('java.util.AbstractMap.SimpleEntry<of,>', r'getKey getValue') 205 #_fix('java.util.AbstractMap.SimpleImmutableEntry<of,>', r'getKey getValue') 213 _fix('Java.Util.AbstractMap<of,>', r'[] get') 214 _fix('Java.Util.HashMap<of,>', r'[] get') 215 #_fix('Java.Util.ConcurrentHashMap<of,>', r'[] get') 216 #_fix('Java.Util.ConcurrentSkipListHashMap<of,>', r'[] get') 217 #_fix('Java.Util.EnumMap<of,>', r'[] get') 218 #_fix('Java.Util.IdentityHash<of,>', r'[] get') 219 #_fix('Java.Util.TreeMap<of,>', r'[] get') 220 #_fix('Java.Util.WeakHashMap<of,>', r'[] get') 221 _fix('Java.Util.Map.Entry<of,>', r'getKey getValue') 222 #_fix('Java.Util.AbstractMap.SimpleEntry<of,>', r'getKey getValue') 223 #_fix('Java.Util.AbstractMap.SimpleImmutableEntry<of,>', r'getKey getValue') 224 #_fix('Java.Util.Properties', r'getProperty') 206 225 207 226 #_fix('System.IO.File', 'create createText open openRead openText openWrite readAllBytes readAllLines readAllText') 208 #_fix('java.io.File', 'create createText open openRead openText openWrite readAllBytes readAllLines readAllText') 227 _fix('Java.Io.File', 'create createText open openRead openText openWrite readAllBytes readAllLines readAllText getPath getAbsolutePath') 228 ##_fixFields('Java.Io.File', 'pathSeparator separator pathSeparatorChar seperatorChar') # TODO 209 229 #_fix('System.IO.FileSystemInfo', 'name fullName') 210 230 #_fix('System.IO.TextWriter', 'newLine') 211 231 #_fix('System.IO.Path', 'combine getFullPath') 212 232 # combine = File(strA, strB).getPath(), getFullPath = File().getAbsolutePath() 213 233 #_fix('java.lang.StringBuilder', 'toString') # ?? 214 _fix('java.lang.Text.RegularExpressions.Regex', 'match replace') 215 _fix('System.Diagnostics.Process', 'processName') 234 #_fix('java.lang.Text.RegularExpressions.Regex', 'match replace') 235 #_fix('System.Diagnostics.Process', 'processName') 236 _fix('java.util.regex.Pattern', 'matches matcher pattern split compile') 237 _fix('java.util.regex.Matcher', 'group pattern replaceAll replaceFirst') 238 _fix('java.lang.ProcessBuilder', 'command start directory') 239 #_fix('java.lang.Process', 'getInputStream getOutputStream getErrorStream') 216 240 217 _fix('System.Reflection.Assembly', 'getEntryAssembly getExecutingAssembly location')218 _fix('System.Reflection.MemberInfo', 'name')219 _fix('System.Reflection.FieldInfo', 'fieldType')220 _fix('System.Reflection.ParameterInfo', 'parameterType')221 _fix('System.Reflection.PropertyInfo', 'propertyType')241 #_fix('System.Reflection.Assembly', 'getEntryAssembly getExecutingAssembly location') 242 #_fix('System.Reflection.MemberInfo', 'name') 243 #_fix('System.Reflection.FieldInfo', 'fieldType') 244 #_fix('System.Reflection.ParameterInfo', 'parameterType') 245 #_fix('System.Reflection.PropertyInfo', 'propertyType') 222 246 223 # TODO: shouldn't need the following. see comment in _fixSubs224 #_fix('System.IO.StringWriter', 'toString')225 226 227 247 228 248 # 229 249 # Jvm Type Cache … … 233 253 Returns the Cobra type for a Java type if the Java type was previously scanned. 234 254 i.e this is access to the Java Type/Class cache. 235 255 """ 236 return if(_jvmTypeTo Type.containsKey(jvmType), _jvmTypeToType[jvmType], nil)256 return if(_jvmTypeToIType.containsKey(jvmType), _jvmTypeToIType[jvmType], nil) 237 257 238 258 def addTypeForJvmType(type as IType, jvmType as JavaClassType) 239 259 require .typeForJvmType(jvmType) in [nil, type] 240 _jvmTypeTo Type[jvmType] = type260 _jvmTypeToIType[jvmType] = type 241 261 242 262 def jvmTypeByName(qualifiedName as String) as JavaClassType 243 263 """ 244 Obtain the Jvm Type given by the fully qualified (cobra) name.264 Obtain the Jvm Type (JavaClassType) given by the fully qualified (cobra) name. 245 265 """ 246 266 t as JavaClassType? 247 267 _jvmTypeCache.tryGetValue(qualifiedName, out t) 248 268 if t is nil 249 # TODO -lookup the JavaClassType by name.250 t = JarSig. classByNameCache[qualifiedName]269 # lookup the JavaClassType by name. 270 t = JarSig.lookupClassByCobraName(qualifiedName) 251 271 _jvmTypeCache[qualifiedName] = t to passthrough # "to passthrough" instead of "to !" to avoid non-nil check 252 272 return t to passthrough 253 273 254 274 255 275 def installJvmNativeMethods(box as Box, nativeType as NativeType) 256 print '++ TODO scanJvmType.installJvmNativeMethods' 276 """Install entries for native static methods on box instances.""" 277 pass 278 #print '++ TODO scanJvmType.installJvmNativeMethods' 257 279 /# 258 280 meths = List<of Method>() 259 281 _installClrNativeMethodsFrom('System', nativeType, nativeType, box, meths) … … 297 319 return (.nativeType to JvmNativeType).backEndType 298 320 299 321 def isJvmSystemExceptionClass as bool 300 return .name == 'Exception' and .parentNameSpace and .parentNameSpace.fullName == ' java.lang'322 return .name == 'Exception' and .parentNameSpace and .parentNameSpace.fullName == 'Java.Lang' 301 323 302 def _scanNativeTypeJvm 324 def prepSystemObjectClassJvm 325 # TODO chk thats this has desired result. 326 # map method getType to java getClass 327 # C#'s typeof(X) is X.getType in Cobra. 328 #existing = .declForName('getClass') to BoxMember 329 #overload = MemberOverload(existing) 330 #.registerOverload(overload) 331 meth = Method(TokenFix.empty, TokenFix.empty, this, 'getType', List<of Param>(), .compiler.typeTypeProxy, nil, ['shared'], AttributeList(), 'Returns the Type instance that defines this type.') 332 meth.sharedMethodBacking = 'getClass' 333 #meth.sharedMethodBackingIsAlias = true # not static 334 #overload.addMember(meth) 335 .addDecl(meth) 336 337 def scanNativeTypeJvm 303 338 """ 304 339 Subclasses should invoke base and then invoke the various _scanXXX methods that are appropriate for them. 305 340 """ … … 307 342 _needScanNativeType = false 308 343 # print '<> _scanNativeType for [.name] in [_parentNameSpace.fullName], class is [.getType.name]' 309 344 310 def _scanGenericArgsJvm 345 def scanGenericArgsJvm 346 #print 'scanGenericArgsJvm [.name] [_jvmType.isGenericType]' 311 347 if _jvmType.isGenericType 312 348 for genArg in _jvmType.getGenericArguments 313 349 t = (.compiler to Compiler).typeForJvmType(genArg) … … 315 351 t = GenericParam(JvmNativeType(genArg), parentDefinition=this) 316 352 (.compiler to Compiler).addTypeForJvmType(t to !, genArg) 317 353 _genericParams.add(t) 354 #print 'scanGenericArgsJvm', .nameWithGenericParams # _genericParams 318 355 319 def _prepSystemObjectClassJvm320 # map method getType to java getClass321 # C#'s typeof(X) is X.getType in Cobra.322 #existing = .declForName('getClass') to BoxMember323 #overload = MemberOverload(existing)324 #.registerOverload(overload)325 meth = Method(TokenFix.empty, TokenFix.empty, this, 'getType', List<of Param>(), .compiler.typeTypeProxy, nil, ['shared'], AttributeList(), 'Returns the Type instance that defines this type.')326 meth.sharedMethodBacking = 'getClass'327 #meth.sharedMethodBackingIsAlias = true # not static328 #overload.addMember(meth)329 .addDecl(meth)330 331 356 def _scanJvmIsNames 332 357 # TODO 333 358 _isNames.add('extern') # to make the box like the ones that were in SystemInterfaces.cobra … … 337 362 if not _badJvmRelatedType(interf) 338 363 _baseInterfaceProxies.add(JvmTypeProxy(interf)) 339 364 340 /#341 365 def _scanJvmNestedTypes 342 # TODO: enable and fix resulting bugs343 # for type in .clrType.getNestedTypes(BindingFlags(Instance, Static, DeclaredOnly, Public, NonPublic))344 366 for type in _jvmType.getNestedTypes 345 _scanJvmNestedType(type) 346 #for type in _clrType.getNestedTypes(BindingFlags(Static, DeclaredOnly, NonPublic)) 347 for type in _jvmType.getNestedTypes 348 if type.isEnum and not type.isPublic 349 _scanJvmNestedType(type) 367 assert type.isNested 368 nativeType = JvmNativeType(type) 369 nativeType.nestedName = nativeType.name.after('$') 370 if type.isClass 371 .addDecl(Class(nativeType, .compiler.backEnd)) 372 else if type.isInterface 373 .addDecl(Interface(nativeType, .compiler.backEnd)) 374 else if type.isEnum 375 .addDecl(EnumDecl(this, nativeType)) 376 else 377 throw FallThroughException(type) 378 if .declsInOrder.count 379 lastDecl = .declsInOrder[.declsInOrder.count-1] to dynamic 380 if (lastDecl to Object).getType.getProperty('ParentBox') # CC: if lastDecl responds to (get parentBox as Box?) 381 lastDecl.parentBox = this 350 382 351 def _scanJvmNestedType(type as JavaClassType)352 nativeType = JvmNativeType(type)353 if type.isClass354 .addDecl(Class(nativeType, .compiler.backEnd))355 else if type.isInterface356 .addDecl(Interface(nativeType, .compiler.backEnd))357 else if type.isEnum358 isNames = List<of String>()359 docString =''360 .addDecl(EnumDecl(this, nativeType, isNames, docString)) # TODO: isNames; docString?361 #else if type.isValueType362 # .addDecl(Struct(clrType, .compiler.backEnd))363 #else if type.isAnsiClass364 # # The Enum class is an example that returns false for .isClass but true for .isAnsiClass365 # .addDecl(Class(clrType, .compiler.backEnd))366 else367 throw FallThroughException(type)368 lastDecl = .declsInOrder[.declsInOrder.count-1] to dynamic369 if (lastDecl to Object).getType.getProperty('ParentBox') # CC: if lastDecl responds to (get parentBox as Box?)370 lastDecl.parentBox = this371 372 #/373 383 374 384 def _scanJvmFields 375 385 for fieldInfo in _jvmType.getFields … … 462 472 if propInfo.isWritable 463 473 prop.makeSetPart(TokenFix.empty) 464 474 if _declsByName.containsKey(prop.name) # for # Double.naN 465 print 'DUP name already exists already for property [prop.name]', _declsByName[prop.name], prop466 return # just drop the property , field ormethod still available475 print 'DUP name exists already for property "[prop.name]" on', /#_declsByName[prop.name],#/ .name 476 return # just drop the property; field or method still available 467 477 .addDecl(prop) 468 478 469 479 … … 493 503 .registerOverload(overload to !) 494 504 else 495 505 throw FallThroughException([this, indexer, other]) 506 #print 'Dbg: add IDXR [_jvmType.name][indexer.name] [propInfo.name]' 496 507 if overload 497 508 overload.addMember(indexer) 498 509 else … … 601 612 """ 602 613 if t is nil 603 614 return false 604 605 615 if t.isNested and not (t.isPublic or t.isProtected)and not t.isGenericParameter # TODO: need the generic param check? 606 616 print 'Type t.name is nested and not public,protected' 607 617 return true 608 609 # FYI: MS .NET 2.0 (but not Mono 1.2.6) will return true for .isNotPublic for types are "by ref"610 618 #if t.isByRef # TODO: or t.isArray 611 619 # return _badJvmRelatedType(t.getElementType) 612 613 620 return false 614 621 615 622 def _jvmMemberTypeProxy(jvmType as JavaClassType?) as ITypeProxy … … 646 653 notNull = member.isNonNullable 647 654 t = JvmTypeProxy(jvmType) to ITypeProxy 648 655 return if(notNull, t, NilableTypeProxy(t)) 656 657 # Can only do these after bindImplementation phase. Nested classes 658 #_fix('java.util.Map<of,>.Entry<of,>', r'getKey getValue') 659 #_fix('java.util.AbstractMap.SimpleEntry<of,>', r'getKey getValue') 660 #_fix('java.util.AbstractMap.SimpleImmutableEntry<of,>', r'getKey getValue') 661 662 def _fixNestedNilables 663 if .parentBox # nested 664 print 'fixNest', .parentBox.name, .name 665 649 666 650 651 667 class Class 652 668 is partial 653 669 654 def _scanNativeTypeJvm655 base. _scanNativeTypeJvm656 print 'scanJvmNativeType ', .name670 def scanNativeTypeJvm 671 base.scanNativeTypeJvm 672 #print 'scanJvmNativeType ', .name 657 673 _scanJvmIsNames 658 674 _scanJvmImplements 659 #_scanJvmNestedTypes675 _scanJvmNestedTypes 660 676 _scanJvmFields 661 677 _scanJvmInitializers 662 678 _scanJvmMethods … … 664 680 ##_scanJvmEvents TODO 665 681 # TODO: _scanJvmEnums 666 682 # TODO: scan all other nested types 683 _fixNestedNilables 667 684 685 668 686 669 687 class Interface 670 688 is partial 671 689 672 def _scanNativeTypeJvm673 base. _scanNativeTypeJvm690 def scanNativeTypeJvm 691 base.scanNativeTypeJvm 674 692 _scanJvmIsNames 675 693 _scanJvmImplements 676 #_scanJvmNestedTypes694 _scanJvmNestedTypes 677 695 _scanJvmFields 678 696 _scanJvmMethods 679 697 _scanJvmProperties 680 698 #_scanJvmEvents #TODO 699 _fixNestedNilables 681 700 682 701 683 702 class Struct 684 703 is partial 685 704 686 def _scanNativeTypeJvm687 base. _scanNativeTypeJvm705 def scanNativeTypeJvm 706 base.scanNativeTypeJvm 688 707 _scanJvmIsNames 689 708 _scanJvmImplements 690 #_scanJvmNestedTypes709 _scanJvmNestedTypes 691 710 _scanJvmFields 692 711 _scanJvmInitializers 693 712 _scanJvmMethods … … 698 717 class Extension 699 718 is partial 700 719 701 def _scanNativeTypeJvm720 def scanNativeTypeJvm 702 721 # this only for Cobra specific extensions. Example: class Extend_String_1939 703 base. _scanNativeTypeJvm722 base.scanNativeTypeJvm 704 723 _scanJvmIsNames 705 724 #_scanJvmImplements 706 725 #_scanJvmNestedTypes … … 727 746 class EnumDecl 728 747 is partial 729 748 730 def _setUnderlyingTypeJvm749 def setUnderlyingTypeJvm 731 750 pass 732 751 733 def _scanNativeTypeJvm752 def scanNativeTypeJvm 734 753 # TODO: read attribs 735 754 _needScanNativeType = false 736 755 _storageType = .compiler.anyIntType # tmp ?? -
Source/BackEndJvm/JvmBackEnd.cobra
10 10 base.init(compiler) 11 11 _name = 'java-jvm' 12 12 _rtlName = 'CobraLang.jar' 13 _rtlSrcFile = 'CobraImp.java' # backEnd source file containing native code support for Cobra.Lang 14 13 15 14 16 _tagToTypeName = { 15 'Object': ' java.lang.Object',16 'Type' : ' java.lang.Class<of>', # java.lang.Type is a marker interface17 'String' : ' java.lang.String',18 'Exception' : ' java.lang.RuntimeException',17 'Object': 'Java.Lang.Object', 18 'Type' : 'Java.Lang.Class<of>', # java.lang.Type is a marker interface 19 'String' : 'Java.Lang.String', 20 'Exception' : 'Java.Lang.RuntimeException', 19 21 20 22 'Delegate' : 'System.Delegate', #cobra.lang.Delegate 21 'Attribute' : 'java.lang.annotation.Annotation', 22 #'ICloneable': 'System.ICloneable', #cobra.lang.ICloneable 23 'IEnumerable': 'java.lang.Iterable', 24 'IEnumerator': 'java.lang.Iterator', 25 'IEnumerable<of>' : 'java.lang.Iterable<of>', 26 'IEnumerator<of>' : 'java.lang.Iterator<of>', 27 'IDictionaryEnumerator' : 'System.Collections.IDictionaryEnumerator', 28 'ICollection': 'java.util.Collection<of Object>', # non generic collection interface 29 'ICollection<of>': 'java.util.Collection<of>', 30 'IList' : 'java.util.List<of Object>', # non generic List interface 31 'IList<of>' : 'java.util.List<of>', 32 'List<of>': 'java.util.ArrayList<of>', 33 'IDictionary': 'java.util.Map<of Object,Object>', # Non Generic Map/Dict interface 34 'IDictionary<of,>': 'java.util.Map<of,>', 35 'Dictionary<of,>' : 'java.util.HashMap<of,>', 36 'Set<of>': 'java.lang.HashSet<of>', 23 'Attribute' : 'Java.Lang.Annotation.Annotation', 24 'ICloneable': 'Java.Lang.Cloneable', 25 'IEnumerable': 'Java.Lang.Iterable', 26 'IEnumerator': 'Java.Lang.Iterator', 27 'IEnumerable<of>' : 'Java.Lang.Iterable<of>', 28 'IEnumerator<of>' : 'Java.Lang.Iterator<of>', 29 'IDictionaryEnumerator' : 'Java.Lang.Iterator', 30 #'IDictionaryEnumerator' : 'System.Collections.IDictionaryEnumerator', 31 'ICollection': 'Java.Util.Collection<of Object>', # non generic collection interface 32 'ICollection<of>': 'Java.Util.Collection<of>', 33 'IList' : 'Java.Util.List<of Object>', # non generic List interface 34 'IList<of>' : 'Java.Util.List<of>', 35 'List<of>': 'Java.Util.ArrayList<of>', 36 'IDictionary': 'Java.Util.Map<of Object,Object>', # Non Generic Map/Dict interface 37 'IDictionary<of,>': 'Java.Util.Map<of,>', 38 'Dictionary<of,>' : 'Java.Util.HashMap<of,>', 39 'Set<of>': 'Java.Lang.HashSet<of>', 37 40 38 'bool' : ' java.lang.Boolean', # boolean39 'char' : ' java.lang.Character',# char40 'decimal': ' java.lang.Double', # ??41 'single': 'java.lang.Float', # float42 'double': 'java.lang.Double', # double43 'sbyte' : 'java.lang.Byte', # byte44 'int16' : 'java.lang.Short', # short45 'int32' : 'java.lang.Integer', # int46 'int64' : 'java.lang.Long', # long47 'byte' : 'java.lang.Short', # short # rest are unsigned - use next widest48 'uint16': 'java.lang.Integer', # int49 'uint32': 'java.lang.Long', # long50 'uint64': 'java.lang.Long', # long41 'bool' : 'Java.Lang.Boolean', # boolean 42 'char' : 'Java.Lang.Character',# char 43 'decimal': 'Java.Lang.Double', # ?? 44 'single': 'Java.Lang.Float', # float 45 'double': 'Java.Lang.Double', # double 46 'sbyte' : 'Java.Lang.Byte', # byte 47 'int16' : 'Java.Lang.Short', # short 48 'int32' : 'Java.Lang.Integer', # int 49 'int64' : 'Java.Lang.Long', # long 50 'byte' : 'Java.Lang.Short', # short # rest are unsigned - use next widest 51 'uint16': 'Java.Lang.Integer', # int 52 'uint32': 'Java.Lang.Long', # long 53 'uint64': 'Java.Lang.Long', # long 51 54 52 55 } 53 56 … … 58 61 phases.add(GenerateJavaCodePhase(.compiler)) 59 62 phases.add(CompileJavaCodePhase(.compiler)) 60 63 64 def getRecommendedBuiltInType(parentNameSpace as NameSpace?, name as String) as String? is override 65 n = nil to String? 66 if parentNameSpace and parentNameSpace.fullName == 'Java.Lang' 67 branch name 68 on 'Boolean', n = 'bool' 69 #on 'SByte', n = 'int8' 70 on 'Byte', n = 'uint8' 71 on 'Short', n = 'int16' 72 #on 'UInt16', n = 'uint16' 73 on 'Integer', n = 'int32' 74 #on 'UInt32', n = 'uint32' 75 on 'Long', n = 'int64' 76 on 'UInt64', n = 'uint64' 77 on 'Character', n = 'char' 78 on 'Float', n = 'float32' 79 on 'Double', n = 'float' 80 on 'BigDecimal', n = 'decimal' 81 return n 82 61 83 def computeOutName as String is override 62 84 return .compiler.computeOutNameJava 63 85 … … 87 109 def setDefaultUseDirectives(ns as NameSpace) is override 88 110 # java packages available by default 89 111 useToken = Token('(implicit)', 1, 1, 1, 'USE', 'use', nil) 90 # java uses lowercase for package names - Should Cobra stay capitalised and we remap it ??91 ns.addUseDirective(UseDirective(useToken, [' java', 'lang']))112 # java uses lowercase for package names - Cobra stay capitalised and we remap it 113 ns.addUseDirective(UseDirective(useToken, ['Java', 'Lang'])) 92 114 #ns.addUseDirective(UseDirective(useToken, ['System', 'Collections', 'Generic'])) # generics built in 93 ns.addUseDirective(UseDirective(useToken, [' java', 'io']))94 ns.addUseDirective(UseDirective(useToken, [' java', 'util']))95 ns.addUseDirective(UseDirective(useToken, [' java', 'text']))96 ns.addUseDirective(UseDirective(useToken, [' cobra', 'lang']))115 ns.addUseDirective(UseDirective(useToken, ['Java', 'Io'])) 116 ns.addUseDirective(UseDirective(useToken, ['Java', 'Util'])) 117 ns.addUseDirective(UseDirective(useToken, ['Java', 'Text'])) 118 ns.addUseDirective(UseDirective(useToken, ['Cobra', 'Lang'])) 97 119 98 120 def fixLibExtension(libRef as String) as String is override 99 121 """ … … 120 142 return .compiler.jvmLoadReference(reference) # in ScanJvmType 121 143 122 144 def readSystemTypes is override 123 #pass # TODO124 145 # Initially we will rely on a external java tool to have been run to produce a precis 125 146 # file in a known place (same as cobra compiler perhaps) containing exported types for 126 147 # items in a jar file. 127 148 128 # JarSig is a holder for jarfile extended with info on contained classes.149 # JarSig is a holder for a jarfile or package extended with info on contained classes. 129 150 # javaReadJar loads info on contained classes into Cobra 130 151 # rt.jar is only one we need 131 152 .compiler.javaReadJar(JarSig('rt.jar')) 132 153 133 154 def fixNilableMemberSigs is override 134 #.compiler.javafixNilableMemberSigs 135 print '++ TODO jvmBackEnd.fixNilableMemberSigs' 155 #.compiler.jvmfixNilableMemberSigs 136 156 pass # TODO 137 157 138 158 def installNativeMethods(box as Box, nativeType as NativeType) is override 139 159 #.compiler.installJvmNativeMethods(box, nativeType) 140 print '++ TODO jvmBackEnd.installNativeMethods'141 160 pass # TODO 142 161 143 162 def cobraNameForNativeBoxName(nativeBoxName as String) as String is override … … 147 166 get objectTypeProxy as AbstractTypeProxy is override 148 167 """Type proxy for BE root of Object hierarchy.""" 149 168 if not _objectTypeProxy 150 _objectTypeProxy = JvmTypeProxy(JarSig. classByNameCache['java.lang.Object'])169 _objectTypeProxy = JvmTypeProxy(JarSig.lookupClassByCobraName('Java.Lang.Object')) 151 170 return _objectTypeProxy to ! 152 171 153 172 get typeTypeProxy as AbstractTypeProxy is override 154 173 """Type proxy for BE notion of a class describing a Type.""" 155 174 if not _typeTypeProxy 156 _typeTypeProxy = JvmTypeProxy(JarSig. classByNameCache['java.lang.Class'])175 _typeTypeProxy = JvmTypeProxy(JarSig.lookupClassByCobraName('Java.Lang.Class')) 157 176 return _typeTypeProxy to ! 158 177 159 178 def nativeTypeProxy(type as NativeType) as NativeTypeProxy is override … … 170 189 /# 171 190 These are the type tags used directly by the compiler code. 172 191 173 bool 'Java. lang.Boolean'174 char ' java.lang.Char'192 bool 'Java.Lang.Boolean' 193 char 'Java.Lang.Char' 175 194 decimal '??System.Decimal' 176 decimal ' java.lang.Float'177 single ' java.lang.Float'178 double ' java.lang.Double'179 sbyte ' java.lang.Byte'180 int16 ' java.lang.Short'181 int32 ' java.lang.Int'182 int64 ' java.lang.Long'195 decimal 'Java.Lang.Float' 196 single 'Java.Lang.Float' 197 double 'Java.Lang.Double' 198 sbyte 'Java.Lang.Byte' 199 int16 'Java.Lang.Short' 200 int32 'Java.Lang.Integer' 201 int64 'Java.Lang.Long' 183 202 # java not have unsigned types (:-( use next largest signed Type 184 byte ' java.lang.Short' #& 0x7f185 uint16 ' java.lang.Int'186 uint32 ' java.lang.Long'187 uint64 ' java.lang.Long'203 byte 'Java.Lang.Short' #& 0x7f 204 uint16 'Java.Lang.Integer' 205 uint32 'Java.Lang.Long' 206 uint64 'Java.Lang.Long' 188 207 #/ 189 208 190 def addArrayInterfaces(interfaces as List<of ITypeProxy>) is override 191 pass 192 #iclone = .compiler.libraryType('ICloneable') # ICloneable not supported 193 #interfaces.insert(0, iclone to ITypeProxy) 209 def determineExtnNativeType(extn as Extension, nativeType as NativeType) as NativeType is override 210 return extn.jvmExtnNativeType(nativeType) # ScanJvmType 211 212 def handleNameSpaceNameCollision(ns as NameSpace, token as IToken, name as String) as NameSpace is override 213 """ 214 Java separates Namespaces and other symbols - Cobra architecture 215 (based on Clr) doesnt easily so currently we'll rename and warn that 216 use of the namespace needs to be changed in user code (:-). 217 """ 218 #print 'In [ns.name] there is already a non-namespace declaration named "[name]".' 219 #print 'Cobra doesnt allow this - a declaration must be either a Namespace or a Type' 220 #print 'so the namespace "[name]" is renamed within Cobra to be "[name]NS".' 221 #print 'Any use of the namespace in cobra code must be changed accordingly.' 222 223 #print 'Cobra name collision in namespace "[ns.name]" for child namespace "[name]" and an existing declaration. Use name "[name]NS" for java namespace/package "[name]" .' 224 print 'In namespace "[ns.name]" java namespace "[name]" renamed in cobra to "[name]NS". (cobra name collision)' 225 name = name+'NS' 226 return ns.getOrMakeNameSpaceNamed(token, name) # recursive 194 227 228 def prepSystemObjectClass(box as Box) is override 229 box.prepSystemObjectClassJvm 195 230 231 def scanGenericArgs(box as Box) is override 232 box.scanGenericArgsJvm 196 233 234 def scanNativeType(box as Box) is override 235 """ Do scan/Load of Types from a dll """ 236 box.scanNativeTypeJvm 237 238 def scanNativeType(edcl as EnumDecl) is override 239 edcl.scanNativeTypeJvm 240 241 def setUnderlyingType(edcl as EnumDecl) is override 242 edcl.setUnderlyingTypeJvm 243 197 244 class GenerateJavaCodePhase inherits Phase 198 245 199 246 cue init(c as Compiler) -
Source/BackEndJvm/JavaCompilationMessage.cobra
11 11 assert msg.lineNum == 30 12 12 13 13 def willSkipMessage(msg as String) as bool is shared 14 #return not '.java:' in msg15 return false14 return not '.java:' in msg 15 #return false 16 16 17 17 var _fileName as String? 18 18 var _lineNum as int? … … 30 30 i += '.java:'.length 31 31 j = line.indexOf(':', i) 32 32 lineStr = line[i:j] 33 try 34 _lineNum = int.parse(lineStr) 35 catch 36 pass 37 success 38 _lineNum = compiler.cobraLineNumForCurly(.fileName, _lineNum to !) 39 if compiler.verbosity or Utils.isDevMachine, line += ' (javac)' 33 _storeLineNum(lineStr, compiler) 34 if compiler.verbosity or Utils.isDevMachine, line += ' (javac)' 40 35 _message = _cleanUp(line) 41 36 37 def append(line as String, compiler as Compiler) 38 line = line.trim 39 _message += '\n >: ' + line 40 if System.Text.RegularExpressions.Regex.isMatch(line, r'// \d+\s*$') 41 lidx = line.lastIndexOf('//') 42 if lidx > 0 43 lidx += 3 # after '// ' 44 lineStr = line[lidx:] 45 _storeLineNum(lineStr, compiler) 46 47 def _storeLineNum(lineStr as String, compiler as Compiler) 48 try 49 _lineNum = int.parse(lineStr) 50 catch 51 pass 52 success 53 _lineNum = compiler.cobraLineNumForCurly(.fileName, _lineNum to !) 54 42 55 def _cleanUp(line as String) as String 43 56 line = line.replace("`double'", "`float'") 44 57 line = line.replace("null", "nil") -
Source/BackEndJvm/JavaGenerator.cobra
34 34 def writeJava 35 35 Node.setCompiler(this) 36 36 try 37 pass37 #pass 38 38 _moduleFileName_to_curlyToCobraLineNum = Dictionary<of String, Dictionary<of int, int>>() 39 39 for _curModule in _modules 40 40 if not _curModule.fileName.endsWith('SystemInterfaces.cobra') … … 175 175 return output 176 176 177 177 def _parseJavaCompilerOutput(output as String) 178 jcm as JavaCompilationMessage? = nil 178 179 for line in output.split(c'\n') 179 180 line = line.trim 180 181 if not line.length, continue 181 182 if JavaCompilationMessage.willSkipMessage(line) 183 if jcm, jcm.append(line, this) 182 184 continue 183 185 else 184 186 if _verbosity >= 3 185 187 print 'javac message: [line]' 186 _addMessage(JavaCompilationMessage(line, this)) 188 jcm = JavaCompilationMessage(line, this) 189 _addMessage(jcm to !) 187 190 188 191 189 192 def _getFixedMainType as String … … 501 504 502 505 class UseDirective is partial 503 506 507 # Dont use java imports as 508 # -- The semantics between Cobra `use` and java `import` are (probably) different. 509 # -- Using Cobra.Lang library type names without qualification in the generated code could lead to confusing errors if the user happens to have a type with the same name. 510 # instead names from 'used' packages/namespaces will be fully qualified in generated java source. 511 512 # def writeJavaDef(sw as CurlyWriter) is override 513 # sw.write('import [.boundNameSpace.javaRef].*;\n') 504 514 pass 505 515 506 516 … … 617 627 class IntType is partial 618 628 619 629 get javaName as String is override 630 # should name to primitives but not prob fm JvmJarSig._aliasPrimitives 631 # TODO fix primitives int, long,... vs classes java.lang.Integer, java.lang.Long 620 632 #return _nativeType.fullName 621 return 'int' # java.lang.Integer 633 t = _nativeType.fullName 634 branch t 635 on 'java.lang.Byte', primName = 'byte' 636 on 'java.lang.Short', primName = 'short' 637 on 'java.lang.Integer', primName = 'int' 638 on 'long', primName = _nativeType.fullName 639 on 'java.lang.Long', primName = 'long' 640 else 641 throw FallThroughException() 642 return primName 622 643 # TODO byte = int8 , short = int16, int = Int32, long = int64 623 644 624 645 class NilableType is partial … … 751 772 sb.append(param.javaRef) 752 773 sep = ', ' 753 774 sb.append('>') 754 xjava= sb.toString775 javaRef = sb.toString 755 776 else 756 xjava= .javaName777 javaRef = .javaName 757 778 if .parentNameSpace and not .parentNameSpace.isRoot 758 779 #trace .parentNameSpace.javaQualifier 759 xjava = .parentNameSpace.javaQualifier + xjava780 javaRef = .parentNameSpace.javaQualifier + javaRef 760 781 else if .parentBox 761 782 trace .parentBox.javaRef 762 xjava = .parentBox.javaRef + '.' + xjava783 javaRef = .parentBox.javaRef + '.' + javaRef 763 784 #trace java 764 return xjava785 return javaRef 765 786 766 787 def writeJavaDef(sw as CurlyWriter) 767 788 base.writeJavaDef(sw) … … 1098 1119 1099 1120 class LocalVar is partial 1100 1121 1101 pass 1122 def writeJavaDef(sw as CurlyWriter) 1123 base.writeSharpDef(sw) 1124 sw.write('[.type.javaRef] [.javaName]') 1125 init = .type.javaInit 1126 if init.length, sw.write(' = [init]') 1127 sw.write(';\n') 1102 1128 1103 1129 1130 1104 1131 class ResultVar is partial 1105 1132 1106 1133 get javaName as String is override … … 1222 1249 base.writeJavaDef(sw) 1223 1250 .writeJavaAttribs(sw) 1224 1251 .writeJavaIsNames(sw) 1225 sw.write(' const ')1252 sw.write('static final ') # const 1226 1253 sw.write(_type.javaRef) 1227 1254 sw.write(' [_javaBackEndName] = ') 1228 1255 _initExpr.writeJavaDef(sw) … … 1602 1629 sw.writeLine('}') 1603 1630 1604 1631 get javaName as String is override 1605 return .name #. capitalized1632 return .name #./capitalized 1606 1633 1607 1634 # Java, for its sins, does not have support for properties built into the language... 1608 1635 # efforts to correct this stupidity seem to be mired in language navel gazing plus associated … … 1612 1639 # Its obviously too difficult to just copy C# (turnabout is fair play), accept and then evolve any edge misses 1613 1640 1614 1641 class ProperDexer is partial 1642 # AbstractBaseClass for Property and Indexer 1643 1644 def writeJavaBody(sw as CurlyWriter) 1645 #sw.write(' {\n') 1646 #sw.indent 1647 if _getPart 1648 #if .isAbstract or not .parentBox.canHaveStatements 1649 # sw.write('\tget;\n') 1650 #else 1651 # _getPart.writeJavaDef(sw) 1652 _getPart.writeJavaDef(sw) 1653 if _setPart 1654 #if .isAbstract or not .parentBox.canHaveStatements 1655 # sw.write('\tset;\n') 1656 #else 1657 # _setPart.writeJavaDef(sw) 1658 _setPart.writeJavaDef(sw) 1659 #sw.dedent 1660 #sw.write('}\n') 1615 1661 1616 # TODO1617 pass1618 1662 1619 1620 1663 class ProperDexerXetter is partial 1664 # BaseClass for Indexer get/set, Property get/set 1621 1665 1622 # TODO 1623 pass 1666 def innerWriteJavaDef(sw as CurlyWriter) 1667 base.innerWriteJavaDef(sw) 1668 sw.write(.xetPartName) 1669 .writeJavaImp(sw, false) 1624 1670 1625 1671 1626 1672 class Property is partial 1627 1673 1628 # TODO1629 pass1674 get javaNotNullPrefix as String is override 1675 return '' 1630 1676 1677 def writeJavaDef(sw as CurlyWriter) 1678 base.writeJavaDef(sw) 1679 sw.writeLine('') 1680 sw.write('//Property [_returnType.javaRef] [.name]') 1681 # .writeJavaImp(sw) 1682 getPart = .getPart 1683 if getPart 1684 .writeJavaNotNull(sw) 1685 .writeJavaAttribs(sw) 1686 .writeJavaIsNames(sw) 1687 sw.write('[_returnType.javaRef] get[.name.capitalized]') 1688 sw.write(' {\n') 1689 sw.indent 1690 getPart.writeJavaDef(sw) 1691 sw.dedent 1692 sw.write('}\n') 1693 setPart = .setPart 1694 if setPart 1695 .writeJavaNotNull(sw) 1696 .writeJavaAttribs(sw) 1697 .writeJavaIsNames(sw) 1698 sw.write('set[.name.capitalized]([_returnType.javaRef] value)') 1699 sw.write(' {\n') 1700 sw.indent 1701 setPart.writeJavaDef(sw) 1702 sw.dedent 1703 sw.write('}\n') 1704 #.writeJavaBody(sw) 1631 1705 1706 1707 if getPart 1708 .compiler.codeMemberStack.push(getPart) 1709 try 1710 if getPart.requirePart 1711 getPart.requirePart.writeJavaMethod(sw) 1712 if getPart.ensurePart 1713 getPart.ensurePart.writeJavaMethod(sw) 1714 finally 1715 .compiler.codeMemberStack.pop 1716 1717 if setPart 1718 .compiler.codeMemberStack.push(setPart) 1719 try 1720 if setPart.requirePart 1721 setPart.requirePart.writeJavaMethod(sw) 1722 if setPart.ensurePart 1723 setPart.ensurePart.writeJavaMethod(sw) 1724 finally 1725 .compiler.codeMemberStack.pop 1726 1727 if .compiler.includeTests 1728 .writeJavaTest(sw) 1729 1730 1632 1731 class Indexer is partial 1633 1732 1634 1733 # TODO … … 1708 1807 fileName = Utils.javaStringLiteralFor(fileName) 1709 1808 return 'new cobra.lang.SourceSite([fileName], [tok.lineNum], [boxName], [memberName], [javaThis])' 1710 1809 1810 def javaSourceSiteArgs as String 1811 return .javaSourceSiteArgs(.compiler.curBox.name, .compiler.curBoxMember.name, .javaThis) 1812 1813 def javaSourceSiteArgs(boxName as String, memberName as String, javaThis as String) as String 1814 require 1815 boxName.length 1816 memberName.length 1817 javaThis.length 1818 body 1819 boxName = Utils.javaStringLiteralFor(boxName) 1820 memberName = Utils.javaStringLiteralFor(memberName) 1821 tok = .token 1822 fileName = tok.fileName 1823 if not Path.isPathRooted(fileName) 1824 fileName = Path.combine(Environment.currentDirectory, fileName) 1825 fileName = Utils.javaStringLiteralFor(fileName) 1826 return '[fileName], [tok.lineNum], [boxName], [memberName], [javaThis]' 1827 1711 1828 get javaThis as String 1712 1829 if _inInitCall # C# won't allow 'this' in a base constructor call -- TODO 1713 1830 return '"(uninitialized [.compiler.curBox.name] instance)"' … … 1838 1955 sw.write('else ') 1839 1956 _elsePart.writeJavaDef(sw) 1840 1957 else 1841 # for any other kind of expression, use a Java switch 1958 # for any other kind of expression, use a Java switch. 1959 # TODO trap if expression is string and use a if-else ladder ( if not java7) 1842 1960 sw.write('switch(') 1843 1961 _expr.writeJavaDef(sw) 1844 1962 sw.write(') {\n') … … 2370 2488 2371 2489 def writeJavaDef(sw as CurlyWriter, parens as bool) is override 2372 2490 # recall that this cannot be the right side of "foo.bar" since that is a MemberExpr 2373 xjava= .javaQualification + .javaName2374 if _requiresGetClass, xjava = xjava+ '.getClass()'2375 #print 'Dbg: IdExpr::', java 2376 sw.write( xjava)2491 javaRef = .javaQualification + .javaName 2492 if _requiresGetClass, javaRef = javaRef + '.getClass()' 2493 #print 'Dbg: IdExpr::', javaRef 2494 sw.write(javaRef) 2377 2495 2378 2496 get javaQualification as String 2379 2497 qual = '' … … 2613 2731 def writeJavaDefForBreakdown(sw as CurlyWriter) is override 2614 2732 requiresTypeOf = _requiresTypeOf # using C# version currently - chop ? 2615 2733 if not requiresTypeOf, sw.write('typeof(') 2616 .write SharpDef(sw)2734 .writeJavaDef(sw) 2617 2735 if not requiresTypeOf, sw.write(')') 2618 2736 2619 2737 … … 2763 2881 def asJava as String is override 2764 2882 return _name 2765 2883 2884 class ToNilableOrNotExpr 2885 is partial 2886 2887 def writeJavaBreakdownItems(sw as CurlyWriter) 2888 base.writeJavaBreakdownItems(sw) 2889 _expr.writeJavaBreakdownItems(sw) 2890 2891 2892 class ToNilableExpr 2893 is partial 2894 2895 def writeJavaDef(sw as CurlyWriter, parens as bool) is override 2896 if _expr.type.isReference 2897 # In C#/.NET, reference types are always "nilable" 2898 _expr.writeJavaDef(sw) 2899 else 2900 # ex: ((int?)x) 2901 # ex: ((Color?)Color.Black) 2902 #sw.write('(([_expr.type.javaRef]?)') 2903 sw.write('(([_expr.type.javaRef])') 2904 _expr.writeJavaDef(sw, false) 2905 sw.write(')') 2906 2907 2908 class ToNonNilableExpr 2909 is partial 2910 2911 2912 def writeJavaDef(sw as CurlyWriter, parens as bool) is override 2913 type = _expr.type 2914 if type inherits NilableType and not type.nonNil.isReference 2915 # ex: (x).Value 2916 # ex: (obj.foo).Value 2917 sw.write('(') 2918 _expr.writeJavaDef(sw, false) 2919 #sw.write(').value') 2920 sw.write(')') 2921 else if .compiler.options.boolValue('include-nil-checks') 2922 sw.write('(CobraLangInternal.CobraCore._willCheckNil ? CobraLangInternal.CobraImp.CheckNonNil<[type.javaRef]>([.javaThis], [Utils.javaStringLiteralFor(_expr.toCobraSource)], ') 2923 _expr.writeJavaDef(sw, false) 2924 sw.write(', [.javaSourceSiteArgs]):') 2925 _expr.writeJavaDef(sw, false) 2926 sw.write(')') 2927 else 2928 _expr.writeJavaDef(sw, parens) 2929 2930 2766 2931 2767 2932 2768 2933 ## … … 3057 3222 _left.writeJavaBreakdownItems(sw) 3058 3223 3059 3224 3225 class InheritsExpr 3226 is partial 3227 3228 def _writeJavaDef(sw as CurlyWriter) is override 3229 _left.writeJavaDef(sw) 3230 sw.write(' instanceof ') 3231 _right.writeSharpDef(sw, false) 3060 3232 3233 3234 class ToExpr is partial 3235 3236 /# def needsContextCast as bool is override 3237 if .type.isDynamic, return base.needsContextCast 3238 else, return false # the user is already casting, so go with their cast 3239 #/ 3240 def _writeJavaDef(sw as CurlyWriter) is override 3241 rightType = _rightTypeExpr.potentialType to ! # its not nil or _bindImp would have thrown an error 3242 if rightType is .compiler.passThroughType 3243 _left.writeJavaDef(sw) 3244 return 3245 sw.write('(') 3246 _right.writeJavaDef(sw, false) # double parens would be pointless and also causes a C# error 3247 sw.write(')') 3248 if not rightType inherits NilableType and rightType.isReference and .compiler.options.boolValue('include-nil-checks') 3249 sw.write('CobraLangInternal.CobraImp.CheckNonNil<[_left.type.javaRef]>([.javaThis], [Utils.javaStringLiteralFor(_left.toCobraSource)], ') 3250 _left.writeJavaDef(sw, false) 3251 sw.write(', [.javaSourceSiteArgs])') 3252 else 3253 _left.writeJavaDef(sw) 3254 3255 3256 class ToQExpr 3257 is partial 3258 3259 def _writeJavaDef(sw as CurlyWriter) is override 3260 # x to? int --> ((x is int || x is int?) ? (int?)x : (int?)null) 3261 # x to? int? --> ((x is int || x is int?) ? (int?)x : (int?)null) 3262 # ^ but this would cause multiple evaluation of x, so... 3263 # x to? int? --> (int?)CobraLangInternal.CobraImp.ToOrNil(x) 3264 3265 # x to? string --> (x as String) 3266 # x to? string? --> (x as String) 3267 right = .right 3268 t = right.definition to IType 3269 t = t.nonNil 3270 typeJavaRef = t.javaRef 3271 #if t.isReference 3272 # sw.write('(') 3273 # .left.writeJavaDef(sw) 3274 # sw.write(') as [typeJavaRef]') 3275 #else 3276 # sw.write('[typeJavaRef])CobraLangInternal.CobraImp.ToOrNil<[typeJavaRef]>(') 3277 # .left.writeJavaDef(sw) 3278 sw.write('[typeJavaRef])CobraLangInternal.CobraImp.ToOrNil<[typeJavaRef]>(') 3279 .left.writeJavaDef(sw) 3280 sw.write(')') 3281 3282 3283 3061 3284 class CoalesceExpr 3062 3285 is partial 3063 3286 … … 3097 3320 if name is nil 3098 3321 name = _name 3099 3322 #print 'Dbg: MemberExpr::', name 3100 sw.write(name) 3101 if _definition and (_definition.isMethod or _name=='toString') and not _isReference # TODO: axe the 'toString' check 3323 if _definition inherits Property 3324 xet='get' 3325 if _isLValue, xet = 'set' 3326 sw.write(xet+name) 3102 3327 sw.write('()') 3328 else 3329 sw.write(name) 3330 if _definition and (_definition.isMethod or _name=='toString') and not _isReference # TODO: axe the 'toString' check 3331 sw.write('()') 3103 3332 3333 def _isLValue as bool 3334 if not (.superNode and .superNode inherits BinaryOpExpr) 3335 return false 3336 bsn0 = this to INode 3337 bsn = .binarySuperNode 3338 while true 3339 if bsn inherits AssignExpr and bsn0 is bsn.left 3340 return true 3341 if not (bsn.superNode and bsn.superNode inherits BinaryOpExpr) 3342 return false 3343 bsn0 = bsn 3344 bsn = bsn.binarySuperNode 3345 3104 3346 def writeJavaBreakdownItems(sw as CurlyWriter) is override 3105 3347 pass 3106 3348 -
Source/TestifyRunner.cobra
469 469 continue 470 470 471 471 if firstLineInsensitive.startsWith('#.require.') 472 rtPlatform = CobraCore.runtimePlatform 472 473 what = firstLineInsensitive[10:] 473 474 branch what 474 475 on 'mono' 475 if not CobraCore.isRunningOnMono476 if rtPlatform <> 'clr' or not CobraCore.isRunningOnMono 476 477 print 'Skipping test because requirement for "mono" is not met.' 477 478 return 0 478 479 on 'dotnet' 479 if CobraCore.isRunningOnMono480 if rtPlatform <> 'clr' or CobraCore.isRunningOnMono 480 481 print 'Skipping test because requirement for "dotnet" is not met.' 481 482 return 0 483 on 'clr' # mono or dotNet 484 if rtPlatform <> 'clr' 485 print 'Skipping test because requirement for "clr" is not met.' 486 return 0 487 on 'jvm' 488 if rtPlatform <> 'jvm' 489 print 'Skipping test because requirement for "jvm" is not met.' 490 return 0 482 491 else 483 492 if what.endsWith('.dll') 484 493 try -
Source/Enums.cobra
26 26 _idToken = Token.empty 27 27 _attribs = AttributeList() 28 28 _nativeType = nativeType 29 assert .compiler 30 .compiler.backEnd.setUnderlyingType(this) # sets _storageTypeNode 29 31 #_storageTypeNode = ClrTypeProxy(Enum.getUnderlyingType((_nativeType to ClrNativeType).backEndType)) # TODO: fix native 30 _callNativeScanMethod('UnderlyingType')31 32 _needScanNativeType = true 32 33 33 def _callNativeScanMethod(tag as String) 34 """ 35 Call a backend scan method for native type scan operation desired and backend in use. 36 """ 37 _needScanNativeType = true 38 # This is icky too - method to call needs to be set directly via backend somehow rather than this check and call code 39 # TODO: change to use strategy object set when init backend. 34 def _scanNativeType 40 35 assert .compiler 41 assert tag in ['ScanNativeType', 'UnderlyingType'] 42 backEnd = .compiler.backEnd 43 branch backEnd.name 44 on 'c#-clr' 45 branch tag 46 on 'UnderlyingType', _setUnderlyingTypeClr # sets _storageTypeNode 47 on 'ScanNativeType', _scanNativeTypeClr 48 on 'java-jvm' 49 branch tag 50 on 'UnderlyingType', _setUnderlyingTypeJvm # sets _storageTypeNode 51 on 'ScanNativeType', _scanNativeTypeJvm 52 on 'objc' 53 print 'objc back end need method for [tag]' 54 assert false, 'Missing backEnd infrastructure for [backEnd.getType.name]' 55 #branch on tag 56 # on 'UnderlyingType', _setUnderlyingTypeObjc 57 # on 'ScanNativeType', _scancNativeTypeObjc 58 else 59 throw FallThroughException('No nativeScanMethod code for backend [backEnd.name] [backEnd.getType.name]') 60 #TODO: remove all direct uses of ClrNativeType, ClrTypeProxy 61 36 .compiler.backEnd.scanNativeType(this) 37 62 38 get attributes as AttributeList is override 63 39 return _attribs 64 40 … … 96 72 return base.isUsed 97 73 set 98 74 base.isUsed = value 99 if _needScanNativeType, _ callNativeScanMethod('ScanNativeType')75 if _needScanNativeType, _scanNativeType 100 76 101 77 get nativeType from var 102 78 … … 113 89 _storageType = _storageTypeNode.realType 114 90 if not _storageType.isDescendantOf(.compiler.anyIntType) 115 91 .throwError('The enumeration storage type must be a primitive integer type such as int8, uint8, int16, uint16, int, uint, int64 or uint64.') 116 if _needScanNativeType, _callNativeScanMethod('ScanNativeType')92 if _needScanNativeType, _scanNativeType 117 93 118 94 def _bindImp is override 119 95 base._bindImp … … 127 103 return name 128 104 129 105 def memberForName(name as String) as IMember? 130 if _needScanNativeType, _callNativeScanMethod('ScanNativeType')106 if _needScanNativeType, _scanNativeType 131 107 m = base.memberForName(name) 132 108 if m is nil 133 109 objClass = .compiler.objectType -
Tests/720-libraries/400-other/216-use-lib-with-no-ref-extension-error.cobra
1 1 2 use Foo.Bar.dll # .error. Do not end a namespace name in a "use" directive with ".dll".2 use Foo.Bar.dll # .error. Do not end a namespace name in a "use" directive with an extension (like ".dll" or ".jar"). 3 3 4 4 class X 5 5 -
Tests/200-misc/280-custom-string-maker.cobra
48 48 sw = StringWriter() 49 49 CobraCore.tracer.destination = sw 50 50 trace s 51 assert sw.toString.startsWith(CobraCore.tracer.prefix + 's=-- special -- ;at')51 assert sw.toString.startsWith(CobraCore.tracer.prefix + 's=-- special --[CobraCore.tracer.separator]at') 52 52 finally 53 53 CobraCore.techStringMaker = save 54 54 -
Tests/100-basics/030-hello-world.cobra
1 # .require. clr 1 2 namespace Test 2 3 class Test 3 4 def main -
Tests/100-basics/033-get-property-instance.cobra
1 #.require. clr 1 2 namespace Test 2 3 class Test 3 4 def main -
Tests/100-basics/030j-hello-world1.cobra
1 # .require. jvm 2 namespace Test 3 class Test 4 def main is shared 5 Java.Lang.System.out.println('Hello, world.(Java.Lang.System)') 6 #print 'Hello, world. (print)' 7 -
Tests/100-basics/032-get-property-static.cobra
1 # .require. clr 1 2 namespace Test 2 3 class Test 3 4 def main -
Tests/100-basics/032j-get-property-static.cobra
1 #.require. jvm 2 namespace Test 3 class Test 4 def main 5 is shared 6 #nl as String = Environment.newLine 7 nl as String? = System.getProperty('line.separator') 8 nl1 as String? = String.format('%n') 9 assert nl == nl1 10 pathSep as String? = File.pathSeparator 11 sep as String? = Java.Io.File.separator 12 print 'pathSep', pathSep 13 print 'DirSep', sep 14 15 CobraCore.noOp(nl, nl1, pathSep) 16 17 rt = Runtime.runtime # Runtime.getRuntime 18 s = rt.totalMemory to ! 19 print s, 'bytes' 20 #print s/1024/1024, 'MB' 21 print rt -
Tests/100-basics/033j-get-property-instance.cobra
1 # .require. jvm 2 namespace Test 3 class Test 4 def main 5 is shared 6 p = System.getProperties 7 #p = System.properties # above as a prop - codegen NYI 8 9 #nl as String = p['line.separator'] # indexer NYI p.getProperty('') 10 nl as String? = p.getProperty('line.separator') 11 print '_', nl, '_' 12 CobraCore.noOp(nl) -
Tests/100-basics/600-backend-names.cobra
1 #.require. clr 2 # chk for leakage from backends. 3 # Collision or bad typing for variables named using BackEnd (system) namespaces 4 class BE 5 def main 6 java = 'java in a string' # not confused with 'java.lang....' namespace 7 #print java 8 #print java.typeOf 9 assert java.typeOf == System.String 10 11 # objc is already a reserved keyword 12 #objc = 'objcStr' 13 #print objc 14 #print objc.typeOf 15 #assert objc.typeOf == 'System.String' 16 17 objectC = 91 18 #print objectC 19 #print objectC.typeOf 20 assert objectC.typeOf == System.Int32 21 22 .objc1 23 24 def objc1 25 objectc = false 26 #print objectc 27 #print objectc.typeOf 28 assert objectc.typeOf == System.Boolean -
Tests/100-basics/030j-hello-world.cobra
1 # .require. jvm 2 namespace Test 3 class Test 4 def main is shared 5 System.out.println('Hello, world.( System only)') 6 #print 'Hello, world. (print)' 7 -
Tests/100-basics/034-set-property.cobra
1 # .require. clr 1 2 namespace Test 2 3 class Test 3 4 def main