Ticket #275: java-jvm-part1.patch
File java-jvm-part1.patch, 196.5 KB (added by hopscc, 13 years ago) |
---|
-
Source/TypeProxies.cobra
3 3 """ 4 4 An ITypeProxy is a node that represents/stands-in for a type. 5 5 Its .realType property returns that type, often by locating it among symbols. 6 Implemented by CobraType, AbstractTypeIdentifier, NilableTypeProxy and ClrTypeProxy.6 Implemented by CobraType, AbstractTypeIdentifier, NilableTypeProxy and the backEnd TypeProxies. 7 7 """ 8 8 9 9 # TODO: See above NOTE and consider adding name below. Also see _bindBase in Boxes.cobra which would benefit from .name … … 110 110 return VariType(_innerType.realType) 111 111 112 112 113 class ClrTypeProxy inherits AbstractTypeProxy113 class NativeTypeProxy inherits AbstractTypeProxy is abstract 114 114 """ 115 Acts as an ITypeProxy where the CLR type is known.116 Typically used when scanning DLLs.115 TypeProxy specifically for a BackEnd provided Type otherwise same as an AbstractTypeProxy 116 Specific implementation will be provided by the backend e.g. {Clr,Jvm}TypeProxy 117 117 """ 118 118 119 shared120 121 var _cobraNameForSharpGenericNameCache = Dictionary<of String, String>()122 123 def cobraNameForSharpBoxName(name as String) as String124 """125 Returns 'Foo' for 'Foo' and 'Foo<of,>' for 'Foo`2'126 In other words, works for generic and non-generic classes, structs and interfaces.127 Does *not* work for arrays, pointers, etc.128 """129 if '`' not in name130 return name131 if _cobraNameForSharpGenericNameCache.containsKey(name)132 return _cobraNameForSharpGenericNameCache[name]133 else134 parts = name.split(c'`')135 count = int.parse(parts[1])136 cobraName = parts[0] + '<of'137 for i in count-1, cobraName += ','138 cobraName += '>'139 _cobraNameForSharpGenericNameCache[name] = cobraName140 return cobraName141 142 var _clrType as Type143 144 145 cue init(nativeType as NativeType) # TODO: HACK146 .init((nativeType to ClrNativeType).clrType)147 148 cue init(clrType as Type)149 base.init150 _clrType = clrType151 152 def addMinFields153 base.addMinFields154 .addField('clrType', _clrType)155 156 get realType as IType is override157 return _realTypeWithCache(_clrType)158 159 def _realTypeWithCache(clrType as Type) as IType160 t = (.compiler to Compiler).typeForClrType(clrType)161 if t is nil162 t = _realTypeWithoutCache(clrType, 0)163 (.compiler to Compiler).addTypeForClrType(t to !, clrType)164 return t to !165 166 def _realTypeWithoutCache(clrType as Type, level as int) as IType167 assert .compiler.basicTypes.count > 9 # should have bool, char, all the ints, etc.168 169 # Must return the Cobra primitive types in place of System.Boolean, System.Char, System.Int16, etc.170 # because it's the primitives that are used all over the compiler.171 clrPrimitiveToIType = .compiler.clrPrimitiveToITypeCache172 if clrPrimitiveToIType is nil or clrPrimitiveToIType.count == 0173 clrPrimitiveToIType = _makePrimitiveTypesDict174 basicType as IType?175 if clrPrimitiveToIType.tryGetValue(clrType, out basicType)176 return basicType to !177 178 # handle wrapped types, like arrays and pointers, with recursive calls179 if clrType.isArray180 # assert clrType.name.endsWith(r'[]') # could be [,] so TODO: handle multidim arrays181 return .typeProvider.arrayType(_realTypeWithCache(clrType.getElementType to !))182 else if clrType.isNested and not clrType.isGenericParameter183 declaringType = _realTypeWithCache(clrType.declaringType to !)184 potential = declaringType.memberForName(clrType.name)185 if potential is nil186 # comes up on MS Windows .NET 2.0 for multiple types when using System.Windows.Forms187 # error: Cannot locate nested CLR type "System.Windows.Forms.UnsafeNativeMethods+IOleControl" (simple name is "IOleControl").188 if 'NativeMethods' in clrType.toString189 return _hack(clrType)190 .throwError('Cannot locate nested CLR type "[clrType]" (simple name is "[clrType.name]").')191 else if potential inherits IType192 return potential193 else194 .throwError('Located CLR type spec "[clrType]" but got a [potential.englishName] instead of a type.')195 else if clrType.isPointer196 assert clrType.name.endsWith('*')197 # TODO: handle pointer types198 return _realTypeWithCache(clrType.getElementType to !)199 else if clrType.isByRef200 assert clrType.name.endsWith('&')201 # TODO: handle ref types202 return _realTypeWithCache(clrType.getElementType to !)203 204 # generic parameters205 if clrType.isGenericParameter206 return GenericParam(ClrNativeType(clrType))207 208 typeName = _computeTypeName(clrType)209 missing = false210 curNS = _computeNameSpace(clrType, level, out missing)211 if missing212 # since the CLR type exists, but cannot be located in our namespaces,213 # it must be pulled from a dependent DLL that was not directly referenced214 # but maybe it was already attempted215 if level > 0, .throwError('Cannot read CLR type "[clrType.fullName]" or its assembly "[clrType.assembly]". Please report to the Cobra discussion forums (http://cobra-language.com/).')216 217 (.compiler to dynamic).readAssembly(clrType.assembly)218 return _realTypeWithoutCache(clrType, level+1) # recurse. guard is just above.219 220 # return namespace member221 member as IMember? = curNS.declForName(typeName)222 if member inherits IType223 if member inherits Box224 if clrType.isGenericType and not clrType.isGenericTypeDefinition225 # So we have something like ICollection<of KeyValuePair<of TKey,TValue>> which is all CLR types.226 # We need the Cobra types of those args so we can construct the Cobra type from the generic cobra type227 # otherwise, we would just end up returning the generic definition.228 member = _typeForArgsOfGeneric(clrType, member)229 return member230 else231 msg = 'Cannot locate CLR type "[clrType]".'232 if clrType.namespace and clrType.namespace.startsWith('System.')233 # TODO: On .NET 2.0 only \Tests\110-basics-two\550-collection-equality.cobra234 # fails with: Cannot locate CLR type "System.Collections.KeyValuePairs[]".235 # Figure out why.236 if .compiler and .compiler.verbosity > 1237 print msg238 # TODO: .compiler.warning(msg)239 return .compiler.objectType240 else241 .throwError(msg)242 return .compiler.intType # CC: to make C# code gen happy.243 244 def _makePrimitiveTypesDict as Dictionary<of System.Type, IType>245 clrPrimitiveToIType = Dictionary<of System.Type, IType>()246 for bt in .compiler.basicTypes247 if bt.systemAliasProxy248 key = (.compiler.nativeType((bt.systemAliasProxy to LibraryTypeProxy).qualifiedName) to ClrNativeType).clrType # TODO: cleanup249 clrPrimitiveToIType[key] = bt250 assert clrPrimitiveToIType.count == 0 or clrPrimitiveToIType.count > 9251 return clrPrimitiveToIType252 253 def _computeTypeName(clrType as Type) as String254 typeName = clrType.name255 if '`' in typeName256 # generic like IComparable`1257 assert r'[' not in typeName258 typeName = .cobraNameForSharpBoxName(typeName)259 else if typeName[typeName.length-1].isLetterOrDigit260 pass261 else262 .throwError('Cannot locate CLR type "[clrType]".')263 return typeName264 265 def _computeNameSpace(clrType as Type, level as int, missing as out bool) as NameSpace266 missing = false267 if clrType.namespace is nil, return .compiler.globalNS268 nameParts = clrType.namespace.split(c'.')269 member = .compiler.globalNS.symbolForName(nameParts[0])270 if member inherits NameSpace, curNS = member271 else, missing = true272 if not missing273 i = 1274 while i < nameParts.length275 namePart = nameParts[i]276 possible = curNS.declForName(namePart)277 if possible is nil278 missing = true279 break280 else if possible inherits NameSpace281 curNS = possible282 else283 .throwError('Found "[namePart]" at component [i+1] of CLR type "[clrType.fullName]", but it is a [possible.englishName].')284 i += 1285 return curNS286 287 def _typeForArgsOfGeneric(clrType as Type, member as IType) as IType288 args = List<of IType>()289 for genArg in clrType.getGenericArguments290 args.add(_realTypeWithCache(genArg))291 boxMember = member to Box292 if boxMember.qualifiedName == 'System.Nullable<of>'293 assert args.count == 1294 member = .typeProvider.nilableType(args[0])295 else296 member = boxMember.constructedTypeFor(args)297 return member298 299 def _hack(clrType as Type) as IType300 if clrType.isInterface301 return ClrTypeProxy(sharp'typeof(System.ICloneable)').realType302 else303 return ClrTypeProxy(Object).realType304 305 306 119 ## 307 120 ## Type Identifiers 308 121 ## -
Source/BackEndObjC/ObjcBackEnd.cobra
1 use System.Diagnostics 2 1 3 class ObjcBackEnd inherits BackEnd 2 4 3 5 cue init(compiler as Compiler) … … 2 4 base.init(compiler) 5 _name = 'objc' 6 _rtlName = 'Cobra.Lang.dll' 7 _tagToTypeName = { # TODO 8 'Object': '', 9 'Type' : '', 10 } 3 11 … … 9 17 10 18 def computeOutName as String is override 11 19 return .compiler.computeOutNameObjc 20 21 def genNativeModule(filename as String, verbosity as int) as Module? is override 22 m as Module? 23 if filename.endsWith('.objc') # ?? 24 if verbosity, print 'Noting [filename] as ObjCModule' # extra space to line up with 'Parsing [filename]' 25 assert false, 'Need code for an ObjCModule' 26 #m = ObjCModule(filename, verbosity) 27 return m 12 28 29 def setupRunProcess(baseExe as String, fullExe as String) as Process is override 30 p = Process() 31 p.startInfo.fileName = baseExe 32 return p 33 34 def setDefaultUseDirectives(ns as NameSpace) is override 35 useToken = Token('(implicit)', 1, 1, 1, 'USE', 'use', nil) 36 # these arent correct for ObjC but are here as a placeholder/reminder 37 ns.addUseDirective(UseDirective(useToken, ['System'])) 38 ns.addUseDirective(UseDirective(useToken, ['System', 'Collections', 'Generic'])) 39 ns.addUseDirective(UseDirective(useToken, ['System', 'IO'])) 40 ns.addUseDirective(UseDirective(useToken, ['System', 'Text'])) 41 ns.addUseDirective(UseDirective(useToken, ['Cobra', 'Lang'])) 42 43 def fixLibExtension(libRef as String) as String is override 44 """ 45 Augment given lib reference string with .dll backend extension if not already have one 46 """ 47 or require libRef.length 48 and ensure result.endsWith('.dll') 49 if not libRef.endsWith('.dll') 50 libRef += '.dll' 51 return libRef 52 53 def loadLibReference(reference as String) as bool is override 54 return false # TODO 55 56 def readSystemTypes is override 57 pass 58 59 def fixNilableMemberSigs is override 60 pass 13 61 62 def installNativeMethods(box as Box, nativeType as NativeType) is override 63 pass 64 65 def cobraNameForNativeBoxName(nativeBoxName as String) as String is override 66 return nativeBoxName # TODO 67 68 # Types 69 get objectTypeProxy as AbstractTypeProxy is override 70 """Type proxy for BE root of Object hierarchy.""" 71 return ClrTypeProxy(Object) # Tmp pending ObjcTypeProxy 72 73 get typeTypeProxy as AbstractTypeProxy is override 74 """Type proxy for BE notion of a class describing a Type.""" 75 return ClrTypeProxy(Type) # Tmp pending ObjcTypeProxy 76 77 def nativeTypeProxy(type as NativeType) as NativeTypeProxy is override 78 assert false, 'ObjcBackEnd ObjcNativeTypeProxy NYI' 79 return ClrTypeProxy(type) # Tmp pending ObjcTypeProxy 80 81 def nativeType(type as dynamic) as NativeType is override 82 assert false, 'ObjcBackEnd ObjcNativeType NYI' 83 return ClrNativeType(type) # Tmp pending ObjcNativeType 84 85 def nativeTypeByName(qualifiedName as String) as NativeType is override 86 assert false, 'ObjcBackEnd ObjcNativeType and objcTypeByName NYI' 87 return ClrNativeType(.compiler.clrTypeByName(qualifiedName)) 88 89 def addArrayInterfaces( interfaces as List<of ITypeProxy>) is override 90 assert false, 'ObjcBackEnd addArrayInterfaces NYI' 91 92 93 14 94 class GenerateObjcCodePhase inherits Phase 15 95 16 96 cue init(c as Compiler) -
Source/Compiler.cobra
29 29 30 30 cue init(obj as Object) 31 31 base.init('Not expecting invocation.') 32 33 class LoadReferenceException inherits Exception 34 """ 35 Thrown when Loading a reference fails for some reason. 36 FileNotFoundException, FileLoadException 37 """ 38 var fileName ='' 39 var tag='' 40 41 cue init(tag as String, fileName as String, msg as String) 42 base.init(msg) 43 .tag = tag 44 .fileName = fileName 45 46 def toString as String is override 47 return '[.tag] [.fileName] [.message]' 32 48 33 34 49 enum PlatformEnum 35 50 Microsoft 36 51 Novell 37 52 38 39 class BackEnd is abstract 53 54 # Should this be in BackEndCommon ? 55 class BackEnd is abstract 40 56 """ 41 Subclasses will often inspect the compiler for various options such as .willWriteTestInvocation.57 Holder for items specific to the backEnd implementation 42 58 """ 43 59 60 var _tagToTypeName = Dictionary<of String, String>() 61 """ Map from Typename tags used in compiler to backend specific qualified Type name""" 62 44 63 cue init(compiler as Compiler) 45 64 base.init 65 _name = '' 66 _rtlName = 'rtl' 46 67 __compiler = compiler 47 68 69 get name from var as String 70 71 get cobraRuntimeLibFile from _rtlName as String 72 48 73 get compiler from __compiler as Compiler 49 74 75 get tagToTypeName from var 76 """ Map from TypeName tags used in compiler to backend specific qualified TypeName""" 77 78 def resolveTypeTag(qualifiedNameOrTag as String) as String 79 if qualifiedNameOrTag.contains('.') 80 qualifiedName = qualifiedNameOrTag 81 else 82 qualifiedName = .tagToTypeName[qualifiedNameOrTag] # type tag to backend qualifiedName 83 return qualifiedName 84 50 85 def makePhases(phases as IList<of Phase>) is abstract 51 86 """ 52 87 Given a list of core phases for compilation complete it with additions (or even removals and … … 57 92 """ 58 93 Return binary output name for compilation of files for this backend. 59 94 """ 95 96 def genNativeModule(filename as String, verbosity as int) as Module? is abstract 97 """ 98 Check if a filename is a Native module and if so return the Native module type for it 99 otherwise return nil. 100 """ 101 102 def setupRunProcess(baseExe as String, fullExe as String) as Process is abstract 103 """ 104 Create and initialise the process to run the compiled program post compilation 105 setup varies on the backend (.Clr/Jvm) and platform. 106 """ 107 108 def setDefaultUseDirectives(ns as NameSpace) is abstract 109 """ 110 Set the default Use directives into the given Namespace (usually topNamespace) for this backend. 111 """ 112 113 def fixLibExtension(libRef as String) as String is abstract 114 """ 115 Augment given lib reference string with backend extension if not already have one. 116 """ 117 118 def loadLibReference(reference as String) as bool is abstract 119 """ 120 Load the given lib reference file using the current backend paradigms. 121 Return true if reference found and loaded correctly, false otherwise 122 """ 123 124 def readSystemTypes is abstract 125 """ Read and Load System Types for backend for Compiler to make available""" 126 127 128 def fixNilableMemberSigs is abstract 129 """ 130 Most backends dont natively support nilablility, this marks/fixes the common backend 131 class signatures that should be marked nilable. 132 """ 133 134 def installNativeMethods(box as Box, nativeType as NativeType) is abstract 135 """ 136 Setup so that static methods (on Primitives and some others) get installed/treated as normal methods 137 on the instance. 138 """ 139 140 # Native Types access 141 def cobraNameForNativeBoxName(name as String) as String is abstract 142 """ 143 Returns name from backend library entries converted to cobra naming form. 144 """ 145 146 get objectTypeProxy as AbstractTypeProxy is abstract 147 """BE TypeProxy for root of back end Object hierarchy.""" 60 148 149 get typeTypeProxy as AbstractTypeProxy is abstract 150 """BE TypeProxy for BE notion of a class describing a Type.""" 61 151 152 def nativeTypeProxy(type as NativeType) as NativeTypeProxy is abstract 153 """ 154 Return a Proxy placeHolder for a BackEnd Native Type. 155 """ 156 157 def nativeType(type as dynamic) as NativeType is abstract 158 """ 159 Return a Native Type wrapped so we can use it without explicitly knowing what it is anywhere 160 else but the providing back end. Used by the backends to generate Types from Libraries. 161 """ 162 163 def nativeTypeByName(qualifiedName as String) as NativeType is abstract 164 """ 165 Return a Native Type corresponding to the fully qualified name. 166 Abstract Type Literal tags used in the compiler directly can also be obtained through this 167 otherwise the qualified names are expected to conform to the platform back end naming. 168 """ 169 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 173 174 class BasicBackEnd inherits BackEnd 175 """ Stub BackEnd for tests. """ 176 177 cue init(compiler as Compiler) 178 base.init(compiler) 179 _name = 'c#-clr(basic)' 180 _rtlName = 'cobraRTL.libext' 181 182 _tagToTypeName = { 183 'Object': 'System.Object', 184 'Type' : 'System.Type', 185 } 186 187 def makePhases(phases as IList<of Phase>) is override 188 pass 189 190 def computeOutName as String is override 191 return 'BasicOut' 192 193 def genNativeModule(filename as String, verbosity as int) as Module? is override 194 return nil 195 196 def setupRunProcess(baseExe as String, fullExe as String) as Process is override 197 p = Process() 198 p.startInfo.fileName = 'echo' 199 p.startInfo.arguments = 'basic BackEnd process - [baseExe]' 200 return p 201 202 def setDefaultUseDirectives(ns as NameSpace) is override 203 pass 204 205 def fixLibExtension(libRef as String) as String is override 206 if not libRef.endsWith('.libext') 207 libRef += '.libext' 208 return libRef 209 210 def loadLibReference(reference as String) as bool is override 211 return true 212 213 def readSystemTypes is override 214 pass 215 216 def fixNilableMemberSigs is override 217 pass 218 219 def installNativeMethods(box as Box, nativeType as NativeType) is override 220 pass 221 222 # Native Type access 223 def cobraNameForNativeBoxName(name as String) as String is override 224 return name + '_BBE' 225 226 # Types 227 get objectTypeProxy as AbstractTypeProxy is override 228 return ClrTypeProxy(Object) # for testing 229 230 get typeTypeProxy as AbstractTypeProxy is override 231 return ClrTypeProxy(Type )# for testing 232 233 def nativeTypeProxy(type as NativeType) as NativeTypeProxy is override 234 return ClrTypeProxy(type) #TODO: fix this to something non BE specific Tmp 235 236 def nativeType(type) as NativeType is override 237 return ClrNativeType(type) #TODO: fix this to something non BE specific Tmp 238 239 def nativeTypeByName(qualifiedName as String) as NativeType is override 240 return ClrNativeType(System.Object) #TODO: fix this to something non BE specific Tmp 241 242 def addArrayInterfaces( interfaces as List<of ITypeProxy>) is override 243 pass 244 62 245 class Compiler implements ITypeProvider, IWarningRecorder, IErrorRecorder, ICompilerForNodes is partial 63 246 """ 64 247 General notes: … … 70 253 """ 71 254 72 255 var _backEnd as BackEnd? 73 256 74 257 var _nextSerialNum as int is shared 75 258 var _serialNum as int 76 259 var _verbosity as int … … 99 282 var _intermediateFileNames as List<of String> 100 283 var _loadedReferences as List<of String> 101 284 102 var _clrTypeCache as Dictionary<of String, System.Type>103 285 104 105 286 # caches 106 var _clrPrimitiveToITypeCache as IDictionary<of System.Type, IType>? 287 #var _clrPrimitiveToITypeCache as IDictionary<of System.Type, IType>? 288 var _primitiveToITypeCache as IDictionary<of dynamic, IType>? 107 289 108 109 290 cue init 110 291 .init(0, nil) 111 292 … … 134 315 _warnings = List<of SourceException>() 135 316 _intermediateFileNames = List<of String>() 136 317 _loadedReferences = List<of String>() 137 _clrTypeCache = Dictionary<of String, System.Type>()138 318 if initialModules 139 319 if false # TODO: not working yet 140 320 for mod in initialModules … … 157 337 get includeTests as bool 158 338 return .options.boolValue('include-tests') 159 339 160 get clrPrimitiveToITypeCache from var340 get primitiveToITypeCache from var 161 341 """ 162 Returns a cache mapping CLRtypes to their corresponding ITypes.163 Populated and used by ClrTypeProxy.342 Returns a cache mapping BackEnd types to their corresponding ITypes. 343 Populated and used by the backend TypeProxy implementations ( {Clr,Jvm,...}TypeProxy) 164 344 """ 345 set primitiveCache as IDictionary<of dynamic, IType> 346 assert value.count <> 0 347 _primitiveToITypeCache = value 165 348 166 349 get globalNS from var 167 350 … … 467 650 if not opts.containsKey('reference') 468 651 opts['reference'] = List<of String>() 469 652 refs = opts['reference'] to List<of String> 470 libName = 'Cobra.Lang.dll' # TODO: why is this hard coded? What is this method used for?653 libName = .backEnd.cobraRuntimeLibFile 471 654 if libName not in refs 472 655 if .verbosity, print 'Adding reference to [libName]' 473 656 refs.add(libName) … … 480 663 Returns a new Process with startInfo.fileName and p.startInfo.arguments set appropriately 481 664 for the produced executable and the current options and any provided argsList. 482 665 """ 483 p = Process()484 666 baseExeFileName = exeName ? .baseExeFileName 485 667 fullExeFileName = exeName ? .fullExeFileName 486 branch .platform 487 on PlatformEnum.Microsoft 488 p.startInfo.fileName = baseExeFileName 489 on PlatformEnum.Novell 490 p.startInfo.fileName = 'mono' 491 args = '' 492 # mono also needs --debug when running 493 if .options.getDefault('debug', '') not in ['', '-'] 494 args += '--debug ' 495 args += '"[fullExeFileName]"' 496 p.startInfo.arguments = args + ' ' 497 else 498 throw FallThroughException(.platform) 668 p = .backEnd.setupRunProcess(baseExeFileName, fullExeFileName) 499 669 500 670 if argList and argList.count 501 671 args = p.startInfo.arguments ? '' … … 637 807 _passThroughType = PassThroughType() 638 808 return _passThroughType to ! 639 809 640 get typeType as IType641 return _libraryType('System.Type')642 643 810 get unspecifiedType as UnspecifiedType 644 811 if _unspecifiedType is nil 645 812 _unspecifiedType = UnspecifiedType() … … 677 844 if _nilableDynamicType is nil 678 845 _nilableDynamicType = .nilableType(.dynamicType) 679 846 return _nilableDynamicType to ! 847 # -- end of ITypeProvider 680 848 849 /# 850 overrides replacing above for mixin of BasicTypeProvider 851 class Compiler ... includes BasicTypeProvider 852 853 var _nilableDynamicType as NilableType? 854 855 get numberType as AbstractNumberType is override 856 if _numberType is nil 857 branch .options['number'] to String 858 on 'decimal', _numberType = .decimalType 859 on 'float', _numberType = .floatType 860 on 'float32', _numberType = .floatType(32) 861 on 'float64', _numberType = .floatType(64) 862 else, throw FallThroughException(.options['number']) 863 return _numberType to ! 681 864 865 866 def nilableType(type as IType) as NilableType is override 867 if type inherits NilableType, return type 868 if _nilableTypes is nil 869 _nilableTypes = Dictionary<of INode, NilableType>() 870 if _nilableTypes.containsKey(type) 871 return _nilableTypes[type] 872 else 873 _nilableTypes[type] = nt = NilableType(type) 874 nt.bindInh 875 if not .isBindingInh, nt.bindInt 876 return nt 877 878 def defaultType as IType is override 879 return .nilableDynamicType 880 881 def nilableDynamicType as NilableType 882 if _nilableDynamicType is nil 883 _nilableDynamicType = .nilableType(.dynamicType) 884 return _nilableDynamicType to ! 885 #/ 886 887 888 get typeType as IType 889 #return _libraryType('System.Type') 890 #return _libraryType(.backEnd.tagToTypeName['Type']) 891 return .libraryType('Type') 892 682 893 ## More type stuff 683 894 684 895 def readSystemTypes 685 # TODO: support targeting a specific CLR version, but not below 2.0 686 .readAssembly(Assembly.load('mscorlib.dll') to !) 896 .backEnd.readSystemTypes 687 897 688 # TODO: .readAssembly(Assembly.loadFrom('System.dll') to !)689 # gives: Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.dll' or one of its dependencies. The system cannot find the file specified.690 691 t = System.Diagnostics.Process.getType692 .readAssembly(t.assembly) # System.dll693 694 898 def fixLibExtensions(references as List<of String>) 695 899 i = 0 696 900 for reference in List<of String>(references) 697 references[i] = reference.fixLibExtension901 references[i] = .backEnd.fixLibExtension(references[i]) 698 902 i += 1 699 903 700 904 def printRefs(references as List<of String>) … … 742 946 # sharp'curDomain.ReflectionOnlyAssemblyResolve += _resolveEvent' 743 947 744 948 for reference in references 745 if not .loadReference(reference )949 if not .loadReference(reference, false) 746 950 _addMessage(SourceException('Cannot locate assembly reference "[reference]".')) 747 951 748 952 def refsForPackage(pkgName as String) as List<of String> … … 798 1002 # see .loadReference which sets up the indented writer 799 1003 (CobraCore.printDestination to IndentedWriter).dedent 800 1004 801 def loadReference(reference as String ) as bool1005 def loadReference(reference as String, addExtn as bool) as bool 802 1006 """ 803 1007 Attempts to load the given library reference. 804 1008 On success, adds reference to .loadedReferences and returns true. 805 1009 On failure, returns false, but does not add any warnings or errors. 806 1010 This method is used by Compiler and UseDirective. 807 1011 """ 1012 if addExtn 1013 reference = .backEnd.fixLibExtension(reference) 808 1014 v, rv = .verbosity, .referenceVerbosity 809 1015 if v, print 'Loading reference:', reference 810 1016 if rv … … 824 1030 825 1031 def _loadReference(reference as String) as bool 826 1032 try 827 return __loadReference(reference)828 catch fnfe as System.IO.FileNotFoundException829 # example: Could not load file or assembly 'NHibernate, Version=2.1.0.1001,1033 return .backEnd.loadLibReference(reference) 1034 catch lre as LoadReferenceException 1035 # example: 'FileNotFoundException fileName Could not load file or assembly 'NHibernate, Version=2.1.0.1001, 830 1036 # Culture=neutral, PublcKeyToken=aa95f207798dfdb4' or one of its dependencies. The 831 1037 # system cannot find the file specified. 832 if .referenceVerbosity, print '[ fnfe] in _loadReference("[reference]")'1038 if .referenceVerbosity, print '[lre] in _loadReference("[reference]")' 833 1039 return false 834 catch fle as System.IO.FileLoadException835 if .referenceVerbosity, print '[fle] in _loadReference("[reference]")'836 return false837 1040 838 def __loadReference(reference as String) as bool 839 require 840 reference.endsWith('.dll') or reference.endsWith('.exe') 841 reference not in ['.dll', '.exe'] 842 ensure 843 result implies .loadedReferences[.loadedReferences.count-1] == reference 844 not result implies .loadedReferences.count == old .loadedReferences.count 845 body 846 rv = .referenceVerbosity 847 assert not (reference.startsWith('-r') and '-r' in reference[2:]) 848 if false 849 # Does not work on Novell Mono. See notes above. 850 referredAss = Assembly.reflectionOnlyLoadFrom(reference) 851 # TODO: handle all the exceptions from Assembly.loadFrom 852 else 853 if File.exists(reference) 854 # try current directory 855 if rv, print '"[reference]" found as file. Will Assembly.loadFrom().' 856 referredAss = Assembly.loadFrom(reference) 857 if rv, print 'Assembly.loadFrom() returned: [CobraCore.toTechString(referredAss)]' 858 else 859 # TODO: the problem with -lib: in both Cobra and C# is that it has no effect on runtime, 860 # you must still register the DLLs in the GAC or copy them into the same dir as the .exe 861 # because the -lib: paths are not passed into executable. 862 # So should Cobra copy the .dll's into the target directory (if their paths are not in MONO_PATH)? 863 if rv, print 'File does not exist.' 864 searchPaths = .options.getDefault('library-directory', List<of String>()) to List<of String> 865 # TODO: ?: searchPaths.add(Path.getDirectoryName(Assembly.getExecutingAssembly.location)) # try Cobra's directory - also should be added to .options.'library-directory' not to a local var 866 found = false 867 for searchPath in searchPaths 868 if rv, print 'Checking lib path: "[searchPath]"' 869 combinedPath = Path.combine(searchPath, reference) 870 if File.exists(combinedPath) 871 if rv, print '"[reference]" found as file. Will Assembly.loadFrom().' 872 referredAss = Assembly.loadFrom(combinedPath) 873 if rv, print 'Assembly.loadFrom() returned: [CobraCore.toTechString(referredAss)]' 874 found = true 875 break 876 if rv 877 if searchPaths.count 878 if not found, print 'Did not find "[reference]" in lib paths' 879 else 880 print 'No lib paths to search.' 881 if not found 882 # try system wide (GAC) 883 if reference.endsWith('.dll'), reference = reference[:-4] 884 if rv, print 'Will load with partial name "[reference]"' 885 referredAss = Utils.loadWithPartialName(reference) 886 if rv, print 'Load with partial name returned: [CobraCore.toTechString(referredAss)]' 887 if referredAss is nil, return false 888 # 2009-08-03 CE: Removed this code: 889 # reference = referredAss.location 890 # To address this: 891 # http://cobra-language.com/forums/viewtopic.php?f=4&t=501 892 # See also: ../Tests/720-libraries/100-microsoft/110-winforms-native-compiler.cobra 893 # Note the -native-compiler option in that test which triggers this. 894 # Also, it doesn't see right to have to use the full path of a GAC-based assembly anyway. 895 # But still have to end in .dll or .exe: 896 reference += if(referredAss.location.endsWith('.exe'), '.exe', '.dll') 897 # TODO: handle all the exceptions from Assembly.loadFrom 898 if referredAss 899 if _willReadDependencies 900 for dependency in referredAss.getReferencedAssemblies 901 if rv 902 print '>> Loading dependency: [dependency]' 903 .indentPrint 904 try 905 .loadAssembly(dependency) 906 finally 907 .outdentPrint 908 print '<< Loading dependency: [dependency]' 909 else 910 .loadAssembly(dependency) 911 if rv, print 'Will read assembly: [referredAss]' 912 try 913 .readAssembly(referredAss, reference <> 'Cobra.Lang.dll') 914 catch readExc as Exception 915 if rv, print 'Caught exception during read assembly: [readExc]' 916 throw 917 if rv, print 'Did read assembly: [referredAss]' 918 # reassert the preconditions. there have been bugs in the past 919 assert reference.endsWith('.dll') or reference.endsWith('.exe') 920 assert reference not in ['.dll', '.exe'] 921 .loadedReferences.add(reference) 922 if rv, print 'Returning true for __loadReference("[reference]").' 923 return true 924 else 925 if rv, print 'Returning false for __loadReference("[reference]").' 926 return false 927 928 var _didLoadAssemblies = Set<of String>() 929 930 def loadAssembly(assName as AssemblyName) 931 if .referenceVerbosity 932 print '>> loadAssembly [assName]' 933 .indentPrint 934 try 935 _loadAssembly(assName) 936 finally 937 .outdentPrint 938 print '<< loadAssembly [assName]' 939 else 940 _loadAssembly(assName) 941 942 def _loadAssembly(assName as AssemblyName) 943 rv = .referenceVerbosity - 1 944 if rv < 0, rv = 0 945 if assName.toString in _didLoadAssemblies 946 if rv, print 'Already loaded.' 947 return 948 _didLoadAssemblies.add(assName.toString) 949 try 950 if rv, print 'Will Assembly.load([assName])' 951 ass = Assembly.load(assName) # Will not pick up the assembly from the same directory. 952 if rv, print 'Did Assembly.load with result: [ass]' 953 catch fnfe as FileNotFoundException # In fact, will get a FileNotFoundException! 954 if rv, print 'Did Assembly.load with exception: [fnfe]. Will try .loadReference' 955 .loadReference(assName.name + '.dll') 956 # TODO: compare the the name loaded to the name given with AssemblyName.referenceMatchesDefinition 957 return 958 catch exc as Exception 959 msg = 'Could not open assembly "[assName]" due to: [exc.getType.name]: [exc.message]' 960 if rv, print msg 961 throw SourceException(msg) 962 if _willReadDependencies 963 for dependency in ass.getReferencedAssemblies 964 if rv 965 print '>> Loading dependency: [dependency]' 966 .indentPrint 967 try 968 .loadAssembly(dependency) 969 finally 970 .outdentPrint 971 print '<< Loading dependency: [dependency]' 972 try 973 .readAssembly(ass) 974 catch readExc as Exception 975 if rv, print 'Caught exception during read assembly: [readExc]' 976 throw 977 978 1041 def fixNilableMemberSigs 1042 .backEnd.fixNilableMemberSigs 1043 1044 def installNativeMethods(box as Box, nativeType as NativeType) 1045 .backEnd.installNativeMethods(box, nativeType) 1046 979 1047 ## 980 1048 ## Binding 981 1049 ## … … 1177 1245 ## 1178 1246 ## Important system library types 1179 1247 ## 1180 1248 # ILibTypeProvider 1249 1181 1250 get objectType as IType 1182 1251 # for ITypeProvider 1183 return _libraryClass(' System.Object')1252 return _libraryClass('Object') 1184 1253 1185 1254 def objectClass as Class 1186 1255 # for stronger typing 1187 return _libraryClass(' System.Object')1256 return _libraryClass('Object') 1188 1257 1189 1258 def stringType as Class 1190 return _libraryClass('S ystem.String')1259 return _libraryClass('String') 1191 1260 1192 1261 def exceptionType as Class 1193 return _libraryClass(' System.Exception')1262 return _libraryClass('Exception') 1194 1263 1195 1264 def delegateType as Class 1196 return _libraryClass(' System.Delegate')1265 return _libraryClass('Delegate') 1197 1266 1198 1267 def attributeType as Box 1199 return _libraryBox(' System.Attribute')1268 return _libraryBox('Attribute') 1200 1269 1201 1270 def enumerableType as Box 1202 return _libraryBox(' System.Collections.IEnumerable')1271 return _libraryBox('IEnumerable') 1203 1272 1204 1273 def enumeratorType as Box 1205 return _libraryBox(' System.Collections.IEnumerator')1274 return _libraryBox('IEnumerator') 1206 1275 1207 1276 def enumerableOfType as Box 1208 return _libraryBox(' System.Collections.Generic.IEnumerable<of>')1277 return _libraryBox('IEnumerable<of>') 1209 1278 1210 1279 def enumeratorOfType as Box 1211 return _libraryBox(' System.Collections.Generic.IEnumerator<of>')1280 return _libraryBox('IEnumerator<of>') 1212 1281 1213 1282 def dictEnumeratorType as Box 1214 return _libraryBox(' System.Collections.IDictionaryEnumerator')1283 return _libraryBox('IDictionaryEnumerator') 1215 1284 1216 1285 def collectionType as Box 1217 return _libraryBox(' System.Collections.ICollection')1286 return _libraryBox('ICollection') 1218 1287 1219 1288 def collectionOfType as Box 1220 return _libraryBox(' System.Collections.Generic.ICollection<of>')1289 return _libraryBox('ICollection<of>') 1221 1290 1222 1291 def ilistType as Box 1223 return _libraryBox(' System.Collections.IList')1292 return _libraryBox('IList') 1224 1293 1225 1294 def ilistOfType as Box 1226 return _libraryBox(' System.Collections.Generic.IList<of>')1295 return _libraryBox('IList<of>') 1227 1296 1228 1297 def listOfType as Class 1229 return _libraryClass(' System.Collections.Generic.List<of>')1298 return _libraryClass('List<of>') 1230 1299 1231 1300 def idictionaryType as Box 1232 return _libraryBox(' System.Collections.IDictionary')1301 return _libraryBox('IDictionary') 1233 1302 1234 1303 def idictionaryOfType as Box 1235 return _libraryBox(' System.Collections.Generic.IDictionary<of,>')1304 return _libraryBox('IDictionary<of,>') 1236 1305 1237 1306 def dictionaryOfType as Class 1238 return _libraryClass(' System.Collections.Generic.Dictionary<of,>')1307 return _libraryClass('Dictionary<of,>') 1239 1308 1240 1309 def setOfType as Class 1241 return _libraryClass(' Cobra.Lang.Set<of>')1310 return _libraryClass('Set<of>') 1242 1311 1243 def libraryType(qualifiedName as String) as IType1312 def libraryType(qualifiedNameOrTag as String) as IType 1244 1313 """ 1245 1314 Implemented for ITypeProvider, but use the more specific methods such as .stringType instead. 1246 1315 """ 1247 return _libraryType( qualifiedName)1316 return _libraryType(.backEnd.resolveTypeTag(qualifiedNameOrTag)) 1248 1317 1249 1318 var _libraryTypeCache = Dictionary<of String, IType>() 1250 1319 1251 1320 def _libraryType(qualifiedName as String) as IType 1252 1321 """ 1322 find qualified Type name in (cache or) Library/namespace Decls structures. 1253 1323 Used to retrieve types such as System.String. 1254 1324 Example: 1255 1325 _libraryType('System.String') 1256 1326 """ 1327 assert qualifiedName.length 1257 1328 type as IType? 1258 1329 if _libraryTypeCache.tryGetValue(qualifiedName, out type) 1259 1330 return type to ! … … 1263 1334 return type to ! 1264 1335 1265 1336 def _libraryType(names as vari String) as IType 1337 #print names 1266 1338 ns as IContainer = _globalNS 1267 1339 thing as IContainer? = nil 1268 1340 for name in names 1341 #print (thing ? ns) 1269 1342 possible = (thing ? ns).declForName(name) 1270 1343 assert possible, name 1271 1344 if possible inherits IContainer … … 1282 1355 else 1283 1356 throw FallThroughException('found [name], but it is not an IType. it is [thing]') 1284 1357 1285 def _libraryBox(qualifiedName as String) as Box1358 def _libraryBox(qualifiedNameOrTag as String) as Box 1286 1359 """ 1287 1360 Returns a box from the standard library such as 'System.Object' or 'System.Collections.Generic.IEnumerable<of>'. 1288 1361 """ 1289 return _libraryType( qualifiedName) to Box1362 return _libraryType(.backEnd.resolveTypeTag(qualifiedNameOrTag)) to Box 1290 1363 1291 def _libraryClass(qualifiedName as String) as Class1364 def _libraryClass(qualifiedNameOrTag as String) as Class 1292 1365 """ 1293 1366 Returns a class from the standard library such as 'System.Object' or 'System.Collections.Generic.Dictionary<of,>'. 1294 1367 """ 1295 return _libraryType( qualifiedName) to Class1368 return _libraryType(.backEnd.resolveTypeTag(qualifiedNameOrTag)) to Class 1296 1369 1297 1370 1298 1371 ## … … 1302 1375 def embedRunTimeSuffix as String 1303 1376 return .options.embedRunTimeSuffix 1304 1377 1378 #special type proxies for common Types - Object and Type 1379 def objectTypeProxy as AbstractTypeProxy 1380 """ 1381 Type proxy for BE notion of a class for the root of Object hierarchy 1382 e.g. Object in dotNet 1383 """ 1384 #return ClrTypeProxy(Object) 1385 return .backEnd.objectTypeProxy 1386 1387 def typeTypeProxy as AbstractTypeProxy 1388 """ 1389 Type proxy for BE notion of a class for a Type 1390 e.g. System.Type in dotNet, java.lang.class in Java 1391 """ 1392 #return ClrTypeProxy(Type) 1393 return .backEnd.typeTypeProxy 1394 1305 1395 def nativeType(qualifiedName as String) as NativeType 1306 return ClrNativeType(_clrType(qualifiedName))1396 return .backEnd.nativeTypeByName(qualifiedName) 1307 1397 1308 def _clrType(qualifiedName as String) as System.Type1309 # eventually this method will be key in targeting different versions of the CLR1310 # suppose you are on .NET 3.0 and want to target .NET 2.01311 t as System.Type?1312 _clrTypeCache.tryGetValue(qualifiedName, out t)1313 if t is nil1314 t = sharp'System.Type.GetType(qualifiedName)' # to System.Type1315 _clrTypeCache[qualifiedName] = t to passthrough # "to passthrough" instead of "to !" to avoid non-nil check1316 return t to passthrough1317 1318 1398 def suggestionFor(name as String) as String? is shared 1319 1399 require name.length 1320 1400 # CC: return _unknownSuggestions.getDefault(name, nil) … … 1452 1532 on 'jvm', _backEnd = JvmBackEnd(this) 1453 1533 on 'objc', _backEnd = ObjcBackEnd(this) 1454 1534 else, throw FallThroughException(.options.get('back-end')) 1535 1455 1536 1456 1457 1537 class InternalError 1458 1538 inherits SourceException 1459 1539 """ … … 1510 1590 1511 1591 cue init 1512 1592 base.init(0) 1513 1593 _backEnd = BasicBackEnd(this) 1594 1514 1595 pro verbosity as int is override 1515 1596 get 1516 1597 return 0 … … 1521 1602 return lineNum 1522 1603 1523 1604 1524 extend String1525 1526 def fixLibExtension as String1527 require .length1528 ensure result.endsWith('.dll') or result.endsWith('.exe')1529 if not .endsWith('.dll') and not .endsWith('.exe')1530 return this + '.dll'1531 else1532 return this -
Source/Expr.cobra
1153 1153 definition = curBox.symbolForName(_name, true) 1154 1154 if definition 1155 1155 .throwError('You must refer to non-underscored members with a leading dot (.). Member name is "[_name]".') 1156 # hops 1157 #print _name, canBeUndottedMember, _definition 1158 if _definition is nil and _name == 'java' # TODO hops: handle thru .findDefinition 1159 #_definition = NameSpace(.token.copy('ID', 'java'), 'java') 1160 _definition = .compiler.passThroughType 1161 #print _name 1156 1162 if _definition is nil and (not _superNode inherits BinaryOpExpr or .binarySuperNode.op<>'ASSIGN') 1157 1163 .throwUnknownIdError 1158 1164 throw FallThroughException() -
Source/Boxes.cobra
35 35 var _nativeType as NativeType? 36 36 var _needScanNativeType as bool 37 37 var _membersToUnNil as String? 38 var _defaultMemberName as String?39 """40 An Indexer in CLR is known by being a property with arguments whose name matches the .memberName of a box-level DefaultMemberAttribute.41 """42 38 43 39 cue init(token as IToken, idToken as IToken, name as String, paramList as List<of IType>, isNames as String*, attribs as AttributeList, baseInterfaceNodes as List<of ITypeProxy>, docString as String?) 44 40 base.init(token, name, isNames, docString) … … 60 56 ensure .needScanNativeType 61 57 _nativeType = t 62 58 _needScanNativeType = true 63 _ scanGenericArgs59 _callNativeScanMethod('ScanGenericArgs') 64 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 code 66 # TODO: change to use strategy object set when init backend. 67 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]') 91 92 65 93 def addMinFields 66 94 base.addMinFields 67 95 .addField('didBindInh', .didBindInh) … … 194 222 195 223 # TODO: cache 196 224 get isSystemObjectClass as bool is override 197 # TODO-BACKEND198 return _ baseClass is nil and .name == 'Object' and .parentNameSpace and .parentNameSpace.fullName == 'System'225 #return _baseClass is nil and .name == 'Object' and .parentNameSpace and .parentNameSpace.fullName == 'System' 226 return _nativeType and _nativeType.isSystemObjectClass 199 227 200 228 get isSystemTypeClass as bool is override 201 # TODO-BACKEND202 return .name == 'Type' and .parentNameSpace and .parentNameSpace.fullName == 'System'229 #return .name == 'Type' and .parentNameSpace and .parentNameSpace.fullName == 'System' 230 return _nativeType and _nativeType.isSystemTypeClass 203 231 204 get isSystemExceptionClass as bool205 # TODO-BACKEND206 return .name == 'Exception' and .parentNameSpace and .parentNameSpace.fullName == 'System'207 208 232 pro membersToUnNil from var 209 233 210 234 get nativeType from var … … 568 592 return r 569 593 570 594 ## Binding 571 595 def _scanNativeType 596 #print '_scanNativeType ', .name 597 _callNativeScanMethod('ScanNativeType') 598 572 599 def _stackPush 573 600 base._stackPush 574 601 if .compiler, .compiler.boxStack.push(this) … … 647 674 # Therefore, everthing below has already happened for a constructed box's generic def. 648 675 base._bindInt 649 676 if .isSystemObjectClass 650 .prepSystemObjectClass677 _callNativeScanMethod('prepSysObjClass') 651 678 errorCount = .compiler.errors.count 652 if _needScanNativeType 653 _scanNativeType 679 if _needScanNativeType, _scanNativeType 654 680 if _baseClass 655 681 _baseClass.bindInt 656 682 for interf in _baseInterfaces … … 694 720 ct.completeMemberConstructionIfNeeded 695 721 ct.bindInt 696 722 697 def prepSystemObjectClass698 # TODO: fix native699 # Pretend .NET is a bit more OO, consistent and elegant.700 # C#'s typeof(X) is X.getType in Cobra.701 existing = .declForName('getType') to BoxMember702 overload = MemberOverload(existing)703 .registerOverload(overload)704 meth = Method(TokenFix.empty, TokenFix.empty, this, 'getType', List<of Param>(), ClrTypeProxy(Type), nil, ['shared'], AttributeList(), 'Returns the Type instance that defines this type.')705 meth.sharedMethodBacking = 'typeof'706 overload.addMember(meth)707 708 723 def _bindBase 709 724 # invoked by _bindInt 710 725 _baseClass = .compiler.objectClass … … 1180 1195 base.init(token, idToken, name, paramList, isNames, attribs, implementsNodes, addsProxies, docString) 1181 1196 _baseNode = baseNode 1182 1197 1183 cue init(nativeType as NativeType )1198 cue init(nativeType as NativeType, backend as BackEnd) 1184 1199 # TODO: fix native 1185 base.init(TokenFix.empty, TokenFix.empty, ClrTypeProxy.cobraNameForSharpBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), List<of ITypeProxy>(), nil)1200 base.init(TokenFix.empty, TokenFix.empty, backend.cobraNameForNativeBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), List<of ITypeProxy>(), nil) 1186 1201 if nativeType.baseType 1187 _baseNode = ClrTypeProxy(nativeType.baseType to ClrNativeType) # TODO: fix native. Change to NativeTypeProxy1202 _baseNode = backend.nativeTypeProxy(nativeType.baseType to !) 1188 1203 _initNativeType(nativeType) 1189 1204 1190 1205 def addRefFields 1191 1206 base.addRefFields 1192 1207 .addField('baseNode', _baseNode) … … 1336 1351 init.changeToPublic 1337 1352 break 1338 1353 1354 get isSystemObjectClass as bool is override 1355 return _nativeType and _nativeType.isSystemObjectClass 1356 1357 get isSystemTypeClass as bool is override 1358 return _nativeType and _nativeType.isSystemTypeClass 1359 1339 1360 def _finishOverloads 1340 1361 # deal with inheritance and overloads 1341 1362 assert _baseClass or .isSystemObjectClass … … 1428 1449 cue init(token as IToken, idToken as IToken, name as String, paramList as List<of IType>, isNames as String*, attribs as AttributeList, baseNodes as List<of ITypeProxy>, docString as String?) 1429 1450 base.init(token, idToken, name, paramList, isNames, attribs, baseNodes, docString) 1430 1451 1431 cue init(nativeType as NativeType )1432 base.init(TokenFix.empty, TokenFix.empty, ClrTypeProxy.cobraNameForSharpBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), nil)1452 cue init(nativeType as NativeType, backend as BackEnd) 1453 base.init(TokenFix.empty, TokenFix.empty, backend.cobraNameForNativeBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), nil) 1433 1454 _initNativeType(nativeType) 1434 1455 1435 1456 get canHaveStatements as bool is override … … 1467 1488 cue init(token as IToken, idToken as IToken, name as String, paramList as List<of IType>, isNames as String*, attribs as AttributeList, baseName as String?, interfaceNodes as List<of ITypeProxy>, addsProxies as List<of ITypeProxy>, docString as String?) 1468 1489 base.init(token, idToken, name, paramList, isNames, attribs, interfaceNodes, addsProxies, docString) 1469 1490 1470 cue init(nativeType as NativeType )1471 base.init(TokenFix.empty, TokenFix.empty, ClrTypeProxy.cobraNameForSharpBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), List<of ITypeProxy>(), nil)1491 cue init(nativeType as NativeType, backend as BackEnd) 1492 base.init(TokenFix.empty, TokenFix.empty, backend.cobraNameForNativeBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), List<of ITypeProxy>(), nil) 1472 1493 _initNativeType(nativeType) 1473 1494 1474 1495 get englishName as String is override … … 1805 1826 _name = '(unnamed extension [.serialNum])' 1806 1827 _extendedBoxProxy = extendedBoxProxy 1807 1828 1808 cue init(nativeType as NativeType )1829 cue init(nativeType as NativeType, backend as BackEnd) 1809 1830 # this only for Cobra specific extensions. Example: class Extend_String_FileName 1810 base.init(TokenFix.empty, TokenFix.empty, ClrTypeProxy.cobraNameForSharpBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), nil)1831 base.init(TokenFix.empty, TokenFix.empty, backend.cobraNameForNativeBoxName(nativeType.name), List<of IType>(), List<of String>(), AttributeList(), List<of ITypeProxy>(), nil) 1811 1832 _initNativeType(nativeType) 1812 1833 # the real extended type is not this type, but the type of the first argument of any method 1813 for methInfo in .clrType.getMethods # TODO: fix native. break this out to a method 1814 nativeType = ClrNativeType(methInfo.getParameters[0].parameterType) 1815 break 1816 _extendedBoxProxy = ClrTypeProxy(nativeType) 1834 branch backend.name 1835 on 'c#-clr', nativeType = .clrExtnNativeType(nativeType) # ScanClrType 1836 on 'java-jvm', nativeType = .jvmExtnNativeType(nativeType) # ScanJvmType 1837 on 'objc' 1838 print 'objc back end need method objcExtnNativeType' 1839 assert false, 'Missing backEnd infrastructure for [backend.getType.name]' 1840 else 1841 throw FallThroughException('No extnNativeType code for backend [backend.name] [backend.getType.name]') 1842 #nativeType = backEnd.determineExtnNativeType(nativeType) 1843 _extendedBoxProxy = backend.nativeTypeProxy(nativeType) 1817 1844 (.compiler.curModule to AssemblyModule).addMustBindInh(this) 1818 1845 1819 1846 get extendedBox from var -
Source/Cobra.Lang/java/CobraCore.java
1 /* 2 * CobraCore.java 3 * 4 * Java code implementation of RTL support code and code 5 * thats needed for simple cobra apps (in java) prior to 6 * cobra library code generated into java. 7 * 8 * Eventually contents of this file will be all cobra. 9 */ 10 package cobra.lang; 11 12 public class CobraCore { 13 14 public static Boolean _willCheckInvariant = true; 15 public static Boolean _willCheckRequire = true; 16 public static Boolean _willCheckEnsure = true; 17 public static Boolean _willCheckAssert = true; 18 public static Boolean _willCheckNil = true; 19 20 public static int noOp(/* allowNull */ Object... args) { 21 /* """ 22 No operation. Primarily used in Cobra's own test suite to consume a local variable to avoid undesired warnings. 23 Takes any number of values and returns an undefined value of type `dynamic?` for maximum flexibility. 24 """ */ 25 26 return 0; 27 } 28 29 /* 30 def runAllTests 31 """ 32 Run all Cobra `test` sections in all assemblies using reflection to locate them. 33 """ 34 if CobraImp.showTestProgress, listener = Cobra.Lang.Test.TextWriterListener(Console.out) 35 else, listener = Cobra.Lang.Test.TextWriterOnlyOnFailureListener(Console.out) 36 tr = Cobra.Lang.Test.TestRunner(listener) 37 tr.runAllTests 38 if listener.testFailures, CobraCore.exit(1) 39 */ 40 public static void runAllTests() 41 { 42 CobraImp.printLine("stub:running all tests..."); 43 } 44 45 public static void printDebuggingTips() 46 { 47 CobraImp.printLine("An unhandled exception has occurred."); 48 CobraImp.printLine(); 49 CobraImp.printLine( "Cobra debugging tips:"); 50 CobraImp.printLine( " To get file name and line number information for the stack frames, use:"); 51 CobraImp.printLine( " cobra -debug foo.cobra"); 52 CobraImp.printLine( " To get a post-mortem, HTML-formatted report with more details about your objects:"); 53 CobraImp.printLine( " cobra -debug -exception-report foo.cobra"); 54 CobraImp.printLine( " For even more information, try:"); 55 CobraImp.printLine( " cobra -debug -exception-report -detailed-stack-trace foo.cobra"); 56 CobraImp.printLine( " Or use the abbreviations:"); 57 CobraImp.printLine( " cobra -d -er -dst foo.cobra"); 58 // TODO: CobraImp.printLine( " See also: http://cobra-language.com/docs/debugging"); 59 CobraImp.printLine(); 60 } 61 } 62 -
Source/Cobra.Lang/java/AssertException.java
1 /* 2 * java code for cobra assert exception ( placeholder currently) 3 * in process of Converting from cobra to java code 4 * Initially using java assertion till this is working 5 */ 6 7 package cobra.lang; 8 9 import java.util.List; 10 11 12 class AssertException extends Exception implements IHasSourceSite, HasAppendNonPropertyKeyValues 13 // has DetailedStackTrace(false) 14 { 15 Object _this; 16 Object _info; /* dynamic */ 17 SourceSite _sourceSite; 18 java.util.List<Object> _expressions; 19 20 AssertException(SourceSite sourceSite, java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*dynamic? */) 21 { 22 this(sourceSite, expressions, thiss, info, nil) 23 } 24 25 AssertException(SourceSite sourceSite, java.util.List<Object> expressions /*dynamic */, Object thiss, Object info /*as dynamic?*/, Exception innerExc) 26 { 27 super('assert', innerExc) 28 _sourceSite = sourceSite 29 _expressions = expressions 30 _this = thiss 31 _info = info 32 } 33 // UNFINISHED 34 35 Object getThis { return _this; } 36 37 Object getInfo { return _info; } 38 39 SourceSite getSourceSite { return _sourceSite; } 40 41 List<Object> getExpressions { return _expressions; } 42 43 @Override 44 String getMessage() 45 { 46 nl = System.properties.newLine 47 StringBuilder sb = new StringBuilder(nl); 48 sb.append('sourceSite = [.sourceSite][nl]'); 49 sb.append('info = [.makeString(.info)][nl]'); 50 sb.append('this = [.makeString(.this)][nl]'); 51 int indentLevel = 1; 52 int i = 1; 53 List<Object> exprs = _expressions; 54 while (i < exprs.size) { 55 Object item = exprs.get(i)); 56 if (item == +1) { 57 indentLevel += 1; 58 i += 1; 59 } 60 else if (item == -1) { 61 indentLevel -= 1; 62 i += 1; 63 } 64 else { 65 String source = (String)item; 66 Object value = exprs.get(i+1); 67 dirStr = value to? CobraDirectString 68 valueString = if(dirStr, dirStr.string, .makeString(value)) 69 sb.append(String(' ', indentLevel*4)) 70 sb.append('[source] = [valueString][nl]'); 71 i += 2; 72 } 73 } 74 75 return sb.toString 76 } 77 78 String makeString(Object obj /*dynamic? */) 79 { 80 String s; 81 try { 82 s = CobraCore.techStringMaker.makeString(obj); 83 } 84 catch (Exception e) { 85 s = 'CobraCore.techStringMaker.makeString exception: ' + e.message; 86 } 87 return s; 88 } 89 90 def appendNonPropertyKeyValues(target as HasAppendKeyValue ) 91 # Invoked by the Cobra Exception Report and CobraMain-ObjectExplorer-WinForms 92 # By adding the expression breakdown as entries in the view, 93 # object values will be clickable which will lead to their own detailed view. 94 indentLevel = 0 95 target.appendKeyValue('expression breakdown:', Html('')) 96 i, exprs = 1, _expressions 97 while i < exprs.count 98 item = exprs[i] 99 if item == +1 100 indentLevel += 1 101 i += 1 102 else if item == -1 103 indentLevel -= 1 104 i += 1 105 else 106 source = item to String 107 value = exprs[i+1] 108 target.appendKeyValue(String(c' ', indentLevel*4)+source, value) 109 i += 2 110 111 def populateTreeWithExpressions(tree as ITreeBuilder) 112 # Invoked by the Object Explorer, but any tool could use this by implementing ITreeBuilder. 113 # By adding the expression breakdown as entries in the view, 114 # object values will be clickable which will lead to their own detailed view. 115 i, exprs = 1, _expressions 116 while i < exprs.count 117 item = exprs[i] 118 if item == +1 119 tree.indent 120 i += 1 121 else if item == -1 122 tree.outdent 123 i += 1 124 else 125 source = item to String 126 value = exprs[i+1] 127 tree.appendKeyValue(source, value) 128 i += 2 129 130 131 132 133 134 /* 135 ## Exceptions about dynamic 136 137 class DynamicOperationException inherits Exception 138 """ 139 The base class for all dynamic operation exceptions. 140 """ 141 142 cue init(message as String?) 143 .init(message, nil) 144 145 cue init(message as String?, innerExc as Exception?) 146 base.init(message, innerExc) 147 148 class CannotEnumerateException inherits DynamicOperationException 149 150 # CC: axe init()s 151 152 cue init(message as String?) 153 .init(message, nil) 154 155 cue init(message as String?, innerExc as Exception?) 156 base.init(message, innerExc) 157 158 159 class UnknownMemberException inherits DynamicOperationException 160 161 var _obj as Object 162 var _name as String 163 var _type as Type 164 165 cue init(obj as Object, name as String, type as Type) 166 .init(obj, name, type, nil) 167 168 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 169 base.init('obj=[CobraCore.toTechString(obj)], name=[CobraCore.toTechString(name)], type=[type]', innerExc) 170 _obj = obj 171 _name = name 172 _type = type 173 174 175 class CannotReadPropertyException inherits UnknownMemberException 176 177 # CC: axe init()s 178 179 cue init(obj as Object, name as String, type as Type) 180 .init(obj, name, type, nil) 181 182 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 183 base.init(obj, name, type, innerExc) 184 185 186 class CannotWritePropertyException inherits UnknownMemberException 187 188 # CC: axe init()s 189 190 cue init(obj as Object, name as String, type as Type) 191 .init(obj, name, type, nil) 192 193 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 194 base.init(obj, name, type, innerExc) 195 196 197 class CannotSliceTypeException inherits UnknownMemberException 198 199 # CC: axe init()s 200 201 cue init(obj as Object, name as String, type as Type) 202 .init(obj, name, type, nil) 203 204 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 205 base.init(obj, name, type, innerExc) 206 207 208 class CannotInTypeException inherits UnknownMemberException 209 210 # CC: axe init()s 211 212 cue init(obj as Object, name as String, type as Type) 213 .init(obj, name, type, nil) 214 215 cue init(obj as Object, name as String, type as Type, innerExc as Exception?) 216 base.init(obj, name, type, innerExc) 217 218 219 class CannotCompareException inherits DynamicOperationException 220 221 var _a 222 var _b 223 224 cue init(a, b) 225 .init(a, b, nil) 226 227 cue init(a, b, innerExc as Exception?) 228 base.init('a=[a], b=[b]', innerExc) 229 #base.init('a=[CobraCore.toTechString(a)], a.getType=[a.getType.name], b=[CobraCore.toTechString(b)], b.getType=[b.getType.name]', innerExc) 230 _a = a 231 _b = b 232 233 234 ## Assertions, contracts, etc. 235 236 class AssertException inherits Exception implements IHasSourceSite, HasAppendNonPropertyKeyValues 237 has DetailedStackTrace(false) 238 239 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?) 240 .init(sourceSite, expressions, thiss, info, nil) 241 242 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?) 243 base.init('assert', innerExc) 244 _sourceSite = sourceSite 245 _expressions = expressions 246 _this = thiss 247 _info = info 248 249 get this from var as Object 250 251 get info from var as dynamic? 252 253 get sourceSite from var as SourceSite 254 255 get expressions from var as IList<of dynamic> 256 257 get message as String? is override 258 nl = Environment.newLine 259 sb = StringBuilder(nl) 260 sb.append('sourceSite = [.sourceSite][nl]') 261 sb.append('info = [.makeString(.info)][nl]') 262 sb.append('this = [.makeString(.this)][nl]') 263 i = indentLevel = 1 264 exprs = _expressions 265 while i < exprs.count 266 item = exprs[i] 267 if item == +1 268 indentLevel += 1 269 i += 1 270 else if item == -1 271 indentLevel -= 1 272 i += 1 273 else 274 source = item to String 275 value = exprs[i+1] 276 dirStr = value to? CobraDirectString 277 valueString = if(dirStr, dirStr.string, .makeString(value)) 278 sb.append(String(c' ', indentLevel*4)) 279 sb.append('[source] = [valueString][nl]') 280 i += 2 281 282 return sb.toString 283 284 def makeString(obj as dynamic?) as String 285 try 286 s = CobraCore.techStringMaker.makeString(obj) 287 catch e as Exception 288 s = 'CobraCore.techStringMaker.makeString exception: ' + e.message 289 return s 290 291 def appendNonPropertyKeyValues(target as HasAppendKeyValue ) 292 # Invoked by the Cobra Exception Report and CobraMain-ObjectExplorer-WinForms 293 # By adding the expression breakdown as entries in the view, 294 # object values will be clickable which will lead to their own detailed view. 295 indentLevel = 0 296 target.appendKeyValue('expression breakdown:', Html('')) 297 i, exprs = 1, _expressions 298 while i < exprs.count 299 item = exprs[i] 300 if item == +1 301 indentLevel += 1 302 i += 1 303 else if item == -1 304 indentLevel -= 1 305 i += 1 306 else 307 source = item to String 308 value = exprs[i+1] 309 target.appendKeyValue(String(c' ', indentLevel*4)+source, value) 310 i += 2 311 312 def populateTreeWithExpressions(tree as ITreeBuilder) 313 # Invoked by the Object Explorer, but any tool could use this by implementing ITreeBuilder. 314 # By adding the expression breakdown as entries in the view, 315 # object values will be clickable which will lead to their own detailed view. 316 i, exprs = 1, _expressions 317 while i < exprs.count 318 item = exprs[i] 319 if item == +1 320 tree.indent 321 i += 1 322 else if item == -1 323 tree.outdent 324 i += 1 325 else 326 source = item to String 327 value = exprs[i+1] 328 tree.appendKeyValue(source, value) 329 i += 2 330 331 332 class InvariantException inherits AssertException 333 334 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?) 335 .init(sourceSite, expressions, thiss, info, nil) 336 337 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?) 338 base.init(sourceSite, expressions, thiss, info, innerExc) 339 340 341 class RequireException inherits AssertException 342 343 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?) 344 .init(sourceSite, expressions, thiss, info, nil) 345 346 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?) 347 base.init(sourceSite, expressions, thiss, info, innerExc) 348 349 pro next from var as RequireException? 350 351 352 class EnsureException inherits AssertException 353 354 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?) 355 .init(sourceSite, expressions, thiss, info, nil) 356 357 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?) 358 base.init(sourceSite, expressions, thiss, info, innerExc) 359 360 361 class NonNilCastException inherits AssertException 362 363 # it's unfortunate that we have to choose between inheriting AssertException or NullReferenceException 364 365 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?) 366 .init(sourceSite, expressions, thiss, info, nil) 367 368 cue init(sourceSite as SourceSite, expressions as IList<of dynamic>, thiss as Object, info as dynamic?, innerExc as Exception?) 369 base.init(sourceSite, expressions, thiss, info, innerExc) 370 371 get message as String? is override 372 return 'Cast to non-nil failed.[Environment.newLine][base.message]' 373 374 375 ## Misc exceptions 376 377 class ExpectException inherits Exception 378 379 cue init(expectedExceptionType as Type, actualException as Exception?) 380 base.init 381 _expectedExceptionType = expectedExceptionType 382 _actualException = actualException 383 384 get expectedExceptionType from var as Type 385 386 get actualException from var as Exception? 387 388 get message as String? is override 389 sb = StringBuilder() 390 sb.append('Expecting exception: [_expectedExceptionType.name], but ') 391 if _actualException 392 sb.append('a different exception was thrown: [_actualException]') 393 else 394 sb.append('no exception was thrown.') 395 return sb.toString 396 397 398 class FallThroughException inherits Exception 399 400 cue init 401 .init(nil) 402 pass 403 404 cue init(info as Object?) 405 base.init 406 _info = info 407 408 cue init(info as Object?, innerExc as Exception?) 409 base.init(nil, innerExc) 410 _info = info 411 412 get message as String is override 413 return 'info=[CobraCore.toTechString(_info)]' 414 415 get info from var as Object? 416 417 418 class SliceException inherits SystemException 419 420 cue init(msg as String?) 421 base.init 422 */ 423 } 424 No newline at end of file -
Source/Cobra.Lang/java/mkjar
1 #!bash 2 # Build script for java sources for cobra 3 # Compile java source classes for java cobra RTL 4 # copy them and std sig files to Source dir 5 6 [ -d classes ] || mkdir classes 7 javac -d classes CobraImp.java CobraCore.java 8 [ $? == 0 ] || exit 9 jar cvf CobraLang.jar -C classes . 10 [ $? == 0 ] || exit 11 cp CobraLang.jar ../.. 12 13 #java -cp '.;CobraLang.jar' PkgSig -j CobraLang.jar > CobraLang.jar.sig 14 ## assume rt.jar, java.util and java.lang sigfiles already exist and are static 15 #cp CobraLang.jar.sig rt.jar.sig java.util.sig java.lang.sig ../.. -
Source/Cobra.Lang/java/PkgSig.java
1 /* 2 * Generate a cobra package signature file 3 * compile: javac -cp . PkgSig.java 4 * run: 5 * generate sigfile for pkg in CLASSPATH 6 * java -cp . PkgSig <pkgname> # generates to stdout 7 * e.g java -cp . PkgSig java.lang 8 * run generating pkgSig file: 9 * java -cp . PkgSig <pkgname> > <pkgname>.sig 10 * e.g java -cp . PkgSig java.lang > java.lang.sig 11 * generate sigfile for jarfile - relative pathnames searched for in dirs in CLASSPATH 12 * java -cp . PkgSig -j <jarfile> # generates to stdout 13 * e.g java -cp . PkgSig -j rt.jar > rt.jar.sig 14 * java -cp . PkgSig -j /JavaLibs/bsh-2.0b4.jar 15 * 16 * 17 * TODO 18 * add cmdline flag generating pkgSig file w/o redirection: 19 * java -cp . PkgSig -cobra <pkgname> 20 * Cleanup and javadoc this file. 21 * Put a PkgSig version and timestamp in the pkgSigFile 22 */ 23 24 import java.io.*; 25 import java.util.*; 26 import java.util.jar.*; 27 import java.net.*; 28 29 import java.lang.reflect.*; 30 31 /** 32 * This abstract class can be used to obtain a list of all classes in a classpath. 33 * 34 * <em>Caveat:</em> When used in environments which utilize multiple class loaders--such as 35 * a J2EE Container like Tomcat--it is important to select the correct classloader 36 * otherwise the classes returned, if any, will be incompatible with those declared 37 * in the code employing this class lister. 38 * to get a reference to your classloader within an instance method use: 39 * <code>this.getClass().getClassLoader()</code> or 40 * <code>Thread.currentThread().getContextClassLoader()</code> anywhere else 41 * <p> 42 * @author Kris Dover <krisdover@hotmail.com> 43 * @version 0.2.0 44 * @since 0.1.0 45 * 46 * Downloaded from: 47 * 48 * Modified to output just class contents per cobra compiler requirements 49 * Mike Hopkirk Mar-2011 50 */ 51 public abstract class PkgSig { 52 53 static public class ClassComparator implements Comparator<Class> { 54 public int compare( Class cl, Class cl1) { 55 String n0 = cl.getName(); 56 String n1 = cl1.getName(); 57 return n0.compareTo(n1); 58 } 59 } 60 61 /** 62 * Convenience for lookup for a single package name. 63 * <p> 64 * @param pkg String name of a package to look for classes for 65 * @return A Set of Classes 66 * 67 * @throws ClassNotFoundException if the current thread's classloader cannot load 68 * a requested class for any reason 69 */ 70 public static Set<Class> findClassesForPkg(String pkg) throws ClassNotFoundException { 71 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 72 assert loader != null; 73 Set<String> pf = new HashSet<String>(); 74 System.out.println("# PkgSig file for '" + pkg+ "'"); 75 pf.add(pkg); 76 return findClasses(loader, pf, null); 77 } 78 79 /** 80 * Searches the classpath for all classes matching a specified search criteria, 81 * returning them in a map keyed with the interfaces they implement or null if they 82 * have no interfaces. The search criteria can be specified via interface, package 83 * and jar name filter arguments 84 * <p> 85 * @param classLoader The classloader whose classpath will be traversed 86 * @param packageFilter A Set of fully qualified package names to search for or 87 * or null to return classes in all packages 88 * @param jarFilter A Set of jar file names to search for or null to return 89 * classes from all jars 90 * @return A Set of Classes 91 * 92 * @throws ClassNotFoundException if the current thread's classloader cannot load 93 * a requested class for any reason 94 */ 95 @SuppressWarnings("unchecked") 96 public static Set<Class> findClasses(ClassLoader classLoader, 97 Set<String> packageFilter, 98 Set<String> jarFilter) throws ClassNotFoundException { 99 Set<Class> allClasses = new java.util.concurrent.ConcurrentSkipListSet(new PkgSig.ClassComparator()); 100 Object[] classPaths = getClassPaths(classLoader); 101 102 for (int h = 0; h < classPaths.length; h++) { 103 Enumeration files = null; 104 JarFile module = null; 105 // for each classpath ... 106 File classPath = new File( (URL.class).isInstance(classPaths[h]) ? 107 ((URL)classPaths[h]).getFile() : classPaths[h].toString() ); 108 if ( classPath.isDirectory() /*&& jarFilter == null*/){ // is our classpath a directory and jar filters are not active? 109 List<String> dirListing = new ArrayList(); 110 // get a recursive listing of this classpath 111 recursivelyListDir(dirListing, classPath, new StringBuffer() ); 112 // an enumeration wrapping our list of files 113 files = Collections.enumeration( dirListing ); 114 } else if( classPath.getName().endsWith(".jar") ) { // is our classpath a jar? 115 // skip any jars not list in the filter 116 if (! classPath.exists()) 117 continue; 118 119 if ( jarFilter != null && !jarFilter.contains( classPath.getName() ) ) 120 continue; 121 122 try { 123 // if our resource is a jar, instantiate a jarfile using the full path to resource 124 module = new JarFile( classPath ); 125 } catch (MalformedURLException mue){ 126 throw new ClassNotFoundException("Bad classpath. Error: " + mue.getMessage()); 127 } catch (IOException io){ 128 throw new ClassNotFoundException("jar file '" + classPath.getName() + 129 "' could not be instantiated from file path. Error: " + io.getMessage()); 130 } 131 System.out.println("# jarfile=" + module.getName()); 132 // get an enumeration of the files in this jar 133 files = module.entries(); 134 } 135 136 // for each file path in our directory or jar 137 while( files != null && files.hasMoreElements() ){ 138 String fileName = files.nextElement().toString(); // get each fileName 139 140 if ( fileName.endsWith(".class") ) { 141 processFile(fileName, classLoader, packageFilter, null, allClasses); 142 } 143 else if ( fileName.endsWith(".jar") ) { 144 if ( jarFilter == null || jarFilter.contains( fileName )) { 145 String pathName = classPath + File.separator + fileName; 146 processJarFile(pathName, classLoader, packageFilter, null, allClasses); 147 } 148 } 149 } 150 151 // close the jar if it was used 152 if (module != null){ 153 try { 154 module.close(); 155 } catch(IOException ioe) { 156 throw new ClassNotFoundException("The module jar file '" + classPath.getName() + 157 "' could not be closed. Error: " + ioe.getMessage()); 158 } 159 } 160 } // end classpath for loop 161 return allClasses; 162 } // end method 163 164 static private Object[] getClassPaths( ClassLoader classLoader) 165 { 166 Object[] classPaths; 167 ArrayList<Object> al; 168 try { 169 // get a list of all classpaths fm classloader 170 classPaths = ((java.net.URLClassLoader) classLoader).getURLs(); 171 } catch (ClassCastException cce){ 172 // or cast failed; tokenize the system classpath 173 classPaths = System.getProperty("java.class.path", "").split(File.pathSeparator); 174 } 175 al = new ArrayList<Object>(Arrays.asList(classPaths)); 176 // alternative to above from classpath setting 177 //classPaths = System.getProperty("java.class.path", "").split(File.pathSeparator); 178 //al.addAll(Arrays.asList(classPaths)); 179 //System.out.printf("# java.class.paths\n"); 180 //for (Object o : classPaths) 181 // System.out.printf("# %s\n", o.toString()); 182 183 //classPaths = System.getProperty("java.ext.dirs", "").split(File.pathSeparator); 184 // calc fm java home - lotta jarfiles under here tho 185 //String jHome = System.getProperty("java.home", ""); 186 //jHome = jHome + File.separator + "lib"; 187 //classPaths = new Object[]{jHome}; 188 189 classPaths = System.getProperty("sun.boot.class.path", "").split(File.pathSeparator); 190 al.addAll(Arrays.asList(classPaths)); 191 // Print classpath searching along 192 //System.out.printf("# sun.boot.class.paths\n"); 193 //for (Object o : classPaths) 194 // System.out.printf("# %s\n", o.toString()); 195 //return classPaths; 196 System.out.printf("# Class paths and boot paths being searched\n"); 197 for (Object o : al) 198 System.out.printf("# %s\n", o.toString()); 199 return al.toArray(); 200 } 201 202 203 /** 204 * Recursively lists a directory while generating relative paths. This is a helper function for findClasses. 205 * Note: Uses a StringBuffer to avoid the excessive overhead of multiple String concatentation 206 * 207 * @param dirListing A list variable for storing the directory listing as a list of Strings 208 * @param dir A File for the directory to be listed 209 * @param relativePath A StringBuffer used for building the relative paths 210 */ 211 private static void recursivelyListDir(List<String> dirListing, File dir, StringBuffer relativePath){ 212 int prevLen; // used to undo append operations to the StringBuffer 213 214 // if the dir is really a directory 215 if ( dir.isDirectory() ) { 216 File[] files = dir.listFiles(); // get a list of the files in this directory 217 // for each file in the present dir 218 for (int i = 0; i < files.length; i++) { 219 // store our original relative path string length 220 prevLen = relativePath.length(); 221 // call this function recursively with file list from present 222 // dir and relateveto appended with present dir 223 recursivelyListDir(dirListing, files[i], relativePath.append( prevLen == 0 ? "" : "/" ).append( files[i].getName() ) ); 224 // delete subdirectory previously appended to our relative path 225 relativePath.delete(prevLen, relativePath.length()); 226 } 227 } else { 228 // this dir is a file; append it to the relativeto path and add it to the directory listing 229 dirListing.add( relativePath.toString() ); 230 } 231 } 232 233 234 @SuppressWarnings("unchecked") 235 static private void processFile( String fileName, 236 ClassLoader classLoader, 237 Set<String> packageFilter, 238 Set<String> suppressFilter, 239 Set<Class> allClasses) throws ClassNotFoundException { 240 // convert our full filename to a fully qualified class name without trailing ".class" 241 String className = fileName.replaceAll("/", ".").substring(0, fileName.length() - 6); 242 // debug class list 243 //System.out.println(className); 244 // skip any classes in packages not explicitly requested in our package filter 245 if ( packageFilter != null) { 246 int li = className.lastIndexOf("."); 247 if (li < 0 || (li > 0 && !packageFilter.contains(className.substring( 0, li)))) 248 //System.out.println("skip " + className + " " + li); 249 return; 250 } 251 252 // suppress filtered package contents 253 if ( suppressFilter != null) { 254 for (String head : suppressFilter) { 255 if (className.startsWith(head)) { 256 //System.out.println("suppress " + className); 257 return; 258 } 259 } 260 } 261 262 // get the class for our class name 263 Class theClass = null; 264 try { 265 theClass = Class.forName(className, false, classLoader); 266 } 267 catch (NoClassDefFoundError e){ 268 System.out.println("Skipping class '" + className + "' for reason " + e.getMessage()); 269 return; 270 } 271 catch (ClassNotFoundException cnfe) { 272 System.out.println("LOAD ERROR: Cannot find/load class '" + className + "'"); 273 System.out.println("Ensure the jarfile or class directory containig the class is given in the classpath"); 274 System.out.printf("e.g. java -cp '.%smy.jar' PkgSig -j my.jar\n", File.pathSeparator); 275 System.out.printf(" java -cp '.%s./java' PkgSig com.mySource\n\n", File.pathSeparator); 276 throw cnfe; 277 } 278 279 int m = theClass.getModifiers(); 280 //if( java.lang.reflect.Modifier.isPublic(m) ) 281 //if( ! java.lang.reflect.Modifier.isPrivate(m) ) 282 if( Modifier.isPublic(m) || Modifier.isProtected(m) ) 283 allClasses.add( theClass ); 284 285 // skip interfaces 286 //if( theClass.isInterface() ){ 287 // continue; 288 //} 289 //accumulateInterfaces(theClass, classTable); 290 } 291 292 293 @SuppressWarnings("unchecked") 294 static private void processJarFile( String fileName, 295 ClassLoader classLoader, 296 Set<String> packageFilter, 297 Set<String> suppressFilter, 298 Set<Class> allClasses) throws ClassNotFoundException 299 { 300 JarFile module = null; 301 try { 302 module = new JarFile( fileName ); 303 } catch (MalformedURLException mue){ 304 throw new ClassNotFoundException("Bad classpath. Error: " + mue.getMessage()); 305 } catch (IOException io){ 306 throw new ClassNotFoundException("jar file '" + fileName + 307 "' could not instantiate Jar from file path. Error: " + io.getMessage()); 308 } 309 System.out.println("# jarfile: "+ module.getName()); 310 Enumeration files = module.entries(); 311 while( files != null && files.hasMoreElements() ){ 312 String fileNameEl = files.nextElement().toString(); 313 if ( fileNameEl.endsWith(".class") ) { 314 //System.out.println("#file:"+fileNameEl); 315 processFile(fileNameEl, classLoader, packageFilter, suppressFilter, allClasses); 316 } 317 } 318 319 if (module != null) { 320 try { 321 module.close(); 322 } catch(IOException ioe) { 323 throw new ClassNotFoundException("The module jar file '" + fileName + 324 "' could not be closed. Error: " + ioe.getMessage()); 325 } 326 } 327 } 328 329 // --- New cobra stuff from here 330 331 public static void usage() { 332 System.out.println("Unknown usage"); 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 "); 336 System.out.printf("A class signature is the class name, its superclass and signatures for fields and methods of the class.\n"); 337 System.out.printf("Packages are searched for in files and jars in classpath.\n"); 338 System.out.printf("Jarfiles are specified as relative or absolute pathnames. Relative pathname Jarfiles not found are searched for in the classpath\n"); 339 System.out.printf("Output format is suitable for parsing and use by the cobra java backend (cross) compiler.\n"); 340 System.exit(2); 341 } 342 343 public static File lookForJarFile( String fileName, ClassLoader loader) { 344 File jarFile = new File(fileName); 345 if ( jarFile.exists()) 346 return jarFile; 347 348 // search for jarfile in Classpath 349 if ( ! jarFile.isAbsolute() ) { 350 Object[] classPaths = getClassPaths(loader); 351 //for (int h = 0; h < classPaths.length; h++) { 352 for ( Object cpo : classPaths) { // for each classpath ... 353 //System.out.printf("DBG: cpo %s\n", cpo.toString()); 354 File classPath = new File((URL.class).isInstance(cpo) ? ((URL)cpo).getFile() : cpo.toString()); 355 if ( classPath.getName().endsWith(".jar") ) { // is our classpath a jar? 356 if (classPath.getName().endsWith(fileName)) { 357 jarFile = classPath; 358 break; 359 } 360 } 361 else if ( classPath.isDirectory() ) { 362 jarFile = new File(classPath, fileName); 363 //System.out.printf("DBG trying %s\n", jarFile.getAbsolutePath()); 364 if (jarFile.exists()) 365 break; 366 } 367 } 368 } 369 return jarFile; 370 } 371 372 373 public static void main( String[] args) throws Exception { 374 if (args.length ==0 ) 375 usage(); 376 377 if (args.length == 1 ) { // default -p pkgname [...] 378 if ( args[0].startsWith("-")) usage(); 379 380 String pkg = args[0]; 381 Set<Class> clsSet = PkgSig.findClassesForPkg(pkg); 382 if (clsSet.size() == 0 ) 383 { 384 System.out.printf("No package '%s' found in classPath\n", pkg); 385 System.exit(1); 386 } 387 388 for ( Class cls : clsSet) { 389 //Class cls = (Class)o; 390 //System.out.println(cls.getName()); 391 ClassSig classSig = new ClassSig(cls); 392 classSig.emit(); 393 } 394 } 395 else if (args[0].equals("-p")) { 396 String pkg = args[1]; 397 Set<Class> clsSet = PkgSig.findClassesForPkg(pkg); 398 for ( Class cls : clsSet) { 399 //ClassSig classSig = new ClassSig(cls); 400 //classSig.emit(); 401 new ClassSig(cls).emit(); 402 } 403 } 404 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 } 413 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 // Theres upwards of 8000 classes in rt.jar most of which we dont care about 418 // suppress internal implementation classes which shouldnt be using anyway 419 suppressFilter.add("com.sun"); 420 suppressFilter.add("com.sunw"); 421 suppressFilter.add("sun"); 422 suppressFilter.add("sunw"); 423 // suppress some biggies we 'probably' wont ever use - may want to revisit these 424 suppressFilter.add("org.omg"); 425 suppressFilter.add("javax.swing.plaf"); 426 suppressFilter.add("javax.print.attribute.standard"); 427 suppressFilter.add("org.jcp.xml.dsig"); 428 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 } 435 } 436 else { 437 usage(); 438 } 439 440 441 } 442 } 443 444 // This class emits class info in format suitable for cobra compiler to (easily) parse. 445 // see Source/BackEndJvm/JvmJarSig.cobra 446 // Any changes made here should be in lockstep with that file.... 447 class ClassSig { 448 Class cls; 449 TypeVariable<?>[] genericParams = {}; 450 int indent= 0; 451 452 public ClassSig(Class cls) { 453 this.cls = cls; 454 } 455 456 // main entry point 457 public void emit() { 458 // suppress anon inner classes 459 if ( this.cls.getSimpleName().trim().length() == 0 ) 460 return; 461 462 463 System.out.println("\n" + this.cls.getName()); 464 this.indent++; 465 emitClassHeader(); 466 emitFields(); 467 emitConstructors(); 468 emitMethods(); 469 this.indent--; 470 } 471 472 public boolean isPkgPrivate(int m) { 473 // if (!cobraGen) 474 // return false 475 476 // suppress classes that have only pkgPrivate (default) accessability 477 return (! Modifier.isPublic(m) && !Modifier.isProtected(m) && !Modifier.isPrivate(m)); 478 } 479 480 public void emitClassHeader() { 481 String flags =""; 482 String t ="class"; 483 if (this.cls.isInterface()) t ="Interface"; 484 else if (this.cls.isEnum()) t ="Enum"; 485 printIndent(); 486 System.out.printf( "%-30s %s\n", t, "# JavaType"); 487 488 printIndent(); 489 System.out.printf("%-30s %s\n", this.cls.getPackage().getName(), "# package"); 490 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 String gName = this.dotNetGenericsName(this.cls, clsName); 499 if (! gName.isEmpty()) { 500 clsName = gName; 501 //System.out.print(gName); 502 flags += "G"; 503 } 504 505 printIndent(); 506 System.out.printf("%-30s %s", clsName, "# name"); 507 System.out.println(); 508 509 //Superclass name - Use Generics superclass if have one and display in dotNet form 510 Class superCls = this.cls.getSuperclass(); 511 String superName = "-"; 512 if ( superCls != null) 513 superName = superCls.getName(); 514 if ( superName != "-") { 515 String gSuperName = this.dotNetGenericsSuperName(this.cls); 516 if (! gSuperName.isEmpty() ) { 517 superName = gSuperName; 518 } 519 } 520 printIndent(); 521 System.out.printf("%-30s %s", superName, "# superclass"); 522 System.out.println(); 523 524 // Interfaces 525 //System.out.printf("%-30s %s\n", '-', " # interfaces"); 526 //Class[] interfaces = this.cls.getInterfaces(); 527 //emitClassList(interfaces, "interfaces"); 528 Type[] gInterfaces = this.cls.getGenericInterfaces(); 529 emitTypesList(gInterfaces, " Interfaces"); 530 531 // Modifiers 532 //System.out.printf("%-30s %s\n", '-', " # modifiers"); 533 int m = this.cls.getModifiers(); 534 emitModifiers(m); 535 536 if (this.genericParams.length > 0 ) // is a generic class 537 emitGenericClassParameters(); 538 } 539 540 void printIndent() { 541 for (int i=0; i < indent; i++) 542 System.out.print(" "); // 4 spaces 543 } 544 545 String dotNetGenericsName( Class cls, String clsName) { 546 // generics class naming like .Net TypeName`<nTypeParams> 547 String gName=""; 548 TypeVariable<?>[] gParams = cls.getTypeParameters(); 549 if (gParams.length > 0) { // 0 TypeParameters -> not generic 550 gName = String.format("%s`%d", clsName, gParams.length); 551 //System.out.printf(" gName=%s`%d", clsName, genArgs.length); 552 this.genericParams = gParams; // copy for later use 553 } 554 return gName; 555 } 556 557 String dotNetGenericsSuperName( Class cls) { 558 Type gsuperCls = cls.getGenericSuperclass(); 559 String gsuperName = ""; 560 //gsuperName = gsuperCls.getCanonicalName(); 561 if ( gsuperCls instanceof ParameterizedType) { 562 gsuperName = gsuperCls.toString(); // this seems the only way to get the name 563 int idx = gsuperName.indexOf("<"); 564 gsuperName = gsuperName.substring(0, idx); // break off GenericTypes 565 // System.out.printf(" gSuper=%-30s", gsuperName); 566 //gsuperName = gsuperCls.getCanonicalName(); 567 Type[] typeArgs = ((ParameterizedType)gsuperCls).getActualTypeArguments(); 568 if (typeArgs.length > 0) { // 0 TypeParameters -> not generic 569 gsuperName = String.format("%s`%d", gsuperName, typeArgs.length); 570 } 571 } 572 return gsuperName; 573 } 574 575 @SuppressWarnings("unchecked") 576 public void emitFields() { 577 Field[] fields = this.cls.getDeclaredFields(); 578 for (java.lang.reflect.Field f : fields) { 579 int m = f.getModifiers(); 580 if( java.lang.reflect.Modifier.isPrivate(m) || isPkgPrivate(m)) 581 continue; 582 printIndent(); 583 584 //printIndent(); 585 //System.out.printf("%s\n", f.getName()); 586 System.out.print("var "); 587 System.out.println(f.getName()); 588 this.indent++; 589 590 emitModifiers(m); 591 592 if (this.cls.isEnum()) { 593 printIndent(); 594 String typeName = f.getType().getName(); 595 System.out.printf("%s\n", typeName); 596 if ( f.getType().isEnum()) { 597 this.indent++; 598 printIndent(); 599 System.out.printf("%d\n", Enum.valueOf( this.cls, f.getName()).ordinal() ); 600 //System.out.printf("%s\n", Enum.valueOf( this.cls, f.getName())); 601 this.indent--; 602 } 603 } 604 else 605 { 606 String gTypeStr = this.makeTypeStr(f.getGenericType()); 607 String tag = "# Type"; 608 if (gTypeStr.contains("<")) 609 tag = "# generic Type :G"; 610 printIndent(); 611 System.out.printf("%-30s %s\n", gTypeStr, tag); 612 } 613 614 615 //TODO attributes 616 //printIndent(); 617 //System.out.printf("%s\n", '-'); 618 this.indent--; 619 } 620 } 621 622 public void emitModifiers(int m) { 623 StringBuilder sb = new StringBuilder(); 624 if (Modifier.isStatic(m)) sb.append("static "); 625 if (Modifier.isAbstract(m)) sb.append("abstract "); 626 if (Modifier.isSynchronized(m)) sb.append("synchronized "); 627 if (Modifier.isFinal(m)) sb.append("final "); 628 if (Modifier.isPublic(m)) sb.append("public "); 629 if (Modifier.isProtected(m)) sb.append("protected "); 630 if (Modifier.isPrivate(m)) sb.append("private "); 631 if (! Modifier.isPublic(m) && !Modifier.isProtected(m) && !Modifier.isPrivate(m)) 632 sb.append("default "); 633 printIndent(); 634 String comment = "# modifiers"; 635 if (sb.length() == 0 ) comment = "# no modifiers"; 636 System.out.format("%-30s %s\n", sb.toString(), comment); 637 } 638 639 public void emitConstructors() { 640 Constructor[] ctors = this.cls.getDeclaredConstructors(); 641 for (Constructor ctor : ctors) { 642 int m = ctor.getModifiers(); 643 if( java.lang.reflect.Modifier.isPrivate(m) || isPkgPrivate(m)) 644 continue; 645 646 printIndent(); 647 648 this.indent++; 649 System.out.print("ctor "); 650 System.out.println(ctor.getName()); 651 652 //Class[] parTypes = ctor.getParameterTypes(); 653 //emitClassList(parTypes, "parameters"); 654 Type[] gparTypes = ctor.getGenericParameterTypes(); 655 emitTypesList(gparTypes, "Parameters"); 656 657 this.indent--; 658 } 659 } 660 661 public void emitMethods() { 662 Method[] methods = this.cls.getDeclaredMethods(); 663 for (Method m : methods) { 664 int mod = m.getModifiers(); 665 if( Modifier.isPrivate(mod) || isPkgPrivate(mod) ) continue; 666 667 printIndent(); 668 System.out.print("method "); 669 String mName = m.getName(); 670 if (m.isVarArgs()) 671 mName = mName + "[V]" ; 672 System.out.println(mName); 673 674 this.indent++; 675 emitModifiers(mod); 676 677 //Class retType = m.getReturnType(); 678 //String retTypeName = retType.getName(); 679 //printIndent(); 680 //System.out.printf("%-30s %s\n", retTypeName, "# returnType"); 681 String retTypeStr = this.makeTypeStr(m.getGenericReturnType()); 682 //if (! retTypeStr.startsWith(retTypeName)) 683 { 684 printIndent(); 685 String tag = "# returnType"; 686 if (retTypeStr.contains("<")) 687 tag = "# generic returnType :G"; 688 System.out.printf("%-30s %s\n", retTypeStr, tag); 689 } 690 691 //Class[] parTypes = m.getParameterTypes(); 692 //emitClassList(parTypes, "parameters"); 693 Type[] gparTypes = m.getGenericParameterTypes(); 694 emitTypesList(gparTypes, "Parameters"); 695 696 //Class[] exceptions = m.getExceptionTypes(); 697 //emitClassList(exceptions, "exceptions"); 698 Type[] gExcTypes = m.getGenericExceptionTypes(); 699 emitTypesList(gExcTypes, "Exceptions"); 700 701 this.indent--; 702 } 703 } 704 705 public void emitClassList(Class[] clsList, String tag) { 706 printIndent(); 707 StringBuilder sb = new StringBuilder(); 708 String sep = ""; 709 for (Class c : clsList) { 710 sb.append(sep); 711 sb.append(c.getName()); 712 sep = ","; 713 } 714 if (clsList.length == 0 ) 715 sb.append("-"); 716 717 String commentPrefix = ((clsList.length == 0 ) ? 718 "# no " : 719 "# "); 720 StringBuilder comment = new StringBuilder(commentPrefix); 721 comment.append(tag); 722 System.out.printf("%-30s %s\n", sb.toString(), comment.toString()); 723 } 724 725 public void emitGenericClassParameters() { 726 assert this.genericParams.length > 0 ; 727 //if (this.genericParams.length == 0 ) // not a generic class 728 // return; 729 730 StringBuilder sb = new StringBuilder(); 731 String sep = ""; 732 for (TypeVariable<?> p : this.genericParams) { // 733 sb.append(sep); 734 sb.append(p.getName()); 735 sep = ","; 736 } 737 //if (this.genericParams.length == 0 ) 738 // return; //sb.append("-"); 739 740 String commentPrefix = ((this.genericParams.length == 0 ) ? "# no " : "# "); 741 StringBuilder comment = new StringBuilder(commentPrefix); 742 comment.append(" Generic Parameter list :G"); 743 printIndent(); 744 System.out.printf("%-30s %s\n", sb.toString(), comment.toString()); 745 } 746 747 public void emitTypesList(Type[] typList, String tag) { 748 StringBuilder sb = new StringBuilder(); 749 String sep = ""; 750 for (Type t : typList) { 751 sb.append(sep); 752 String tStr = this.makeTypeStr(t); 753 sb.append(tStr); 754 sep = ","; 755 } 756 if (typList.length == 0 ) { 757 //if (isOptional) 758 // return; 759 //else 760 sb.append("-"); 761 } 762 763 String commentPrefix = ((typList.length == 0 ) ? 764 "# no " : 765 "# "); 766 StringBuilder comment = new StringBuilder(commentPrefix); 767 comment.append(tag); 768 if (sb.toString().contains("<")) 769 comment.append(" :G"); 770 771 printIndent(); 772 System.out.printf("%-30s %s\n", sb.toString(), comment.toString()); 773 } 774 775 /* 776 * Cleanup a (Generic) Type name to be 'consistant' with class naming. 777 */ 778 public String makeTypeStr(Type t) { 779 String tStr = t.toString(); 780 tStr = tStr.replace("class ", ""); // sometimes puts on leading 'type ' 781 tStr = tStr.replace("interface ", ""); 782 // possibly others - enum ? 783 tStr = tStr.replace("<?>", ""); // lose generic wildcard 784 if ( tStr.endsWith("[]")) { // Type makes ' <name>[]' rather than '[L<name>;' for arrays 785 StringBuilder sfx = new StringBuilder(); 786 while (tStr.endsWith("[]")) { 787 tStr = tStr.substring(0, tStr.length()-2); 788 sfx = sfx.append("["); 789 } 790 sfx.append("L"); 791 sfx.append(tStr); 792 sfx.append(";"); 793 tStr = sfx.toString(); 794 } 795 return tStr; 796 } 797 } -
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.jar 3 4 cobra.lang.CobraCore 5 class # JavaType 6 cobra.lang # package 7 CobraCore # name 8 java.lang.Object # superclass 9 - # no Interfaces 10 public # modifiers 11 var _willCheckInvariant 12 static public # modifiers 13 java.lang.Boolean # Type 14 var _willCheckRequire 15 static public # modifiers 16 java.lang.Boolean # Type 17 var _willCheckEnsure 18 static public # modifiers 19 java.lang.Boolean # Type 20 var _willCheckAssert 21 static public # modifiers 22 java.lang.Boolean # Type 23 var _willCheckNil 24 static public # modifiers 25 java.lang.Boolean # Type 26 ctor cobra.lang.CobraCore 27 - # no Parameters 28 method noOp[V] 29 static public # modifiers 30 int # returnType 31 [Ljava.lang.Object; # Parameters 32 - # no Exceptions 33 method runAllTests 34 static public # modifiers 35 void # returnType 36 - # no Parameters 37 - # no Exceptions 38 method printDebuggingTips 39 static public # modifiers 40 void # returnType 41 - # no Parameters 42 - # no Exceptions 43 44 cobra.lang.CobraImp 45 class # JavaType 46 cobra.lang # package 47 CobraImp # name 48 java.lang.Object # superclass 49 - # no Interfaces 50 public # modifiers 51 var _printStringMaker 52 static public # modifiers 53 cobra.lang.CobraImp$SimpleStringMaker # Type 54 ctor cobra.lang.CobraImp 55 - # no Parameters 56 method printLine 57 static public # modifiers 58 void # returnType 59 - # no Parameters 60 - # no Exceptions 61 method printLine 62 static public # modifiers 63 void # returnType 64 java.lang.String # Parameters 65 - # no Exceptions 66 method printStop 67 static public # modifiers 68 void # returnType 69 - # no Parameters 70 - # no Exceptions 71 method printStop 72 static public # modifiers 73 void # returnType 74 java.lang.String # Parameters 75 - # no Exceptions 76 method makeString 77 static public # modifiers 78 java.lang.String # returnType 79 java.lang.String # Parameters 80 - # no Exceptions 81 method makeString 82 static public # modifiers 83 java.lang.String # returnType 84 [Ljava.lang.String; # Parameters 85 - # no Exceptions 86 87 cobra.lang.CobraImp$SimpleStringMaker 88 class # JavaType 89 cobra.lang # package 90 CobraImp$SimpleStringMaker # name 91 java.lang.Object # superclass 92 - # no Interfaces 93 static public # modifiers 94 ctor cobra.lang.CobraImp$SimpleStringMaker 95 - # no Parameters 96 method makeString 97 public # modifiers 98 java.lang.String # returnType 99 [Ljava.lang.String; # Parameters 100 - # no Exceptions 101 method makeString 102 public # modifiers 103 java.lang.String # returnType 104 java.lang.String # Parameters 105 - # no Exceptions 106 method makeString 107 public # modifiers 108 java.lang.String # returnType 109 int # Parameters 110 - # no Exceptions 111 method makeString[V] 112 public # modifiers 113 java.lang.String # returnType 114 [Ljava.lang.Object; # Parameters 115 - # no Exceptions -
Source/Cobra.Lang/java/00-README
1 README for cobra java backend cross compiler devt. 2 -------------------------------------------------- 3 4 Task: Make the cobra compiler generate Java code (a java back end). 5 6 Initially (now) this is a cross compiler. The .Net cobra compiler will 7 with the correct switch (-back-end:jvm) generate java source for the given 8 cobra source, compile it and run it. 9 i.e A cobra to java compiler (compiler running) on .Net 10 11 Eventually when I have bootstrapped enough java codegeneration capability 12 and worked out a few issues I'll run the cross compiler on the 13 (probably heavily modified) compiler source and build a java version of the 14 compiler. Then we'll have a cobra to java compiler on the jvm. 15 16 Supporting that is this directory which provides 17 - stub code for a java cobra RTL (CobraLang.jar) 18 - A tool to generate descriptions for java library classes (Pkgsig files) 19 - a script to build and copy the various supporting pieces the java backend needs to the compiler Source directory. 20 21 22 The base java version supported is 1.6. 23 This one specifically 24 java version "1.6.0_24" 25 Java(TM) SE Runtime Environment (build 1.6.0_24-b07) 26 Java HotSpot(TM) Client VM (build 19.1-b02, mixed mode, sharing) 27 28 = Caveats = 29 30 This backend is under development 31 - for any but the most trivial uses it is effectively broken. 32 There are large amounts of (java) code generation missing. 33 It spews debug/diagnostic/conversational/status info all the time. 34 There are bugs. 35 There are missing capabilities. 36 There are horrible bits 37 38 Regardless, the .Net/Mono/C# compilation should continue to run as per the 39 standard source distribution without problems. 40 Specifically all the tests should run. 41 42 This is a compiler mod only - there is no support for any sort of a 43 common/shared/portable system library. 44 45 This is a source modification - no installation support. 46 Run the compiler out of the cobra source directory 47 48 I'm developing this in Windows (XP) - it may or may not be working under mono 49 on any other platform. 50 51 This is (the/an) initial devt snapshot. 52 Its working(ish) but rough, 53 Things will change 54 55 - What To Do - 56 57 If you are brave or foolhardy enough to want to run this and see what 58 happens, good for you. 59 This is what you will need to do 60 61 1) Apply the patches providing the java backend to the Source tree 62 - get the modified compiler subsequently rebuilt 63 Patch should be on the cobra website http://cobra-language.com 64 Ticket 275: More support for java backend 65 http://cobra-language.com/trac/cobra/ticket/275 66 67 2) Ensure java and javac executables (1.6) are in your PATH and work. 68 69 3) Go into this dir and run ./mkJarAll 70 ( its a bash script - you will need bash or to port the script, 71 or run the command contents manually) - this builds the 72 tool and uses that to create the class description info and copies 73 it to the right places in the cobra source tree) 74 4) find a test cobra script and compile it 75 76 - How to build and run a cobra program generating a java app - 77 78 cobra -back-end:jvm -v:2 -verbosity-ref:1 -kif file.cobra 79 80 -v:2 - display some compile run info 81 -verbosity-ref:1 display (std) info about reading jarfiles 82 -kif - leave the generated java files around after compilation 83 file.cobra - the cobra source file to compile 84 85 If you are lucky you'dll get a whole lot of compiler output at the end of 86 which you'll see a javac invocation followed by a successful execution 87 of the translated cobra program. 88 89 If you are unlucky you'll see error lines from the javac compilation phase cos 90 the cobra program exercises something thats not implemented (java codegen wise). 91 92 If you are really unlucky something in the compiler will break and the 93 cobra compiler will barf some sort of exception. 94 95 96 97 - Status - 98 Jul-2011 - We can build and run simple (single file) programs. 99 (Up to about 032-* of the files in Tests/100-*. 100 Maybe more but thats what I've tried so far) 101 We seem to be understanding references to java classes in library (jar) files. 102 103 - Other - 104 105 Post issues/questions/comments/etc if you have them to Cobra Programming Language Forum 106 http://cobra-language.com/forums/viewforum.php 107 theres an existing topic 'Java Back End' or open new ones. 108 109 110 111 - hops 112 -
Source/Cobra.Lang/java/CobraImp.java
1 /* 2 * CobraImp.java 3 * Native java support code RTL 4 * 5 * Currently only stubbed, minimal native code impl. 6 */ 7 package cobra.lang; 8 9 import java.lang.*; 10 11 12 public class CobraImp { 13 // simple minimal StringMaker pending cobra compilation of StringMaker.cobra 14 public static class SimpleStringMaker { 15 16 public String makeString(String[] args) { 17 StringBuilder sb = new StringBuilder(); 18 for (Object arg : args) 19 sb.append(arg); 20 return sb.toString(); 21 } 22 public String makeString(String s) { 23 return s; 24 } 25 public String makeString(int i) { 26 return new Integer(i).toString(); 27 } 28 29 public String makeString(Object... args) { 30 StringBuilder sb = new StringBuilder(); 31 for (Object arg : args) 32 sb.append(arg.toString()); 33 return sb.toString(); 34 } 35 } 36 //static public StringMaker _printStringMaker; 37 static public SimpleStringMaker _printStringMaker = new SimpleStringMaker(); 38 39 static { 40 // _printToStack = new Stack<TextWriter>(); 41 // PushPrintTo(Console.Out); 42 //_printStringMaker = new SimpleStringMaker(); 43 // _printStringMaker = new PrintStringMaker(); 44 // _techStringMaker = new TechStringMaker(); 45 // PromoteNumerics = NumericTypeInfo.PromoteNumerics; 46 } 47 48 static public void printLine() { 49 //_printToStack.Peek().WriteLine(); 50 System.out.println(); 51 } 52 53 static public void printLine(String s) { 54 // _printToStack.Peek().WriteLine(s); 55 System.out.println(s); 56 } 57 58 static public void printStop() { 59 } 60 61 static public void printStop(String s) { 62 // _printToStack.Peek().Write(s); 63 System.out.print(s); 64 } 65 66 static public String makeString(String[] args) { 67 return _printStringMaker.makeString(args); 68 } 69 70 static public String makeString(String s) { 71 return s; 72 } 73 74 } 75 -
Source/Cobra.Lang/java/mkjarAll
1 #!bash 2 # Build script for java sources for cobra (on MSWindows (XP)) 3 # Compile java source classes for java cobra RTL 4 # copy them and std sig files to Source dir 5 6 echo 'making RTL from java sources' 7 [ -d classes ] || mkdir classes 8 javac -d classes CobraImp.java CobraCore.java 9 [ $? == 0 ] || exit 10 jar cvf CobraLang.jar -C classes . 11 [ $? == 0 ] || exit 12 cp CobraLang.jar ../.. 13 14 if [ ! -e PkgSig.class ]; then 15 echo 'building PkgSig app' 16 javac -cp . PkgSig.java 17 fi 18 19 echo 'Gen pkgSig file for CobraLang.jar' 20 java -cp '.;CobraLang.jar' PkgSig -j CobraLang.jar > CobraLang.jar.sig 21 22 echo 'Gen pkgSig file for rt.jar' 23 java -cp . PkgSig -j rt.jar > rt.jar.sig 24 echo 'Gen pkgSig file for java.lang' 25 java -cp . PkgSig java.lang > java.lang.sig 26 echo 'Gen pkgSig file for java.util' 27 java -cp . PkgSig java.util > java.util.sig 28 29 echo 'copy .sig files to compiler directory' 30 cp CobraLang.jar.sig rt.jar.sig java.util.sig java.lang.sig ../.. -
Source/Container.cobra
167 167 ensure 168 168 result implies result.name==name 169 169 body 170 #print _declsByName.keys 170 171 return if(_declsByName.containsKey(name), _declsByName[name], nil) 171 172 172 173 def declForName(name as String) as IMember? -
Source/BinaryOpExpr.cobra
534 534 535 535 # TODO: handle the real equals and does not equal 536 536 537 var _cobraToSharp = {538 'EQ': '==',539 'NE': '!=',540 'GT': '>',541 'LT': '<',542 'GE': '>=',543 'LE': '<=',544 'IS': '==',545 'ISNOT': '!=',546 }547 548 537 var _items as List<of Expr> 549 538 var _operations as List<of String> 550 539 -
Source/Module.cobra
27 27 base.addMinFields 28 28 .addField('fileName', _fileName) 29 29 30 30 # Would be better named LibModule or similar 31 31 class AssemblyModule inherits Module is partial 32 32 """ 33 An assembly module represents a .dll 33 An assembly module represents a .dll, jarfile or libraryish thing 34 Basically a holder for a filename (location) and a namespace for its contents 34 35 """ 35 36 36 37 var _topNameSpace as NameSpace 37 38 var _mustBindInhList = List<of INameSpaceMember>() 38 39 39 cue init(ass as Assembly, globalNS as NameSpace)40 .init(ass, 0, globalNS)40 #cue init(ass as Assembly, globalNS as NameSpace) 41 # .init(ass, 0, globalNS) 41 42 42 cue init(ass as Assembly, verbosity as int, globalNS as NameSpace)43 base.init(ass.location, verbosity, '')44 _topNameSpace = NameSpace(globalNS, '(top namespace for assembly [ass])')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])') 45 46 47 cue init(location as String, globalNS as NameSpace) 48 .init(location, 0, globalNS) 49 50 cue init(location as String, verbosity as int, globalNS as NameSpace) 51 base.init(location, verbosity, '') 52 _topNameSpace = NameSpace(globalNS, '(top namespace for assemblyModule at [location])') 53 46 54 def addMustBindInh(what as INameSpaceMember) 47 55 require .compiler.curModule is this 48 56 _mustBindInhList.add(what) -
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>? 1191 #get clrPrimitiveToITypeCache as IDictionary<of System.Type, IType>? 1192 get primitiveToITypeCache as IDictionary<of dynamic, IType>? 1192 1193 1193 1194 get basicTypes as IList<of PrimitiveType> 1194 1195 … … 1215 1216 def setOfType as Class 1216 1217 def stringType as Class 1217 1218 1219 # multiple backends 1220 get backEnd as BackEnd 1221 def objectTypeProxy as AbstractTypeProxy 1222 def typeTypeProxy as AbstractTypeProxy 1223 def installNativeMethods(box as Box, nativeType as NativeType) 1218 1224 1219 1225 ## Other 1220 1226 1221 1227 def addIntermediateFile(path as String) 1222 def loadReference(reference as String ) as bool1228 def loadReference(reference as String, addExtn as bool) as bool -
Source/CommandLine.cobra
739 739 try 740 740 comp.initBackEnd 741 741 reference = .options['document-library'] to String # to-do: pick out type name. to-do: support multiple references 742 if not reference.endsWith('.dll') and not reference.endsWith('.exe'), reference += '.dll' # todo-backend742 reference = comp.backEnd.fixLibExtension(reference) 743 743 .options['reference'] = [reference] 744 744 phaseClasses = [ 745 745 BindRunTimeLibraryPhase, -
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') 90 #if .compiler.loadReference(_fileName + '.dll') 91 if .compiler.loadReference(_fileName, true) 91 92 _bindUse(true) 92 93 if .boundNameSpace is nil 93 94 .throwError('Cannot find namespace "[_fullName]" in library "[_fileName]".') … … 100 101 else 101 102 if _fullName.endsWith('.dll') 102 103 .throwError('Do not end a namespace name in a "use" directive with ".dll".') 103 if .compiler.loadReference(_fullName + '.dll') 104 #if .compiler.loadReference(_fullName + '.dll') 105 if .compiler.loadReference(_fullName, true) 104 106 _bindUse(true) 105 107 if .boundNameSpace is nil 106 108 .throwError('Cannot find namespace "[_fullName]" in loaded library "[_fullName]".') -
Source/Phases/ParsePhase.cobra
25 25 extraSource = .options.getDefault('extra-source', '').trim to String 26 26 if extraSource <> '' 27 27 # CC: parser = CobraParser(verbosity=.verbosity, typeProvider=this, warningRecorder=this, errorRecorder=this, globalNS=compiler.globalNS, parseCommandLineArgs=ref .parseCommandLineArgsCallBack) 28 parser = CobraParser(verbosity=.verbosity, typeProvider=compiler, warningRecorder=compiler, errorRecorder=compiler, globalNS=compiler.globalNS) 28 parser = CobraParser() 29 parser.verbosity=.verbosity 30 parser.typeProvider = compiler # compiler.typeProvider 31 parser.warningRecorder = compiler 32 parser.errorRecorder = compiler 33 parser.globalNS=compiler.globalNS 29 34 parser.parseCommandLineArgs = ref .parseCommandLineArgsCallBack 35 parser.backEnd = compiler.backEnd 30 36 errorsCount = compiler.errors.count 31 37 try 32 38 module = parser.parseSource('_ch_cobra-extra-source.cobra', extraSource) # ch = compiler helper … … 35 41 throw 36 42 if compiler.errors.count > errorsCount 37 43 _printExtraSource(extraSource) 38 for r in parser.references, compiler.loadReference( r.fixLibExtension)44 for r in parser.references, compiler.loadReference(.compiler.backEnd.fixLibExtension(r), false) 39 45 modules.add(module) 40 46 41 47 didError = false 42 48 for filename in .compiler.pathsToCompile 43 if filename.endsWith('.cs')44 if .verbosity, print 'Noting [filename]' # extra space to line up with 'Parsing [filename]'45 modules.add( SharpModule(filename, .verbosity))49 nativeModule = .compiler.backEnd.genNativeModule(filename, .verbosity) 50 if nativeModule 51 modules.add(nativeModule) # SharpModule or JavaModule or ... 46 52 else 47 53 parser = CobraParser() 48 54 parser.verbosity = .verbosity … … 52 58 parser.parseCommandLineArgs = ref .parseCommandLineArgsCallBack 53 59 parser.globalNS = compiler.globalNS 54 60 # @@ TODO: assert _globalNS is parser.nameSpaceStack[0] 61 parser.backEnd = compiler.backEnd 55 62 try 56 63 module = parser.parseFileNamed(filename) 57 64 catch SourceException 58 65 didError = true 59 66 success 60 for r in parser.references, compiler.loadReference( r.fixLibExtension)67 for r in parser.references, compiler.loadReference(.compiler.backEnd.fixLibExtension(r), false) 61 68 # There could still be parse errors that were recorded, but not thrown. 62 69 # But that's okay because _errors.count is checked further below. 63 70 modules.add(module) -
Source/HelpGenerator.cobra
469 469 i = 0 470 470 for prop in props 471 471 if prop.canRead 472 name = Utils.cobraNameFor SharpMemberName(prop.name)472 name = Utils.cobraNameForNativeMemberName(prop.name) 473 473 try 474 474 value = prop.getValue(obj, nil) 475 475 catch exc as Exception -
Source/Utils.cobra
33 33 success 34 34 value = _toTechString(value) 35 35 name = pi.name 36 name = Utils.cobraNameFor SharpMemberName(name)36 name = Utils.cobraNameForNativeMemberName(name) 37 37 print ' [name] = [value]' 38 38 if obj inherits System.Collections.ICollection 39 39 i = 0 … … 53 53 54 54 extend String 55 55 56 # These should go in String Extensions 57 def beforeL(sep as String) as String 58 test 59 s = 'abc|de' 60 assert s.beforeL('|') == 'abc' 61 assert s.beforeL('=') == 'abc|de' 62 assert '|abcde'.beforeL('|') == '' 63 assert 'abcde|'.beforeL('|') == 'abcde' 64 body 65 idx = .indexOf(sep) 66 if idx < 0 67 return this 68 return this[0:idx] 69 70 def afterL(sep as String) as String 71 test 72 s = 'abc|de' 73 assert s.afterL('|') == 'de' 74 assert s.afterL('=') == '' 75 assert '|abcde'.afterL('|') == 'abcde' 76 assert 'abcde|'.afterL('|') == '' 77 body 78 idx = .indexOf(sep) 79 if idx < 0 80 return '' 81 return this[idx+sep.length:] 82 56 83 ## Language specific 57 58 84 def canBeUndottedMemberName as bool 59 85 """ 60 86 Returns true if this string is the kind of name that can reference a box member without … … 172 198 return defaultValue 173 199 174 200 175 ## C#201 ## BackEnd C# 176 202 177 def cobraNameFor SharpMemberName(name as String) as String203 def cobraNameForNativeMemberName(name as String) as String 178 204 require 179 205 name.length 180 206 ensure … … 197 223 ] 198 224 for case in cases 199 225 parts = case.split 200 assert Utils.cobraNameFor SharpMemberName(parts[0]) == parts[1]226 assert Utils.cobraNameForNativeMemberName(parts[0]) == parts[1] 201 227 body 202 228 if name.length == 1 203 229 return name.toLower … … 321 347 # return Assembly.loadWithPartialName(name) 322 348 # with dynamic binding: 323 349 assemblyType = Assembly to dynamic 324 return assemblyType.loadWithPartialName(name) 350 try 351 ass = assemblyType.loadWithPartialName(name) 352 catch System.Reflection.TargetInvocationException # or any Exception 353 ass = nil 354 return ass 325 355 326 356 327 357 class ShouldNotCallException inherits Exception -
Source/BackEndClr/ClrType.cobra
1 """ 2 BackEnd Type wrappers for dotNet/CLR 3 """ 4 5 1 6 class ClrNativeType inherits NativeType 2 7 """ 8 Acts as a holder for a Native Type, typically from scanning a DLL. 9 """ 10 3 11 var _type as System.Type 4 12 5 13 cue init(type as System.Type) … … 17 25 def getHashCode as int is override 18 26 return .clrType.getHashCode 19 27 20 get clrType asType28 get backEndType as Type # was clrType changed to backEndType 21 29 return _type 22 30 31 # Not part of NativeType - used by a cast to ClrNativeType then deref (:( 32 # should only be used/called from within ClrBackEnd code 33 get clrType as Type 34 return _type 35 23 36 get name as String is override 24 37 return _type.name 25 38 … … 35 48 def customAttributes as IList<of dynamic> is override 36 49 return .clrType.getCustomAttributes(true) to IList<of dynamic> 37 50 51 get isSystemObjectClass as bool is override 52 return /#_type and #/ .fullName == 'System.Object' 53 54 get isSystemTypeClass as bool is override 55 return /#_type and #/ .fullName == 'System.Type' 38 56 39 class Class is partial 57 class ClrTypeProxy inherits NativeTypeProxy 58 """ 59 Acts as an ITypeProxy where the CLR type is known. 60 Typically used when scanning DLLs. 61 """ 40 62 41 get isSystemObjectClass as bool is override 42 return _nativeType and _nativeType.fullName == 'System.Object' 63 shared 43 64 44 get isSystemTypeClass as bool is override 45 return _nativeType and _nativeType.fullName == 'System.Type' 65 var _cobraNameForSharpGenericNameCache = Dictionary<of String, String>() 66 67 def cobraNameForSharpBoxName(name as String) as String 68 """ 69 Returns 'Foo' for 'Foo' and 'Foo<of,>' for 'Foo`2' 70 In other words, works for generic and non-generic classes, structs and interfaces. 71 Does *not* work for arrays, pointers, etc. 72 """ 73 if '`' not in name 74 return name 75 if _cobraNameForSharpGenericNameCache.containsKey(name) 76 return _cobraNameForSharpGenericNameCache[name] 77 else 78 parts = name.split(c'`') 79 count = int.parse(parts[1]) 80 cobraName = parts[0] + '<of' 81 for i in count-1, cobraName += ',' 82 cobraName += '>' 83 _cobraNameForSharpGenericNameCache[name] = cobraName 84 return cobraName 85 86 var _clrType as Type 87 88 cue init(nativeType as NativeType) # TODO: HACK 89 .init((nativeType to ClrNativeType).clrType) 90 91 cue init(clrType as Type) 92 base.init 93 _clrType = clrType 94 95 def addMinFields 96 base.addMinFields 97 .addField('clrType', _clrType) 98 99 get realType as IType is override 100 return _realTypeWithCache(_clrType) 101 102 def _realTypeWithCache(clrType as Type) as IType 103 t = (.compiler to Compiler).typeForClrType(clrType) 104 if t is nil 105 t = _realTypeWithoutCache(clrType, 0) 106 (.compiler to Compiler).addTypeForClrType(t to !, clrType) 107 return t to ! 108 109 def _realTypeWithoutCache(clrType as Type, level as int) as IType 110 assert .compiler.basicTypes.count > 9 # should have bool, char, all the ints, etc. 111 112 # Must return the Cobra primitive types in place of System.Boolean, System.Char, System.Int16, etc. 113 # because it's the primitives that are used all over the compiler. 114 clrPrimitiveToIType = .compiler.primitiveToITypeCache 115 if clrPrimitiveToIType is nil or clrPrimitiveToIType.count == 0 116 typeToIType = _makePrimitiveTypesDict 117 clrPrimitiveToIType = Dictionary<of dynamic, IType>() 118 for key in typeToIType.keys, clrPrimitiveToIType[key] = typeToIType[key] 119 (.compiler to Compiler).primitiveCache = clrPrimitiveToIType to ! 120 basicType as IType? 121 if clrPrimitiveToIType.tryGetValue(clrType, out basicType) 122 return basicType to ! 123 124 # handle wrapped types, like arrays and pointers, with recursive calls 125 if clrType.isArray 126 # assert clrType.name.endsWith(r'[]') # could be [,] so TODO: handle multidim arrays 127 return .typeProvider.arrayType(_realTypeWithCache(clrType.getElementType to !)) 128 else if clrType.isNested and not clrType.isGenericParameter 129 declaringType = _realTypeWithCache(clrType.declaringType to !) 130 potential = declaringType.memberForName(clrType.name) 131 if potential is nil 132 # comes up on MS Windows .NET 2.0 for multiple types when using System.Windows.Forms 133 # error: Cannot locate nested CLR type "System.Windows.Forms.UnsafeNativeMethods+IOleControl" (simple name is "IOleControl"). 134 if 'NativeMethods' in clrType.toString 135 return _hack(clrType) 136 .throwError('Cannot locate nested CLR type "[clrType]" (simple name is "[clrType.name]").') 137 else if potential inherits IType 138 return potential 139 else 140 .throwError('Located CLR type spec "[clrType]" but got a [potential.englishName] instead of a type.') 141 else if clrType.isPointer 142 assert clrType.name.endsWith('*') 143 # TODO: handle pointer types 144 return _realTypeWithCache(clrType.getElementType to !) 145 else if clrType.isByRef 146 assert clrType.name.endsWith('&') 147 # TODO: handle ref types 148 return _realTypeWithCache(clrType.getElementType to !) 149 150 # generic parameters 151 if clrType.isGenericParameter 152 return GenericParam(ClrNativeType(clrType)) 153 154 typeName = _computeTypeName(clrType) 155 missing = false 156 curNS = _computeNameSpace(clrType, level, out missing) 157 if missing 158 # since the CLR type exists, but cannot be located in our namespaces, 159 # it must be pulled from a dependent DLL that was not directly referenced 160 # but maybe it was already attempted 161 if level > 0, .throwError('Cannot read CLR type "[clrType.fullName]" or its assembly "[clrType.assembly]". Please report to the Cobra discussion forums (http://cobra-language.com/).') 162 163 (.compiler to dynamic).clrReadAssembly(clrType.assembly) 164 return _realTypeWithoutCache(clrType, level+1) # recurse. guard is just above. 165 166 # return namespace member 167 member as IMember? = curNS.declForName(typeName) 168 if member inherits IType 169 if member inherits Box 170 if clrType.isGenericType and not clrType.isGenericTypeDefinition 171 # So we have something like ICollection<of KeyValuePair<of TKey,TValue>> which is all CLR types. 172 # We need the Cobra types of those args so we can construct the Cobra type from the generic cobra type 173 # otherwise, we would just end up returning the generic definition. 174 member = _typeForArgsOfGeneric(clrType, member) 175 return member 176 else 177 msg = 'Cannot locate CLR type "[clrType]".' 178 if clrType.namespace and clrType.namespace.startsWith('System.') 179 # TODO: On .NET 2.0 only \Tests\110-basics-two\550-collection-equality.cobra 180 # fails with: Cannot locate CLR type "System.Collections.KeyValuePairs[]". 181 # Figure out why. 182 if .compiler and .compiler.verbosity > 1 183 print msg 184 # TODO: .compiler.warning(msg) 185 return .compiler.objectType 186 else 187 .throwError(msg) 188 return .compiler.intType # CC: to make C# code gen happy. 189 190 def _makePrimitiveTypesDict as IDictionary<of System.Type, IType> 191 clrPrimitiveToIType = Dictionary<of System.Type, IType>() 192 #def _makePrimitiveTypesDict as IDictionary<of dynamic, IType> 193 # clrPrimitiveToIType = Dictionary<of dynamic, IType>() 194 for bt in .compiler.basicTypes 195 if bt.systemAliasProxy 196 key = (.compiler.nativeType((bt.systemAliasProxy to LibraryTypeProxy).qualifiedName) to ClrNativeType).clrType # TODO: hops cleanup no ClrNativeType 197 clrPrimitiveToIType[key] = bt 198 assert clrPrimitiveToIType.count == 0 or clrPrimitiveToIType.count > 9 199 return clrPrimitiveToIType 200 201 def _computeTypeName(clrType as Type) as String 202 typeName = clrType.name 203 if '`' in typeName 204 # generic like IComparable`1 205 assert r'[' not in typeName 206 typeName = .cobraNameForSharpBoxName(typeName) 207 else if typeName[typeName.length-1].isLetterOrDigit 208 pass 209 else 210 .throwError('Cannot locate CLR type "[clrType]".') 211 return typeName 212 213 def _computeNameSpace(clrType as Type, level as int, missing as out bool) as NameSpace 214 missing = false 215 if clrType.namespace is nil, return .compiler.globalNS 216 nameParts = clrType.namespace.split(c'.') 217 member = .compiler.globalNS.symbolForName(nameParts[0]) 218 if member inherits NameSpace, curNS = member 219 else, missing = true 220 if not missing 221 i = 1 222 while i < nameParts.length 223 namePart = nameParts[i] 224 possible = curNS.declForName(namePart) 225 if possible is nil 226 missing = true 227 break 228 else if possible inherits NameSpace 229 curNS = possible 230 else 231 .throwError('Found "[namePart]" at component [i+1] of CLR type "[clrType.fullName]", but it is a [possible.englishName].') 232 i += 1 233 return curNS 234 235 def _typeForArgsOfGeneric(clrType as Type, member as IType) as IType 236 args = List<of IType>() 237 for genArg in clrType.getGenericArguments 238 args.add(_realTypeWithCache(genArg)) 239 boxMember = member to Box 240 if boxMember.qualifiedName == 'System.Nullable<of>' 241 assert args.count == 1 242 member = .typeProvider.nilableType(args[0]) 243 else 244 member = boxMember.constructedTypeFor(args) 245 return member 246 247 def _hack(clrType as Type) as IType 248 if clrType.isInterface 249 return ClrTypeProxy(sharp'typeof(System.ICloneable)').realType 250 else 251 return ClrTypeProxy(Object).realType 252 253 254 255 256 257 -
Source/BackEndClr/SharpGenerator.cobra
1499 1499 sw.write(';\n') 1500 1500 1501 1501 1502 class BoxField is partial 1503 1504 get _sharpBackEndName as String 1505 name = .name 1506 if not name.startsWith('_') 1507 name = name.capitalized 1508 return name 1509 1502 1510 class BoxConst is partial 1503 1511 1504 1512 def writeSharpDef(sw as CurlyWriter) is override … … 1507 1515 .writeSharpIsNames(sw) 1508 1516 sw.write('const ') 1509 1517 sw.write(_type.sharpRef) 1510 sw.write(' [_ backEndName] = ')1518 sw.write(' [_sharpBackEndName] = ') 1511 1519 _initExpr.writeSharpDef(sw) 1512 1520 sw.write(';\n') 1513 1521 … … 1516 1524 is partial 1517 1525 1518 1526 get sharpAssignmentNames as List<of String> 1519 return [_ backEndName]1527 return [_sharpBackEndName] 1520 1528 # return List<of String>(_useBackEndNameStack) 1521 1529 1522 1530 get sharpName as String is override 1523 1531 if _ifInheritsStack.count 1524 1532 if _type.isReference 1525 return '(([_ifInheritsStack.peek.sharpRef])[_ backEndName])'1533 return '(([_ifInheritsStack.peek.sharpRef])[_sharpBackEndName])' 1526 1534 else 1527 1535 # could it be a subclass? no. value types are structs and cannot be subclassed so this must be `if i` where `i` is nullable struct 1528 return '[_ backEndName].Value' # Nullable<of T>.Value1536 return '[_sharpBackEndName].Value' # Nullable<of T>.Value 1529 1537 else 1530 return _backEndName 1538 backEndName = .name 1539 if not backEndName.startsWith('_') 1540 backEndName = backEndName.capitalized 1541 return backEndName 1542 #return _backEndName 1531 1543 # return _useBackEndNameStack.peek to ! 1532 1544 1533 1545 def writeSharpDef(sw as CurlyWriter) is override … … 1535 1547 .writeSharpAttribs(sw) 1536 1548 .writeSharpIsNames(sw) 1537 1549 sw.write(_type.sharpRef) 1538 sw.write(' [_ backEndName]')1550 sw.write(' [_sharpBackEndName]') 1539 1551 if _initExpr 1540 1552 sw.write(' = ') 1541 1553 _initExpr.writeSharpDef(sw) … … 2417 2429 sw.write('// exactly what is expected\n') 2418 2430 sw.write('[gotRightExceptionVarName] = true;\n') 2419 2431 sw.dedentAndWrite('}\n') 2420 if _exceptionType inherits Box and not (_exceptionType to Box).is SystemExceptionClass2432 if _exceptionType inherits Box and not (_exceptionType to Box).isClrSystemExceptionClass 2421 2433 wrongExceptionVarName = '_lh_expect_[_varNumber]' 2422 2434 assert gotRightExceptionVarName <> wrongExceptionVarName 2423 2435 sw.writeAndIndent('catch (System.Exception [wrongExceptionVarName]) {\n') … … 4368 4380 class CompareExpr 4369 4381 is partial 4370 4382 4383 var _cobraToSharp = { 4384 'EQ': '==', 4385 'NE': '!=', 4386 'GT': '>', 4387 'LT': '<', 4388 'GE': '>=', 4389 'LE': '<=', 4390 'IS': '==', 4391 'ISNOT': '!=', 4392 } 4393 4371 4394 def _writeSharpDef(sw as CurlyWriter) is override 4372 4395 left = _left 4373 4396 right = _right -
Source/BackEndClr/ScanClrType.cobra
1 1 class Compiler is partial 2 2 3 var _didLoadAssemblies = Set<of String>() 4 3 5 var _didReadAssemblies = Set<of String>() 4 6 5 def readAssembly(ass as Assembly) 6 .readAssembly(ass, false) 7 var _clrTypeToType = Dictionary<of System.Type, IType>() 8 9 var _clrTypeCache = Dictionary<of String, System.Type>() 10 11 12 # .Net specific Reference loading 13 def dotNetLoadReference(reference as String) as bool 14 try 15 return __dotNetLoadReference(reference) 16 catch fnfe as System.IO.FileNotFoundException 17 throw LoadReferenceException('FileNotFound', fnfe.fileName, fnfe.message) 18 catch fle as System.IO.FileLoadException 19 throw LoadReferenceException('FileLoadException', fle.fileName ? reference, fle.message) 7 20 8 def readAssembly(ass as Assembly, skipCobra as bool) 21 def __dotNetLoadReference(reference as String) as bool 22 # uses reference parameter 23 # compiler .referenceVerbosity, _willReadDependencies 24 # fills .loadedReferences 25 26 require 27 reference.endsWith('.dll') or reference.endsWith('.exe') 28 reference not in ['.dll', '.exe'] 29 ensure 30 result implies .loadedReferences[.loadedReferences.count-1] == reference 31 not result implies .loadedReferences.count == old .loadedReferences.count 32 body 33 rv = .referenceVerbosity 34 assert not (reference.startsWith('-r') and '-r' in reference[2:]) 35 if false 36 # Does not work on Novell Mono. See notes above. 37 referredAss = Assembly.reflectionOnlyLoadFrom(reference) 38 # TODO: handle all the exceptions from Assembly.loadFrom 39 else 40 if File.exists(reference) 41 # try current directory 42 if rv, print '"[reference]" found as file. Will Assembly.loadFrom().' 43 referredAss = Assembly.loadFrom(reference) 44 if rv, print 'Assembly.loadFrom() returned: [CobraCore.toTechString(referredAss)]' 45 else 46 # TODO: the problem with -lib: in both Cobra and C# is that it has no effect on runtime, 47 # you must still register the DLLs in the GAC or copy them into the same dir as the .exe 48 # because the -lib: paths are not passed into executable. 49 # So should Cobra copy the .dll's into the target directory (if their paths are not in MONO_PATH)? 50 if rv, print 'File does not exist.' 51 searchPaths = .options.getDefault('library-directory', List<of String>()) to List<of String> 52 # TODO: ?: searchPaths.add(Path.getDirectoryName(Assembly.getExecutingAssembly.location)) # try Cobra's directory - also should be added to .options.'library-directory' not to a local var 53 found = false 54 for searchPath in searchPaths 55 if rv, print 'Checking lib path: "[searchPath]"' 56 combinedPath = Path.combine(searchPath, reference) 57 if File.exists(combinedPath) 58 if rv, print '"[reference]" found as file. Will Assembly.loadFrom().' 59 referredAss = Assembly.loadFrom(combinedPath) 60 if rv, print 'Assembly.loadFrom() returned: [CobraCore.toTechString(referredAss)]' 61 found = true 62 break 63 if rv 64 if searchPaths.count 65 if not found, print 'Did not find "[reference]" in lib paths' 66 else 67 print 'No lib paths to search.' 68 if not found 69 # try system wide (GAC) 70 if reference.endsWith('.dll'), reference = reference[:-4] 71 if rv, print 'Will load with partial name "[reference]"' 72 referredAss = Utils.loadWithPartialName(reference) 73 if rv, print 'Load with partial name returned: [CobraCore.toTechString(referredAss)]' 74 if referredAss is nil, return false 75 # 2009-08-03 CE: Removed this code: 76 # reference = referredAss.location 77 # To address this: 78 # http://cobra-language.com/forums/viewtopic.php?f=4&t=501 79 # See also: ../Tests/720-libraries/100-microsoft/110-winforms-native-compiler.cobra 80 # Note the -native-compiler option in that test which triggers this. 81 # Also, it doesn't see right to have to use the full path of a GAC-based assembly anyway. 82 # But still have to end in .dll or .exe: 83 reference += if(referredAss.location.endsWith('.exe'), '.exe', '.dll') 84 # TODO: handle all the exceptions from Assembly.loadFrom 85 if referredAss 86 if _willReadDependencies # wired false in Compiler.cobra 87 for dependency in referredAss.getReferencedAssemblies 88 if rv 89 print '>> Loading dependency: [dependency]' 90 .indentPrint 91 try 92 _dotNetLoadAssembly(dependency) 93 finally 94 .outdentPrint 95 print '<< Loading dependency: [dependency]' 96 else 97 _dotNetLoadAssembly(dependency) 98 if rv, print 'Will read assembly: [referredAss]' 99 try 100 __dotNetReadAssembly(referredAss, reference <> 'Cobra.Lang.dll') 101 catch readExc as Exception 102 if rv, print 'Caught exception during read assembly: [readExc]' 103 throw 104 if rv, print 'Did read assembly: [referredAss]' 105 # reassert the preconditions. there have been bugs in the past 106 assert reference.endsWith('.dll') or reference.endsWith('.exe') 107 assert reference not in ['.dll', '.exe'] 108 .loadedReferences.add(reference) 109 if rv, print 'Returning true for __loadReference("[reference]").' 110 return true 111 else 112 if rv, print 'Returning false for __loadReference("[reference]").' 113 return false 114 115 def _dotNetLoadAssembly(assName as AssemblyName) 116 if .referenceVerbosity 117 print '>> loadAssembly [assName]' 118 .indentPrint 119 try 120 _loadAssembly(assName) 121 finally 122 .outdentPrint 123 print '<< loadAssembly [assName]' 124 else 125 _loadAssembly(assName) 126 127 def _loadAssembly(assName as AssemblyName) 128 rv = .referenceVerbosity - 1 129 if rv < 0, rv = 0 130 if assName.toString in _didLoadAssemblies 131 if rv, print 'Already loaded.' 132 return 133 _didLoadAssemblies.add(assName.toString) 134 try 135 if rv, print 'Will Assembly.load([assName])' 136 ass = Assembly.load(assName) # Will not pick up the assembly from the same directory. 137 if rv, print 'Did Assembly.load with result: [ass]' 138 catch fnfe as FileNotFoundException # In fact, will get a FileNotFoundException! 139 if rv, print 'Did Assembly.load with exception: [fnfe]. Will try .loadReference' 140 .loadReference(assName.name to !, true) # .compiler.loadReference(assName.name to !, true) 141 # TODO: compare the the name loaded to the name given with AssemblyName.referenceMatchesDefinition 142 return 143 catch exc as Exception 144 msg = 'Could not open assembly "[assName]" due to: [exc.getType.name]: [exc.message]' 145 if rv, print msg 146 throw SourceException(msg) 147 if _willReadDependencies # wired false in Compiler.cobra 148 for dependency in ass.getReferencedAssemblies 149 if rv 150 print '>> Loading dependency: [dependency]' 151 .indentPrint 152 try 153 _dotNetLoadAssembly(dependency) 154 finally 155 .outdentPrint 156 print '<< Loading dependency: [dependency]' 157 try 158 .clrReadAssembly(ass to !) # compiler.readAssembly(ass) 159 catch readExc as Exception 160 if rv, print 'Caught exception during read assembly: [readExc]' 161 throw 162 163 # Called by ClrTypeProxy 164 # dotNet specific - readLibrary 165 def clrReadAssembly(ass as Assembly) 166 """ Reads the contents of an dotNet assembly (.DLL) so that they are accessible to the program.""" 167 assert _backEnd.typeOf == ClrBackEnd # tmp guard 168 __dotNetReadAssembly(ass, false) # ScanClrType 169 170 171 #def dotNetReadAssembly(ass as Assembly) 172 # """ Reads the contents of an dotNet assembly (.DLL). EntryPoint""" 173 # __dotNetReadAssembly(ass, false) 174 175 def __dotNetReadAssembly(ass as Assembly, skipCobra as bool) 9 176 """ 10 177 Reads the contents of an assembly (.DLL) so that they are accessible to the program. 11 178 In other words, this method reads libraries. … … 17 184 print 'Reading assembly: [ass]' # extra space lines up with 'Loading reference:' 18 185 print ' at: [ass.location]' 19 186 namespaceQualNameToNameSpaceObject = Dictionary<of String, NameSpace>() 20 module = AssemblyModule(ass, .globalNS) 187 module = AssemblyModule(ass.location, .globalNS) 188 #module = AssemblyModule(ass, .globalNS) 21 189 saveModule, _curModule = _curModule, module 22 190 try 23 191 _modules.add(module) … … 54 222 else 55 223 if type.isClass 56 224 if type.name.startsWith('Extend_') and type.name.count(c'_') >= 2 57 curNameSpace.addDecl(Extension(clrType ))225 curNameSpace.addDecl(Extension(clrType, .backEnd)) 58 226 else 59 curNameSpace.addDecl(Class(clrType ))227 curNameSpace.addDecl(Class(clrType, .backEnd)) 60 228 else if type.isInterface 61 curNameSpace.addDecl(Interface(clrType ))229 curNameSpace.addDecl(Interface(clrType, .backEnd)) 62 230 else if type.isEnum 63 231 curNameSpace.addDecl(EnumDecl(curNameSpace, clrType, List<of String>(), '')) # TODO: isNames; docString? 64 232 else if type.isValueType 65 curNameSpace.addDecl(Struct(clrType ))233 curNameSpace.addDecl(Struct(clrType, .backEnd)) 66 234 else if type.isAnsiClass 67 235 # The Enum class is an example that returns false for .isClass but true for .isAnsiClass 68 curNameSpace.addDecl(Class(clrType ))236 curNameSpace.addDecl(Class(clrType, .backEnd)) 69 237 else 70 238 throw FallThroughException(type) 71 239 finally 72 240 _curModule = saveModule 73 241 74 def fixNilableMemberSigs242 def dotNetfixNilableMemberSigs 75 243 # TODO: this really needs to go in a separate file that the compiler reads each time 76 244 77 245 # TODO: look to see if what the Spec# team put together can be leveraged instead of recreating all this work! … … 124 292 print 'WARNING: Cannot fix [className] which is not a class/struct/interface. (type=[type])' # TODO: make a real warning 125 293 126 294 127 var _clrTypeToType = Dictionary<of System.Type, IType>()128 295 129 296 def typeForClrType(clrType as System.Type) as IType? 130 297 """ 131 298 Returns the Cobra type for a CLR type if the CLR type was previously scanned. 132 In other words, this is access to the c ache.299 In other words, this is access to the clr Type cache. 133 300 This not only eliminates unwanted duplication, but it is essential to the compiler when it 134 301 checks for certain things like "does this type implement IDictionary<of TKey, TValue>?" 135 302 """ … … 138 305 def addTypeForClrType(type as IType, clrType as System.Type) 139 306 require .typeForClrType(clrType) in [nil, type] 140 307 _clrTypeToType[clrType] = type 308 309 def clrTypeByName(qualifiedName as String) as System.Type 310 """ 311 Obtain the Clr type given by the fully qualified name. 312 """ 313 # eventually this method will be key in targeting different versions of the CLR 314 # suppose you are on .NET 3.0 and want to target .NET 2.0 315 t as System.Type? 316 _clrTypeCache.tryGetValue(qualifiedName, out t) 317 if t is nil 318 t = sharp'System.Type.GetType(qualifiedName)' # to System.Type 319 _clrTypeCache[qualifiedName] = t to passthrough # "to passthrough" instead of "to !" to avoid non-nil check 320 return t to passthrough 321 141 322 323 324 def installClrNativeMethods(box as Box, nativeType as NativeType) 325 meths = List<of Method>() 326 _installClrNativeMethodsFrom('System', nativeType, nativeType, box, meths) 327 _installClrNativeMethodsFrom('System', ClrNativeType(System.Math.getType), nativeType, box, meths) 142 328 329 # the next statement can be problematic in that you have to add new DecimalTools methods in Snapshot just so the compiler can see them 330 # ultimately, extensions of primitive types should be supported 331 _installClrNativeMethodsFrom('CobraLangInternal', ClrNativeType(Cobra.Lang.DecimalTools.getType), nativeType, box, meths) 332 333 # _printMethods(meths, box) 334 335 def compareMethodNames(a as Method, b as Method) as int 336 return a.name.compareTo(b.name) 337 338 def _printMethods(meths as IList<of Method>, box as Box) 339 # print out the methods, useful for documentation 340 print 341 print 'type', box.name 342 sharedMeths = for meth in meths where meth.isShared 343 if sharedMeths.count 344 sharedMeths.sort(ref .compareMethodNames) 345 print ' shared' 346 for meth in sharedMeths 347 print ' [meth.cobraSourceSignature(false)]' 348 objectMeths = for meth in meths where not meth.isShared 349 if objectMeths.count 350 objectMeths.sort(ref .compareMethodNames) 351 for meth in objectMeths 352 print ' [meth.cobraSourceSignature]' 353 354 def _installClrNativeMethodsFrom(namespaceName as String, nativeType as NativeType, 355 thisNativeType as NativeType, box as Box, meths as List<of Method>) 356 argClrType = (nativeType to ClrNativeType).backEndType 357 thisClrType = (thisNativeType to ClrNativeType).backEndType 358 # print 359 # print '** [.name], clrType' 360 isSameNativeType = argClrType == thisClrType 361 for methInfo in argClrType.getMethods(BindingFlags(DeclaredOnly, Static, Instance, Public)) 362 if methInfo.isSpecialName, continue 363 # print 364 # print '--', methInfo, methInfo.isStatic 365 name = Utils.cobraNameForNativeMemberName(methInfo.name) 366 modifiers = List<of String>() 367 if methInfo.isStatic, modifiers.add('shared') 368 newParams = List<of Param>() 369 first = true 370 cancel = false 371 for nativeParam in methInfo.getParameters 372 if first 373 first = false 374 if methInfo.isStatic 375 if methInfo.getParameters[0].parameterType == thisClrType 376 # When the first arg of the shared method is the same type, 377 # then make an instance method that can be used directly on values of the type. 378 # print methInfo.getParameters 379 # print methInfo.getParameters[0].parameterType 380 modifiers.remove('shared') 381 continue 382 else if not isSameNativeType 383 # don't want, for example, Math.sign showing up in types char, bool, etc. as a shared method 384 cancel = true 385 continue 386 param = Param(Token.empty.copy('ID', nativeParam.name), ClrTypeProxy(nativeParam.parameterType)) 387 if nativeParam.parameterType.isByRef and not nativeParam.isOut 388 param.direction = Direction.InOut 389 else if nativeParam.isOut 390 param.direction = Direction.Out 391 newParams.add(param) 392 if cancel, continue 393 meth = Method(Token.empty, Token.empty, box, name, newParams, ClrTypeProxy(methInfo.returnType), nil, modifiers, AttributeList(), '') 394 if methInfo.isStatic 395 meth.sharedMethodBacking = '[namespaceName].[argClrType.name].[methInfo.name]' 396 if 'shared' in modifiers, meth.sharedMethodBackingIsAlias = true 397 398 overload = nil to MemberOverload? 399 other = box.declForName(name) 400 if other 401 if other inherits MemberOverload 402 overload = other 403 else if other inherits AbstractMethod or other inherits ProperDexer 404 overload = MemberOverload(other to BoxMember) 405 box.registerOverload(overload to !) 406 else 407 throw FallThroughException([box, meth, other]) 408 else 409 assert box.declForName(name) is nil 410 if overload 411 overload.addMember(meth) 412 else 413 box.addDecl(meth) 414 415 meths.add(meth) 416 417 418 143 419 class Box is partial 144 420 145 get clrType as Type421 get _clrType as Type 146 422 """ 147 423 Returns the CLR System.Type boxed by the .nativeType. 148 424 Throws exception rather than return nil. 149 425 """ 150 426 return (.nativeType to ClrNativeType).clrType 151 427 152 def _scanNativeType428 var _defaultMemberName as String? 153 429 """ 430 An Indexer in CLR is known by being a property with arguments whose name matches the .memberName of a box-level DefaultMemberAttribute. 431 """ 432 433 def isClrSystemExceptionClass as bool 434 return .name == 'Exception' and .parentNameSpace and .parentNameSpace.fullName == 'System' 435 436 def _prepSystemObjectClassClr 437 # Pretend .NET is a bit more OO, consistent and elegant. 438 # C#'s typeof(X) is X.getType in Cobra. 439 existing = .declForName('getType') to BoxMember 440 overload = MemberOverload(existing) 441 .registerOverload(overload) 442 meth = Method(TokenFix.empty, TokenFix.empty, this, 'getType', List<of Param>(), .compiler.typeTypeProxy, nil, ['shared'], AttributeList(), 'Returns the Type instance that defines this type.') 443 meth.sharedMethodBacking = 'typeof' 444 overload.addMember(meth) 445 446 def _scanNativeTypeClr 447 """ 154 448 Subclasses should invoke base and then invoke the various _scanFoo methods that are appropriate for them. 155 449 """ 156 450 ensure not .needScanNativeType 157 451 _needScanNativeType = false 158 452 # print '<> _scanNativeType for [.name] in [_parentNameSpace.fullName], class is [.getType.name]' 159 453 160 def _scanIsNames 454 455 def _scanGenericArgsClr 456 if _clrType.isGenericType 457 for genArg in _clrType.getGenericArguments 458 t = (.compiler to Compiler).typeForClrType(genArg) 459 if t is nil 460 t = GenericParam(ClrNativeType(genArg), parentDefinition=this) 461 (.compiler to Compiler).addTypeForClrType(t to !, genArg) 462 _genericParams.add(t) 463 464 def _scanClrIsNames 161 465 # TODO 162 466 _isNames.add('extern') # to make the box like the ones that were in SystemInterfaces.cobra 163 467 164 468 # scan DefaultMemberAttribute for later use 165 for attr in .clrType.getCustomAttributes(true)469 for attr in _clrType.getCustomAttributes(true) 166 470 if attr inherits DefaultMemberAttribute 167 471 _defaultMemberName = attr.memberName # this attribute names the indexer for the class 168 472 break 169 473 170 def _scanGenericArgs 171 if .clrType.isGenericType 172 for genArg in .clrType.getGenericArguments 173 t = (.compiler to Compiler).typeForClrType(genArg) 174 if t is nil 175 t = GenericParam(ClrNativeType(genArg), parentDefinition=this) 176 (.compiler to Compiler).addTypeForClrType(t to !, genArg) 177 _genericParams.add(t) 178 179 def _scanImplements 180 for interf in .clrType.getInterfaces 181 if not _badRelatedType(interf) 474 def _scanClrImplements 475 for interf in _clrType.getInterfaces 476 if not _badClrRelatedType(interf) 182 477 _baseInterfaceProxies.add(ClrTypeProxy(interf)) 183 478 184 def _scan NestedTypes479 def _scanClrNestedTypes 185 480 # TODO: enable and fix resulting bugs 186 481 # for type in .clrType.getNestedTypes(BindingFlags(Instance, Static, DeclaredOnly, Public, NonPublic)) 187 for type in .clrType.getNestedTypes188 _scan NestedType(type)189 for type in .clrType.getNestedTypes(BindingFlags(Static, DeclaredOnly, NonPublic))482 for type in _clrType.getNestedTypes 483 _scanClrNestedType(type) 484 for type in _clrType.getNestedTypes(BindingFlags(Static, DeclaredOnly, NonPublic)) 190 485 if type.isEnum and not type.isPublic and not type.isNestedAssembly 191 486 # "not type.isNestedAssembly" guards against a strange WPF enum on Windows called 192 487 # Control+ControlBoolFlags whose Enum.getValues() returns enums instead of ints 193 _scan NestedType(type)488 _scanClrNestedType(type) 194 489 195 def _scan NestedType(type as System.Type)490 def _scanClrNestedType(type as System.Type) 196 491 clrType = ClrNativeType(type) 197 492 if type.isClass 198 .addDecl(Class(clrType ))493 .addDecl(Class(clrType, .compiler.backEnd)) 199 494 else if type.isInterface 200 .addDecl(Interface(clrType ))495 .addDecl(Interface(clrType, .compiler.backEnd)) 201 496 else if type.isEnum 202 497 .addDecl(EnumDecl(this, clrType, List<of String>(), '')) # TODO: isNames; docString? 203 498 else if type.isValueType 204 .addDecl(Struct(clrType ))499 .addDecl(Struct(clrType, .compiler.backEnd)) 205 500 else if type.isAnsiClass 206 501 # The Enum class is an example that returns false for .isClass but true for .isAnsiClass 207 .addDecl(Class(clrType ))502 .addDecl(Class(clrType, .compiler.backEnd)) 208 503 else 209 504 throw FallThroughException(type) 210 505 lastDecl = .declsInOrder[.declsInOrder.count-1] to dynamic 211 506 if (lastDecl to Object).getType.getProperty('ParentBox') # CC: if lastDecl responds to (get parentBox as Box?) 212 507 lastDecl.parentBox = this 213 508 214 def _scan Fields215 for fieldInfo in .clrType.getFields(BindingFlags(Instance, Static, DeclaredOnly, Public))216 if fieldInfo.declaringType is not .clrType, continue509 def _scanClrFields 510 for fieldInfo in _clrType.getFields(BindingFlags(Instance, Static, DeclaredOnly, Public)) 511 if fieldInfo.declaringType is not _clrType, continue 217 512 if fieldInfo.isAssembly, continue 218 513 if fieldInfo.isPrivate, continue 219 name = Utils.cobraNameFor SharpMemberName(fieldInfo.name)220 type = _ memberTypeResultProxy(fieldInfo, fieldInfo.fieldType)514 name = Utils.cobraNameForNativeMemberName(fieldInfo.name) 515 type = _clrMemberTypeResultProxy(fieldInfo, fieldInfo.fieldType) 221 516 attrs = AttributeList() 222 517 isNames = [if(fieldInfo.isPublic, 'public', 'protected')] # private was guarded against above 223 518 if fieldInfo.isStatic, isNames.add('shared') … … 234 529 varr.binaryName = fieldInfo.name 235 530 .addDecl(varr) 236 531 237 def _scan Initializers238 for conInfo in .clrType.getConstructors(BindingFlags(Instance, DeclaredOnly, Public, NonPublic))532 def _scanClrInitializers 533 for conInfo in _clrType.getConstructors(BindingFlags(Instance, DeclaredOnly, Public, NonPublic)) 239 534 if conInfo.isPrivate, continue 240 if conInfo.declaringType is not .clrType, continue535 if conInfo.declaringType is not _clrType, continue 241 536 skip = false 242 537 for paramInfo in conInfo.getParameters 243 if _bad RelatedType(paramInfo.parameterType)538 if _badClrRelatedType(paramInfo.parameterType) 244 539 skip = true 245 540 break 246 541 if skip, continue 247 params = _scan Params(conInfo.getParameters)542 params = _scanClrParams(conInfo.getParameters) 248 543 isNames = _isNamesForMethodInfo(conInfo) 249 544 attribs = _attribsForMethodInfo(conInfo) 250 545 docString = '' # TODO: get doc string for class? … … 264 559 else 265 560 .addDecl(initer) 266 561 267 def _scan Properties268 for propInfo in .clrType.getProperties(BindingFlags(Instance, Static, DeclaredOnly, Public, NonPublic))562 def _scanClrProperties 563 for propInfo in _clrType.getProperties(BindingFlags(Instance, Static, DeclaredOnly, Public, NonPublic)) 269 564 getMethod = propInfo.getGetMethod(true) # true means include nonpublic 270 565 setMethod = propInfo.getSetMethod(true) 271 566 visible = false … … 278 573 theMethod = setMethod to ! 279 574 visible = true 280 575 if not visible, continue 281 if theMethod.declaringType is not .clrType, continue576 if theMethod.declaringType is not _clrType, continue 282 577 if propInfo.name == _defaultMemberName and propInfo.getIndexParameters and propInfo.getIndexParameters.length 283 _scan Indexer(propInfo)578 _scanClrIndexer(propInfo) 284 579 continue 285 if _bad RelatedType(propInfo.propertyType)580 if _badClrRelatedType(propInfo.propertyType) 286 581 continue 287 582 attribs = AttributeList() # TODO: 288 583 docString = '' # TODO: get doc string 289 584 # TODO: eventually the isNames need to be an the property part level (get or set) rather than the property level, like in C# and the CLR runtime 290 585 isNames = _isNamesForMethodInfo(theMethod) 291 prop = Property(TokenFix.empty, TokenFix.empty, this, Utils.cobraNameFor SharpMemberName(propInfo.name), _memberTypeResultProxy(propInfo, propInfo.propertyType), isNames, attribs, docString)586 prop = Property(TokenFix.empty, TokenFix.empty, this, Utils.cobraNameForNativeMemberName(propInfo.name), _clrMemberTypeResultProxy(propInfo, propInfo.propertyType), isNames, attribs, docString) 292 587 prop.binaryName = propInfo.name 293 588 if propInfo.canRead 294 589 prop.makeGetPart(TokenFix.empty) … … 296 591 prop.makeSetPart(TokenFix.empty) 297 592 .addDecl(prop) 298 593 299 def _scan Indexer(propInfo as PropertyInfo)594 def _scanClrIndexer(propInfo as PropertyInfo) 300 595 for paramInfo in propInfo.getIndexParameters 301 if _bad RelatedType(paramInfo.parameterType)596 if _badClrRelatedType(paramInfo.parameterType) 302 597 return 303 params = _scan Params(propInfo.getIndexParameters)598 params = _scanClrParams(propInfo.getIndexParameters) 304 599 attribs = AttributeList() # TODO: 305 600 docString = '' # TODO: get doc string for class? 306 601 if propInfo.canRead … … 309 604 isNames = _isNamesForMethodInfo(propInfo.getSetMethod(true) to !) 310 605 else 311 606 throw FallThroughException(propInfo) 312 indexer = Indexer(TokenFix.empty, TokenFix.empty, this, r'[]', params, _ memberTypeResultProxy(propInfo, propInfo.propertyType), isNames, attribs, docString)607 indexer = Indexer(TokenFix.empty, TokenFix.empty, this, r'[]', params, _clrMemberTypeResultProxy(propInfo, propInfo.propertyType), isNames, attribs, docString) 313 608 overload as MemberOverload? = nil 314 609 other = .declForName(r'[]') 315 610 if other … … 325 620 else 326 621 .addDecl(indexer) 327 622 328 def _scan Methods329 for methInfo in .clrType.getMethods(BindingFlags(Instance, Static, DeclaredOnly, Public, NonPublic))623 def _scanClrMethods 624 for methInfo in _clrType.getMethods(BindingFlags(Instance, Static, DeclaredOnly, Public, NonPublic)) 330 625 if methInfo.isSpecialName, continue 331 626 if methInfo.isAssembly, continue 332 627 if methInfo.isPrivate, continue 333 if methInfo.declaringType is not .clrType, continue628 if methInfo.declaringType is not _clrType, continue 334 629 skip = false 335 if _bad RelatedType(methInfo.returnType)630 if _badClrRelatedType(methInfo.returnType) 336 631 skip = true 337 632 else 338 633 for paramInfo in methInfo.getParameters 339 if _bad RelatedType(paramInfo.parameterType)634 if _badClrRelatedType(paramInfo.parameterType) 340 635 skip = true 341 636 break 342 637 if skip, continue … … 348 643 # TODO: these are mostly (maybe all) explicit implementations of interfaces 349 644 # print 'xxx dotted name: [methInfo]' 350 645 continue 351 name = Utils.cobraNameFor SharpMemberName(methInfo.name)646 name = Utils.cobraNameForNativeMemberName(methInfo.name) 352 647 genericParams = List<of IType>() 353 648 for genArg in methInfo.getGenericArguments 354 649 genericParams.add(GenericParam(ClrNativeType(genArg))) 355 params = _scan Params(methInfo.getParameters)650 params = _scanClrParams(methInfo.getParameters) 356 651 isNames = _isNamesForMethodInfo(methInfo) 357 652 attribs = _attribsForMethodInfo(methInfo) 358 653 docString = '' # TODO: get doc string for class? 359 654 implementsTypeNode as ITypeProxy? # TODO: explicit interface implementation? 360 method = Method(TokenFix.empty, TokenFix.empty, this, name, genericParams, params, _ memberTypeResultProxy(methInfo, methInfo.returnType), implementsTypeNode, isNames, attribs, docString)655 method = Method(TokenFix.empty, TokenFix.empty, this, name, genericParams, params, _clrMemberTypeResultProxy(methInfo, methInfo.returnType), implementsTypeNode, isNames, attribs, docString) 361 656 method.binaryName = methInfo.name 362 657 overload as MemberOverload? = nil 363 658 other = .declForName(name) … … 374 669 else 375 670 .addDecl(method) 376 671 377 def _scan Params(paramInfos as ParameterInfo[]?) as List<of Param>672 def _scanClrParams(paramInfos as ParameterInfo[]?) as List<of Param> 378 673 """ 379 674 Returns a list of Cobra parameters given a list of CLR Reflection ParameterInfos. 380 675 """ … … 394 689 isRef = paramInfo.parameterType.isByRef and not paramInfo.isOut 395 690 # Unpack "ByRef" types. Comes up with WinForm's .processCmdKey which has a ByRef struct argument (Message&) 396 691 parameterType = if(isRef, paramInfo.parameterType.getElementType, paramInfo.parameterType) 397 type = _ memberTypeProxy(parameterType, isNotNull)692 type = _clrMemberTypeProxy(parameterType, isNotNull) 398 693 if isVari, type = VariTypeProxy(type) 399 694 # In XNA 3.1 some types such as GraphicsDevice and Texture have a Dispose method 400 695 # with one argument with an empty name (''). Cobra doesn't dig that. … … 413 708 params.add(param) 414 709 return params 415 710 416 def _scan Events417 for eventInfo in .clrType.getEvents(BindingFlags(Instance, Static, DeclaredOnly, Public, NonPublic))711 def _scanClrEvents 712 for eventInfo in _clrType.getEvents(BindingFlags(Instance, Static, DeclaredOnly, Public, NonPublic)) 418 713 if eventInfo.getAddMethod is nil, continue 419 714 if eventInfo.getAddMethod.isAssembly, continue 420 715 if eventInfo.getAddMethod.isPrivate, continue 421 716 if eventInfo.isSpecialName, continue 422 if eventInfo.declaringType is not .clrType, continue717 if eventInfo.declaringType is not _clrType, continue 423 718 if '.' in eventInfo.name 424 719 # TODO: these are mostly (maybe all) explicit implementations of interfaces 425 720 # print 'xxx dotted name: [methInfo]' 426 721 continue 427 name = Utils.cobraNameFor SharpMemberName(eventInfo.name)722 name = Utils.cobraNameForNativeMemberName(eventInfo.name) 428 723 if eventInfo.getAddMethod # Gtk.Object has such a beast (InternalDestroyed) 429 724 isNames = _isNamesForMethodInfo(eventInfo.getAddMethod to !) 430 725 else … … 454 749 def _attribsForMethodInfo(mi as MethodBase) as AttributeList 455 750 return AttributeList() # TODO: 456 751 457 def _bad RelatedType(t as Type?) as bool752 def _badClrRelatedType(t as Type?) as bool 458 753 """ 459 754 Returns true if the given type, which comes from a parameter or return value, is unsupported. 460 755 For example, it's not public or it's nested. Members with bad types are skipped when scanning DLLs. … … 468 763 469 764 # FYI: MS .NET 2.0 (but not Mono 1.2.6) will return true for .isNotPublic for types are "by ref" 470 765 if t.isByRef # TODO: or t.isArray 471 return _bad RelatedType(t.getElementType)766 return _badClrRelatedType(t.getElementType) 472 767 if t.isNotPublic or t.isNestedAssembly # .isNestedAssembly should imply .isNotPublic but at least in System.Windows.Forms, on Novell Mono 1.2.6, Control+LayoutType reports .isNestedAssembly but not .isNotPublic 473 768 return true 474 769 475 770 return false 476 771 477 def _ memberTypeProxy(clrType as Type?) as ITypeProxy478 return _ memberTypeProxy(clrType, false)772 def _clrMemberTypeProxy(clrType as Type?) as ITypeProxy 773 return _clrMemberTypeProxy(clrType, false) 479 774 480 def _ memberTypeProxy(clrType as Type?, notNullAttr as bool) as ITypeProxy775 def _clrMemberTypeProxy(clrType as Type?, notNullAttr as bool) as ITypeProxy 481 776 """ 482 Returns a type proxy for a member type such as a parameter type or method return type.777 Returns a type proxy for a member type such as a parameter type 483 778 In CLR, reference types are nilable by default, but you can pass `true` for `notNullAttr` to indicate there was a NotNullAttribute in the DLL. 484 779 """ 485 780 if clrType is nil … … 493 788 tp = NilableTypeProxy(tp) 494 789 return tp 495 790 496 def _ memberTypeResultProxy(member as MemberInfo, clrType as Type?) as ITypeProxy791 def _clrMemberTypeResultProxy(member as MemberInfo, clrType as Type?) as ITypeProxy 497 792 """ 498 Returns a type proxy for a member type such as a parameter type or method return type.793 Returns a type proxy for a member result type such as a method return type, property or field. 499 794 In CLR, reference types are nilable by default. 500 795 """ 501 796 if clrType is nil … … 523 818 class Class 524 819 is partial 525 820 526 def _scanNativeType 527 base._scanNativeType 528 _scan IsNames529 _scan Implements530 _scan NestedTypes531 _scan Fields532 _scan Initializers533 _scan Properties534 _scan Methods535 _scan Events536 # TODO: _scan Enums821 def _scanNativeTypeClr 822 base._scanNativeTypeClr 823 _scanClrIsNames 824 _scanClrImplements 825 _scanClrNestedTypes 826 _scanClrFields 827 _scanClrInitializers 828 _scanClrProperties 829 _scanClrMethods 830 _scanClrEvents 831 # TODO: _scanClrEnums 537 832 # TODO: scan all other nested types 538 833 539 834 540 835 class Interface 541 836 is partial 542 837 543 def _scanNativeType 544 base._scanNativeType 545 _scan IsNames546 _scan Implements547 _scan NestedTypes548 _scan Fields549 _scan Properties550 _scan Methods551 _scan Events838 def _scanNativeTypeClr 839 base._scanNativeTypeClr 840 _scanClrIsNames 841 _scanClrImplements 842 _scanClrNestedTypes 843 _scanClrFields 844 _scanClrProperties 845 _scanClrMethods 846 _scanClrEvents 552 847 553 848 554 849 class Struct 555 850 is partial 556 851 557 def _scanNativeType 558 base._scanNativeType 559 _scan IsNames560 _scan Implements561 _scan NestedTypes562 _scan Fields563 _scan Initializers564 _scan Properties565 _scan Methods566 _scan Events852 def _scanNativeTypeClr 853 base._scanNativeTypeClr 854 _scanClrIsNames 855 _scanClrImplements 856 _scanClrNestedTypes 857 _scanClrFields 858 _scanClrInitializers 859 _scanClrProperties 860 _scanClrMethods 861 _scanClrEvents 567 862 568 863 569 864 class Extension 570 865 is partial 571 866 572 def _scanNativeType 867 def _scanNativeTypeClr 573 868 # this only for Cobra specific extensions. Example: class Extend_String_1939 574 base._scanNativeType 575 _scan IsNames576 #_scan Implements577 #_scan NestedTypes578 #_scan Fields579 #_scan Initializers580 #_scan Properties581 _scan Methods869 base._scanNativeTypeClr 870 _scanClrIsNames 871 #_scanClrImplements 872 #_scanClrNestedTypes 873 #_scanClrFields 874 #_scanClrInitializers 875 #_scanClrProperties 876 _scanClrMethods 582 877 #_scanEvents 583 878 584 def _scan Params(paramInfos as ParameterInfo[]?) as List<of Param>879 def _scanClrParams(paramInfos as ParameterInfo[]?) as List<of Param> is override 585 880 # the first argument is implicit in an Extension 586 results = base._scan Params(paramInfos)881 results = base._scanClrParams(paramInfos) 587 882 return results[1:] 883 884 def clrExtnNativeType(nativeType as NativeType) as NativeType 885 # the real extended type is the type of the first argument of any method 886 for methInfo in _clrType.getMethods 887 nativeType = ClrNativeType(methInfo.getParameters[0].parameterType) 888 break 889 return nativeType 890 891 892 893 class EnumDecl 894 is partial 895 896 def _setUnderlyingTypeClr 897 _storageTypeNode = ClrTypeProxy(Enum.getUnderlyingType((_nativeType to ClrNativeType).backEndType)) 898 899 def _scanNativeTypeClr 900 # TODO: read attribs 901 _needScanNativeType = false 902 clrType = (_nativeType to ClrNativeType).clrType 903 isByte = Enum.getUnderlyingType(clrType).name == 'Byte' 904 is64 = Enum.getUnderlyingType(clrType).name == 'Int64' 905 isU32 = Enum.getUnderlyingType(clrType).name == 'UInt32' 906 isU64 = Enum.getUnderlyingType(clrType).name == 'UInt64' 907 values = Enum.getValues(clrType) 908 i = 0 909 #print clrType 910 for name in Enum.getNames(clrType) 911 #print name 912 value = values.getValue(i) 913 # CC: lameness follows 914 if isByte 915 intValue = int.parse((value to uint8).toString) 916 else if is64 917 try 918 intValue = int.parse((value to int64).toString) 919 catch OverflowException 920 intValue = 999 # CC: omg. but probably doesn't affect anything. we're reading the DLL here, not creating one 921 else if isU32 922 try 923 intValue = int.parse((value to uint32).toString) 924 catch OverflowException 925 intValue = 2147483647 926 else if isU64 927 try 928 intValue = int.parse((value to uint64).toString) 929 catch OverflowException 930 intValue = 2147483647 931 else 932 intValue = value to int 933 member = EnumMember(name, intValue) 934 member.enumDecl = this 935 .addDecl(member) 936 i += 1 937 938 -
Source/BackEndClr/ClrBackEnd.cobra
1 use System.Diagnostics 1 2 use System.Reflection 2 3 3 4 … … 3 4 class ClrBackEnd inherits BackEnd 4 5 6 var _objectTypeProxy as AbstractTypeProxy = ClrTypeProxy(Object) 7 var _typeTypeProxy as AbstractTypeProxy = ClrTypeProxy(Type) 8 5 9 cue init(compiler as Compiler) 6 10 base.init(compiler) 11 _name = 'c#-clr' 12 _rtlName = 'Cobra.Lang.dll' 13 14 _tagToTypeName = { 15 'Object' : 'System.Object', 16 'Type' : 'System.Type', 17 'String' : 'System.String', 18 'Exception' : 'System.Exception', 19 'Delegate' : 'System.Delegate', 20 'Attribute' : 'System.Attribute', 21 'ICloneable': 'System.ICloneable', 22 'IEnumerable': 'System.Collections.IEnumerable', 23 'IEnumerator': 'System.Collections.IEnumerator', 24 'IEnumerable<of>' : 'System.Collections.Generic.IEnumerable<of>', 25 'IEnumerator<of>' : 'System.Collections.Generic.IEnumerator<of>', 26 'IDictionaryEnumerator' : 'System.Collections.IDictionaryEnumerator', 27 'ICollection': 'System.Collections.ICollection', 28 'ICollection<of>': 'System.Collections.Generic.ICollection<of>', 29 'IList' : 'System.Collections.IList', 30 'IList<of>' : 'System.Collections.Generic.IList<of>', 31 'List<of>': 'System.Collections.Generic.List<of>', 32 'IDictionary': 'System.Collections.IDictionary', 33 'IDictionary<of,>': 'System.Collections.Generic.IDictionary<of,>', 34 'Dictionary<of,>' : 'System.Collections.Generic.Dictionary<of,>', 35 'Set<of>': 'Cobra.Lang.Set<of>', 7 36 37 'bool' : 'System.Boolean', 38 'char' : 'System.Char', 39 'decimal': 'System.Decimal', 40 'single': 'System.Single', 41 'double': 'System.Double', 42 'sbyte' : 'System.SByte', 43 'int16' : 'System.Int16', 44 'int32' : 'System.Int32', 45 'int64' : 'System.Int64', 46 'byte' : 'System.Byte', 47 'uint16': 'System.UInt16', 48 'uint32': 'System.UInt32', 49 'uint64': 'System.UInt64', 50 } 51 8 52 def makePhases(phases as IList<of Phase>) is override 9 53 phases.add(GenerateSharpCodePhase(.compiler)) … … 13 57 def computeOutName as String is override 14 58 return .compiler.computeOutNameSharp 15 59 60 def genNativeModule(filename as String, verbosity as int) as Module? is override 61 m as Module? = nil 62 if filename.endsWith('.cs') 63 if verbosity, print 'Noting [filename] as SharpModule' # extra space to line up with 'Parsing [filename]' 64 m = SharpModule(filename, verbosity) 65 return m 66 67 def setupRunProcess(baseExe as String, fullExe as String) as Process is override 68 p = Process() 69 branch .compiler.platform 70 on PlatformEnum.Microsoft 71 p.startInfo.fileName = baseExe 72 on PlatformEnum.Novell 73 p.startInfo.fileName = 'mono' 74 args = '' 75 # mono also needs --debug when running 76 if .compiler.options.getDefault('debug', '') not in ['', '-'] 77 args += '--debug ' 78 args += '"[fullExe]"' 79 p.startInfo.arguments = args + ' ' 80 else 81 throw FallThroughException(.compiler.platform) 82 return p 83 84 def setDefaultUseDirectives(ns as NameSpace) is override 85 useToken = Token('(implicit)', 1, 1, 1, 'USE', 'use', nil) # TODO: make an "implicit" token 86 ns.addUseDirective(UseDirective(useToken, ['System'])) 87 ns.addUseDirective(UseDirective(useToken, ['System', 'Collections', 'Generic'])) 88 ns.addUseDirective(UseDirective(useToken, ['System', 'IO'])) 89 ns.addUseDirective(UseDirective(useToken, ['System', 'Text'])) 90 ns.addUseDirective(UseDirective(useToken, ['Cobra', 'Lang'])) 91 92 def fixLibExtension(libRef as String) as String is override 93 """ 94 Augment given lib reference string with backend extension if not already have one 95 """ 96 or require libRef.length 97 and ensure result.endsWith('.dll') or result.endsWith('.exe') 98 if not libRef.endsWith('.dll') and not libRef.endsWith('.exe') 99 libRef += '.dll' 100 return libRef 101 102 def loadLibReference(reference as String) as bool is override 103 return .compiler.dotNetLoadReference(reference) # in ScanClrType 104 105 def readSystemTypes is override 106 # TODO: Move the called support methods below out of Compiler 107 108 # TODO: support targeting a specific CLR version, but not below 2.0 109 #.compiler.readAssembly(Assembly.load('mscorlib.dll') to !) 110 .compiler.clrReadAssembly(Assembly.load('mscorlib.dll') to !) 16 111 112 # TODO: .readAssembly(Assembly.loadFrom('System.dll') to !) 113 # gives: Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.dll' or one of its dependencies. The system cannot find the file specified. 114 115 t = System.Diagnostics.Process.getType 116 #.compiler.readAssembly(t.assembly) # System.dll 117 .compiler.clrReadAssembly(t.assembly) # System.dll 118 119 def fixNilableMemberSigs is override 120 .compiler.dotNetfixNilableMemberSigs # in ScanClrType 121 122 # Types 123 get objectTypeProxy from var is override 124 """Type proxy for BE root of Object hierarchy.""" 125 get typeTypeProxy from var is override 126 """Type proxy for BE notion of a class describing a Type.""" 127 128 def cobraNameForNativeBoxName(nativeBoxName as String) as String is override 129 return ClrTypeProxy.cobraNameForSharpBoxName(nativeBoxName) 130 131 def nativeTypeProxy(type as NativeType) as NativeTypeProxy is override 132 return ClrTypeProxy(type) 133 134 def nativeType(type as dynamic) as NativeType is override 135 return ClrNativeType(type) 136 137 def nativeTypeByName(qualifiedNameOrTag as String) as NativeType is override 138 qualifiedName = .resolveTypeTag(qualifiedNameOrTag) 139 return ClrNativeType(.compiler.clrTypeByName(qualifiedName)) 140 /# 141 These are the type tags used directly by the compiler code. 142 143 bool 'System.Boolean' 144 char 'System.Char' 145 decimal 'System.Decimal' 146 single 'System.Single' 147 double 'System.Double' 148 sbyte 'System.SByte' 149 int16 'System.Int16' 150 int32 'System.Int32' 151 int64 'System.Int64' 152 byte 'System.Byte' 153 uint16 'System.UInt16' 154 uint32 'System.UInt32' 155 uint64 'System.UInt64' 156 #/ 157 158 def installNativeMethods(box as Box, nativeType as NativeType) is override 159 .compiler.installClrNativeMethods(box, nativeType) # in ScanClrType 160 161 def addArrayInterfaces( interfaces as List<of ITypeProxy>) is override 162 iclone = .compiler.libraryType('ICloneable') 163 interfaces.insert(0, iclone to ITypeProxy) 164 165 166 17 167 class GenerateSharpCodePhase inherits Phase 18 168 19 169 cue init(c as Compiler) -
Source/CobraParser.cobra
62 62 """ 63 63 64 64 test 65 c = Compiler() 65 66 p = CobraParser() 66 67 p.globalNS = NameSpace(Token.empty, '(global)') 67 68 p.typeProvider = BasicTypeProvider() 69 p.backEnd = BasicBackEnd(c) 68 70 module = p.parseSource('test1', 'class Test\n\tpass\n') 69 71 decls = (module to dynamic).topNameSpace.declsInOrder 70 72 decl = decls[decls.count-1] … … 76 78 p = CobraParser() 77 79 p.globalNS = NameSpace(Token.empty, '(global)') 78 80 p.typeProvider = BasicTypeProvider() 81 p.backEnd = BasicBackEnd(c) 79 82 p.parseSource('test2', 'class Test\n\tdef main is shared\n\t\treturn\n') 80 83 81 c = Compiler()82 p = CobraParser(typeProvider=c, warningRecorder=c, errorRecorder=c, globalNS=c.globalNS )84 c = TestCompiler() # to default backend to something on init 85 p = CobraParser(typeProvider=c, warningRecorder=c, errorRecorder=c, globalNS=c.globalNS, backEnd=c.backEnd) 83 86 p.parseSource('test3', '') 84 87 85 c = Compiler()86 p = CobraParser(typeProvider=c, warningRecorder=c, errorRecorder=c, globalNS=c.globalNS )88 c = TestCompiler() 89 p = CobraParser(typeProvider=c, warningRecorder=c, errorRecorder=c, globalNS=c.globalNS, backEnd=c.backEnd) 87 90 p.parseSource('test4', ' ') 88 91 89 92 shared … … 125 128 var _expectAnonymousMethodExprStack as Stack<of AnonymousMethodExpr> 126 129 127 130 var _typeProvider as ITypeProvider? 131 var _backEnd as BackEnd? 132 # compiler is available from _backEnd.compiler 128 133 129 134 var _parseCommandLineArgs as ParseCommandLineArgsSig? 130 135 … … 142 147 _curLoopBlockDepth = 0 143 148 144 149 pro typeProvider from var 150 pro backEnd from var 145 151 146 152 pro parseCommandLineArgs from var 147 153 """ … … 178 184 return _nameSpaceStack.peek 179 185 180 186 def parseFileNamed(fileName as String) as CobraModule 181 require .typeProvider 187 require .typeProvider and .backEnd 182 188 if .verbosity >= 2, print 'Parsing [fileName]' 183 189 _fileName = fileName 184 190 source = File.readAllText(_fileName to !) 185 191 return .parseSource(fileName, source) 186 192 187 193 def parseSource(source as String) as CobraModule 188 require .typeProvider 194 require .typeProvider and .backEnd 189 195 return .parseSource('(no file name)', source) 190 196 191 197 def parseSource(fileName as String, source as String) as CobraModule … … 246 252 .recordError(te.token, te.message) 247 253 return false 248 254 249 # TODO: fold all occcurrences of this lookup to a helper 250 compiler = .typeProvider to? Compiler 251 if compiler 252 compiler.noWarningLines.addRange(tokenizer.noWarningLines) 253 compiler.linesCompiled += tokenizer.linesCompiled 254 compiler.tokensCompiled += tokens.count 255 compiler = .backEnd.compiler 256 compiler.noWarningLines.addRange(tokenizer.noWarningLines) 257 compiler.linesCompiled += tokenizer.linesCompiled 258 compiler.tokensCompiled += tokens.count 255 259 256 260 if tokenizer.errors.count 257 261 for error in tokenizer.errors … … 356 360 try 357 361 topNS = _module.topNameSpace 358 362 if not _fileName.endsWith('SystemInterfaces.cobra') 359 # TODO: make an "implicit" token 360 useToken = Token(_fileName, 1, 1, 1, 'USE', 'use', nil) 361 # default use directives 362 topNS.addUseDirective(UseDirective(useToken, ['System'])) 363 topNS.addUseDirective(UseDirective(useToken, ['System', 'Collections', 'Generic'])) 364 topNS.addUseDirective(UseDirective(useToken, ['System', 'IO'])) 365 topNS.addUseDirective(UseDirective(useToken, ['System', 'Text'])) 366 topNS.addUseDirective(UseDirective(useToken, ['Cobra', 'Lang'])) 363 .backEnd.setDefaultUseDirectives(topNS) 367 364 while .peek, .parseTopLevel 368 365 finally 369 366 _nameSpaceStack.pop … … 455 452 if not typeName.text.isOneOf('decimal.float.float32.float64.') 456 453 .throwError('Compiler directive "number": unrecognized type "[typeName.text]". Must be one of "decimal", "float", "float32" or "float64".') 457 454 .expect('EOL') 458 comp = .typeProvider to? Compiler 459 if comp, comp.numberTypeName = typeName.text 455 .backEnd.compiler.numberTypeName = typeName.text 460 456 on 'ref' 461 457 pathToken = .grab 462 458 if not pathToken.which.isOneOf('ID.STRING_SINGLE.STRING_DOUBLE.') -
Source/Types.cobra
1 1 use System.Reflection 2 2 3 4 3 class NativeType is abstract 5 4 """ 6 5 The abstract base class for a boxed native type of the platform being compiled to. … … 42 41 TODO: Add contract to enforce above statement 43 42 """ 44 43 44 get isSystemObjectClass as bool is abstract 45 """ 46 Return true if this is the Native Type Object for the root Object of the class hierarchy. 47 e.g. like System.Object in .Net, java.lang.Object in java 48 """ 49 50 get isSystemTypeClass as bool is abstract 51 """ 52 Return true if this is the Native Type Object for a System Type. 53 e.g. like System.Type in .Net, java.lang.class in java 54 """ 55 45 56 def customAttributes as IList<of dynamic> is abstract 46 57 """ 47 58 Return a list of custom attributes attached to this type. … … 52 63 53 64 def getHashCode as int is override 54 65 throw Exception('Subclasses must override .getHashCode') 66 67 class NullNativeType inherits NativeType 68 """ 69 Valid but empty nativeType for Tests 70 """ 71 var _full = '' 72 var _name = '' 73 74 cue init(qualName as String) 75 base.init 76 _full = qualName 77 l = qualName.split('.') 78 _name = l[l.length-1] # l.last or l[-1:][0] 79 80 get name as String is override 81 return _name 82 83 get fullName as String is override 84 return _full 55 85 86 get isValueType as bool is override 87 return false 88 89 get baseType as NativeType? is override 90 return this # wrong either way - cant get ObjectType and isnt Object root so cant return nil 91 92 def customAttributes as IList<of dynamic> is override 93 return List<of dynamic>() 56 94 95 def equals(other as Object?) as bool is override 96 return false 97 98 def getHashCode as int is override 99 return 999666 100 101 get isSystemObjectClass as bool is override 102 return false 103 104 get isSystemTypeClass as bool is override 105 return false 106 57 107 interface ITypeProvider 58 108 """ 59 A type provider can provide essential types and serve as a place 60 t hey are "uniqued" in order to avoid type duplication.109 A type provider can provide essential types and serve as a place to centralise the provision of these 110 types. They are "uniqued" in order to avoid type duplication. 61 111 62 112 The Cobra types themselves rely on having a type provider available to implement some of their methods. 63 113 64 The main type provider is Compiler.114 The main type provider is in the Compiler. 65 115 There is also a BasicTypeProvider that is useful in setting up tests. 66 116 """ 67 117 … … 114 164 115 165 def defaultType as IType 116 166 117 167 168 # TODO: rename to TypeProvider, change to a "mix-in" and have the Compiler class inherit it 118 169 class BasicTypeProvider 119 170 implements ITypeProvider 120 171 """ 121 T ODO: rename to TypeProvider, change to a "mix-in" and have the Compiler class inherit it172 This is the base and also can be used as a test TypeProvider 122 173 """ 123 174 124 175 var _anyFloatType as AnyFloatType? … … 264 315 _variTypes[type] = vt = VariType(type) 265 316 return vt 266 317 267 def libraryType(qualifiedName as String) as IType268 return BasicLibraryType(.nativeType(qualifiedName))269 270 def nativeType(qualifiedName as String) as NativeType271 return ClrNativeType(sharp'System.Type.GetType(qualifiedName)' to System.Type)272 273 318 def defaultType as IType 274 319 if _defaultType is nil 275 320 _defaultType = .nilableType(.dynamicType) 276 321 return _defaultType to ! 277 322 323 def libraryType(qualifiedName as String) as IType 324 return BasicLibraryType(.nativeType(qualifiedName)) 278 325 326 def nativeType(qualifiedName as String) as NativeType 327 return NullNativeType(qualifiedName) 328 #return ClrNativeType(sharp'System.Type.GetType(qualifiedName)' to System.Type) 329 330 279 331 class BasicLibraryType 280 332 is partial 281 333 implements IType … … 288 340 shared 289 341 290 342 def systemObjectType as BasicLibraryType 291 return BasicLibraryType(ClrNativeType(sharp'typeof(System.Object)')) 343 #nativeType = .compiler.ObjectNativeType 344 nativeType = ClrNativeType(sharp'typeof(System.Object)') 345 return BasicLibraryType(nativeType) 292 346 293 347 var _nativeType as NativeType 294 348 … … 513 567 def unNilReturnType 514 568 pass 515 569 570 516 571 517 572 interface IType 518 573 is partial … … 843 898 844 899 var _systemAliasProxy as ITypeProxy? 845 900 """ 846 Subclasses set this to a LibraryTypeProxy instead of ClrTypeProxy because, for example, the901 Subclasses set this to a LibraryTypeProxy instead of a backendTypeProxy because, for example, the 847 902 ClrTypeProxy for the clr type System.Boolean would return a Cobra BoolType instance! Then 848 903 the primitive type would have a self reference when what it really wanted was the Struct 849 904 instance for System.Boolean. … … 876 931 _systemAliasType = _systemAliasProxy.realType 877 932 _systemAliasType.bindInh 878 933 if .compiler # will be nil during unit tests 879 _box = Class(Token.empty, Token.empty, '[.getType.name]_[.serialNum]', List<of IType>(), List<of String>(), AttributeList(), ClrTypeProxy(Object), List<of ITypeProxy>(), List<of ITypeProxy>(), nil) 934 baseNode = .compiler.objectTypeProxy 935 _box = Class(Token.empty, Token.empty, '[.getType.name]_[.serialNum]', List<of IType>(), List<of String>(), AttributeList(), baseNode, List<of ITypeProxy>(), List<of ITypeProxy>(), nil) 880 936 if _systemAliasType inherits Box 881 937 for bip in _systemAliasType.baseInterfaceProxies 882 938 _box.baseInterfaceProxies.add(bip) … … 884 940 885 941 def _bindInt 886 942 base._bindInt 887 888 943 if _systemAliasType, _systemAliasType.bindInt 889 890 944 if .compiler and _nativeType 891 meths = List<of Method>() 892 _installNativeMethodsFrom('System', _nativeType to !, meths) 893 _installNativeMethodsFrom('System', ClrNativeType(System.Math.getType), meths) 894 895 # the next statement can be problematic in that you have to add new DecimalTools methods in Snapshot just so the compiler can see them 896 # ultimately, extensions of primitive types should be supported 897 _installNativeMethodsFrom('CobraLangInternal', ClrNativeType(Cobra.Lang.DecimalTools.getType), meths) 898 899 # _printMethods(meths) 900 945 .compiler.installNativeMethods(_box to !, _nativeType to !) # BackEnd 901 946 _box.bindInt 902 947 903 def _printMethods(meths as IList<of Method>)904 # print out the methods905 # useful for documentation906 print907 print 'type', .name908 sharedMeths = for meth in meths where meth.isShared909 if sharedMeths.count910 sharedMeths.sort(ref .compareMethodNames)911 print ' shared'912 for meth in sharedMeths913 print ' [meth.cobraSourceSignature(false)]'914 objectMeths = for meth in meths where not meth.isShared915 if objectMeths.count916 objectMeths.sort(ref .compareMethodNames)917 for meth in objectMeths918 print ' [meth.cobraSourceSignature]'919 920 def _installNativeMethodsFrom(namespaceName as String, nativeType as NativeType, meths as List<of Method>)921 argClrType = (nativeType to ClrNativeType).clrType922 thisClrType = (_nativeType to ClrNativeType).clrType923 box = _box924 # print925 # print '** [.name], clrType'926 isSameNativeType = argClrType == thisClrType927 for methInfo in argClrType.getMethods(BindingFlags(DeclaredOnly, Static, Instance, Public))928 if methInfo.isSpecialName, continue929 # print930 # print '--', methInfo, methInfo.isStatic931 name = Utils.cobraNameForSharpMemberName(methInfo.name)932 modifiers = List<of String>()933 if methInfo.isStatic, modifiers.add('shared')934 newParams = List<of Param>()935 first = true936 cancel = false937 for nativeParam in methInfo.getParameters938 if first939 first = false940 if methInfo.isStatic941 if methInfo.getParameters[0].parameterType == thisClrType942 # When the first arg of the shared method is the same type,943 # then make an instance method that can be used directly on values of the type.944 # print methInfo.getParameters945 # print methInfo.getParameters[0].parameterType946 modifiers.remove('shared')947 continue948 else if not isSameNativeType949 # don't want, for example, Math.sign showing up in types char, bool, etc. as a shared method950 cancel = true951 continue952 param = Param(Token.empty.copy('ID', nativeParam.name), ClrTypeProxy(nativeParam.parameterType))953 if nativeParam.parameterType.isByRef and not nativeParam.isOut954 param.direction = Direction.InOut955 else if nativeParam.isOut956 param.direction = Direction.Out957 newParams.add(param)958 if cancel, continue959 meth = Method(Token.empty, Token.empty, box, name, newParams, ClrTypeProxy(methInfo.returnType), nil, modifiers, AttributeList(), '')960 if methInfo.isStatic961 meth.sharedMethodBacking = '[namespaceName].[argClrType.name].[methInfo.name]'962 if 'shared' in modifiers, meth.sharedMethodBackingIsAlias = true963 964 overload = nil to MemberOverload?965 other = box.declForName(name)966 if other967 if other inherits MemberOverload968 overload = other969 else if other inherits AbstractMethod or other inherits ProperDexer970 overload = MemberOverload(other to BoxMember)971 box.registerOverload(overload to !)972 else973 throw FallThroughException([box, meth, other])974 else975 assert box.declForName(name) is nil976 if overload977 overload.addMember(meth)978 else979 box.addDecl(meth)980 981 meths.add(meth)982 983 def compareMethodNames(a as Method, b as Method) as int984 return a.name.compareTo(b.name)985 986 948 def memberForName(name as String) as IMember? 987 949 member = base.memberForName(name) 988 950 if member is nil, member = _box.memberForName(name) … … 1010 972 1011 973 cue init 1012 974 base.init 1013 _nativeType = .typeProvider.nativeType(' System.Boolean')1014 _systemAliasProxy = LibraryTypeProxy(' System.Boolean')975 _nativeType = .typeProvider.nativeType('bool') 976 _systemAliasProxy = LibraryTypeProxy('bool') 1015 977 1016 978 get name as String is override 1017 979 return 'bool' … … 1021 983 1022 984 cue init 1023 985 base.init 1024 _nativeType = .typeProvider.nativeType(' System.Char')1025 _systemAliasProxy = LibraryTypeProxy(' System.Char')986 _nativeType = .typeProvider.nativeType('char') 987 _systemAliasProxy = LibraryTypeProxy('char') 1026 988 1027 989 get name as String is override 1028 990 return 'char' … … 1038 1000 1039 1001 cue init 1040 1002 base.init 1041 _nativeType = .typeProvider.nativeType(' System.Decimal')1042 _systemAliasProxy = LibraryTypeProxy(' System.Decimal')1003 _nativeType = .typeProvider.nativeType('decimal') 1004 _systemAliasProxy = LibraryTypeProxy('decimal') 1043 1005 1044 1006 get name as String is override 1045 1007 return 'decimal' … … 1133 1095 base.init(superType) 1134 1096 _size = size 1135 1097 branch size 1136 on 32, _nativeType = .typeProvider.nativeType(' System.Single')1137 on 64, _nativeType = .typeProvider.nativeType(' System.Double')1098 on 32, _nativeType = .typeProvider.nativeType('single') 1099 on 64, _nativeType = .typeProvider.nativeType('double') 1138 1100 else, throw FallThroughException(size) 1139 1101 _systemAliasProxy = LibraryTypeProxy(_nativeType.fullName) 1140 1102 … … 1240 1202 _size = size 1241 1203 if signed 1242 1204 branch size 1243 on 8, _nativeType = .typeProvider.nativeType(' System.SByte')1244 on 16, _nativeType = .typeProvider.nativeType(' System.Int16')1245 on 32, _nativeType = .typeProvider.nativeType(' System.Int32')1246 on 64, _nativeType = .typeProvider.nativeType(' System.Int64')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') 1247 1209 else, throw FallThroughException(size) 1248 1210 else 1249 1211 branch size 1250 on 8, _nativeType = .typeProvider.nativeType(' System.Byte')1251 on 16, _nativeType = .typeProvider.nativeType(' System.UInt16')1252 on 32, _nativeType = .typeProvider.nativeType(' System.UInt32')1253 on 64, _nativeType = .typeProvider.nativeType(' System.UInt64')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') 1254 1216 else, throw FallThroughException(size) 1255 1217 _systemAliasProxy = LibraryTypeProxy(_nativeType.fullName) 1256 1218 … … 1761 1723 def _bindInh 1762 1724 base._bindInh 1763 1725 if .compiler # will be nil during unit tests 1764 iclone = .compiler.libraryType('System.ICloneable') 1765 icoll = (.compiler.libraryType('System.Collections.Generic.ICollection<of>') to Box).constructedTypeFor([.theWrappedType]) 1726 #iclone = .compiler.libraryType('ICloneable') 1727 1728 #icoll = (.compiler.libraryType('System.Collections.Generic.ICollection<of>') to Box).constructedTypeFor([.theWrappedType]) 1729 #icoll = (.compiler.libraryType('ICollection<of>') to Box).constructedTypeFor([.theWrappedType]) 1730 icoll = .compiler.collectionOfType.constructedTypeFor([.theWrappedType]) 1766 1731 ienum = .compiler.enumerableOfType.constructedTypeFor([.theWrappedType]) 1767 1732 _ilistOf = .compiler.ilistOfType.constructedTypeFor([.theWrappedType]) to Interface 1768 interfaces = [iclone to ITypeProxy, icoll, ienum] # TODO:, _ilistOf] -- problems with cobra -ert:yes hello and extension method String.split 1733 interfaces = [icoll to ITypeProxy, ienum] # TODO:, _ilistOf] -- problems with cobra -ert:yes hello and extension method String.split 1734 .compiler.backEnd.addArrayInterfaces(interfaces) 1769 1735 _box = Class(Token.empty, Token.empty, '[.getType.name]_[.serialNum]', List<of IType>(), List<of String>(), AttributeList(), nil, interfaces, List<of ITypeProxy>(), nil) 1770 1736 # TODO: make members based on System.Array 1771 1737 indexer = Indexer(Token.empty, Token.empty, _box, r'[]', [Param(Token('', 1, 1, 1, 'ID', 'index', nil), .compiler.intType)], _wrappedType, List<of String>(), AttributeList(), '') -
Source/files-to-compile.text
59 59 BackEndClr/SharpGenerator 60 60 BackEndClr/SharpCompilationMessage 61 61 62 #BackEndClr/CobraJvmProxy 62 63 BackEndJvm/JvmBackEnd 64 BackEndJvm/JvmType 65 BackEndJvm/JvmJarSig 66 BackEndJvm/ScanJvmType 63 67 BackEndJvm/JavaGenerator 64 68 BackEndJvm/JavaCompilationMessage 65 69 -
Source/Vars.cobra
39 39 var _ifInheritsStack = Stack<of IType>() 40 40 var _isAssignedTo as bool 41 41 var _backEndName as String 42 var _useBackEndNameStack = Stack<of String>() # for if-inherits42 var _useBackEndNameStack = Stack<of String>() # TODO: for if-inherits 43 43 44 44 cue init(token as IToken, type as IType) 45 45 require token.text.length