diff --git a/Source/Aliases.swift b/Source/Aliases.swift index 1f8be1f..7eb7553 100644 --- a/Source/Aliases.swift +++ b/Source/Aliases.swift @@ -1,4 +1,8 @@ -public typealias NSObject = Object +#if DARWIN + public typealias NSObject = Foundation.Object +#else + public typealias NSObject = Object +#endif #if CLR || JAVA public typealias Int = Int64 @@ -32,11 +36,9 @@ public typealias UTF16Char = Char // UInt16 public typealias UTF32Char = UInt32 #if !COCOA && !ISLAND public typealias AnsiChar = Byte -public typealias UTF8Char = Byte -#else // Cocoa and Island already have AnsiChar -public typealias UTF8Char = AnsiChar #endif +public typealias UTF8Char = Byte public typealias StaticString = NativeString @@ -54,8 +56,10 @@ public typealias AnyClass = rtl.Class public typealias AnyClass = java.lang.Class #endif -#if COCOA +#if DARWIN public typealias Selector = SEL +public typealias NSObjectProtocol = INSObject +public typealias INSObjectProtocol = INSObject #endif /* more obscure aliases */ @@ -70,9 +74,18 @@ public typealias CFloat = Float public typealias CInt = Int32 public typealias CLong = Int public typealias CLongLong = Int64 -#if COCOA || ISLAND + +#if !JAVA +// UnsafeMutablePointer and UnsafePointer are defined by the compiler +public typealias UnsafeMutableBufferPointer = UnsafeMutablePointer +public typealias UnsafeBufferPointer = UnsafePointer +public typealias UnsafeMutableRawPointer = UnsafeMutablePointer +public typealias UnsafeRawPointer = UnsafePointer +public typealias UnsafeMutableRawBufferPointer = UnsafeMutablePointer +public typealias UnsafeRawBufferPointer = UnsafePointer public typealias OpaquePointer = UnsafePointer #endif + public typealias CShort = Int16 public typealias CSignedChar = Int8 public typealias CUnsignedChar = UInt8 diff --git a/Source/Array.Java.swift b/Source/Array.Java.swift index 16a368c..e31a6d3 100644 --- a/Source/Array.Java.swift +++ b/Source/Array.Java.swift @@ -9,11 +9,13 @@ public extension Swift.Array : java.util.List { public func contains(_ arg1: Object!) -> Bool { return list.contains(arg1) } + @inline(__always) public func toArray(_ arg1: T![]) -> T![] { - return list.toArray(arg1) + return platformList.toArray(arg1) } + @inline(__always) public func toArray() -> Object![] { - return list.toArray() + return platformList.toArray() } mutating func add(_ arg1: Int32, _ arg2: T!) { makeUnique() diff --git a/Source/Array.swift b/Source/Array.swift index 96940e8..43c4d7d 100755 --- a/Source/Array.swift +++ b/Source/Array.swift @@ -92,7 +92,7 @@ public struct Array public init(repeating value: T, count: Int) { if count == 0 { list = PlatformList() - } else { + } else{ #if JAVA list = PlatformList(count) for i in 0 ..< count { @@ -127,7 +127,7 @@ public struct Array #elseif CLR | ISLAND list = sequence.ToList() #elseif COCOA - list = sequence.array().mutableCopy() + list = sequence.ToNSArray().mutableCopy() #endif } @@ -152,8 +152,8 @@ public struct Array // Storage // - private var list: PlatformList - private var unique: Boolean = true + internal var list: PlatformList + internal var unique: Boolean = true private mutating func makeUnique() { @@ -182,56 +182,35 @@ public struct Array return [T](arrayLiteral: array) } + #if !COOPER public static func __implicit(_ array: [T]) -> T[] { return array.nativeArray } + #endif + + // Cast from sequence + + public static func __implicit(_ sequence: ISequence) -> [T] { + return [T](sequence: sequence) + } // Cast from/to platform type - public static func __implicit(_ list: PlatformList) -> [T] { + public static func __implicit(_ list: PlatformImmutableList) -> [T] { return [T](list) } public static func __implicit(_ array: [T]) -> PlatformList { return array.platformList } - // Darwin only: cast from/to Cocoa type - #if DARWIN - #if ISLAND - public static func __implicit(_ array: NSArray) -> [T] { - return List(array) - } - - public static func __implicit(_ array: [T]) -> NSArray { - return array.list.ToNSArray() - } - - public static func __implicit(_ list: [T]) -> NSMutableArray { - return list.list.ToNSMutableArray() - } - #else + #if DARWIN && !ISLAND public static func __implicit(_ array: [T]) -> PlatformImmutableList { return array.platformList } #endif - // Cocoa only: cast from/to different generic Cocoa type - - public static func __explicit(_ array: NSArray) -> [T] { - return (array as! NSArray) as! [T] - } - - public static func __explicit(_ array: [T]) -> NSArray { - return (array as! NSArray) as! NSArray - } - - public static func __explicit(_ array: [T]) -> NSMutableArray { - return (array as! NSMutableArray) as! NSMutableArray - } - #endif - // // Operators // @@ -252,6 +231,18 @@ public struct Array return result } + public func +=(inout lhs: [T], rhs: [T]) { + for i in rhs { + lhs.append(i) + } + } + + public static func += (inout lhs: Array, rhs: ISequence) { + for i in rhs { + lhs.append(i) + } + } + public static func == (lhs: [T], rhs: [T]) -> Bool { if lhs.list == rhs.list { return true @@ -336,7 +327,7 @@ public struct Array public subscript (range: Range) -> [T] { #if COCOA - return [T](list.Skip(range.lowerBound).Take(range.length).array()) + return [T](list.Skip(range.lowerBound).Take(range.length).ToNSArray()) #else return [T](list.Skip(range.lowerBound).Take(range.length).ToList()) #endif @@ -436,7 +427,7 @@ public struct Array #elseif CLR | ISLAND list.AddRange(sequence.ToList()) #elseif COCOA - list.addObjectsFromArray(sequence.array()) + list.addObjectsFromArray(sequence.ToNSArray()) #endif } @@ -621,7 +612,19 @@ public struct Array if i != 0, let separator = separator { result.Append(separator) } + #if ISLAND + switch modelOf(T) { + case "Island": result.Append((self[i] as? IslandObject)?.ToString()) + case "Cocoa": result.Append(self[i]?.description) + case "Swift": result.Append(self[i]?.description) + case "Delphi": throw Exception("This feature is not supported for Delphi Objects (yet)"); + case "COM": throw Exception("This feature is not supported for COM Objects"); + case "JNI": throw Exception("This feature is not supported for JNI Objects"); + default: throw Exception("Unexpected object model \(modelOf(T))") + } + #else result.Append(self[i]?.ToString()) + #endif } return result.ToString()! #elseif COCOA @@ -633,9 +636,9 @@ public struct Array //} public func map(_ transform: (T) -> U) -> ISequence { // we deliberatey return a sequence, not an array, for efficiency and flexibility. - #if JAVA + #if JAVA || ISLAND return list.Select({ return transform($0) }) - #elseif CLR || ISLAND || COCOA + #elseif CLR || COCOA return list.Select(transform) #endif } @@ -645,9 +648,9 @@ public struct Array //} public func filter(_ includeElement: (T) -> Bool) -> ISequence { // we deliberatey return a sequence, not an array, for efficiency and flexibility. - #if JAVA + #if JAVA || ISLAND return list.Where({ return includeElement($0) }) - #elseif CLR || ISLAND || COCOA + #elseif CLR || COCOA return list.Where(includeElement) #endif } @@ -684,7 +687,7 @@ public struct Array #endif } - private static func compareElements(_ r: T, _ l: T) -> Bool { + private static func compareElements(_ r: T?, _ l: T?) -> Bool { if l == nil { return r == nil } @@ -692,23 +695,64 @@ public struct Array return false } #if COOPER - return l.equals(r) + return l!.equals(r) #elseif ECHOES return System.Collections.Generic.EqualityComparer.Default.Equals(l, r) #elseif ISLAND return RemObjects.Elements.System.EqualityComparer.Equals(l, r) #elseif COCOA - return l.isEqual(r) + return l!.isEqual(r) #endif return true } @ToString - public override func description() -> String { + public override func description() -> NativeString { return list.description } } +//public extension Swift.Array where T: String { + //public convenience init(_ items: [NativeString]) { + //self.list = items.map({ $0 as! String }).ToList() + //self.unique = true + //} +//} + +#if DARWIN && ISLAND +public extension Swift.Array where T: NSObject { + public static func __implicit(_ array: NSArray) -> [T] { + var result = [T](capacity: array.count) + for i in 0 ... array.count { + result.append(array[i]) + } + return result + } + + public static func __implicit(_ array: [T]) -> NSArray { + return array.list.ToNSArray() + } + + public static func __implicit(_ list: [T]) -> NSMutableArray { + return list.list.ToNSMutableArray() + } + + // Cocoa only: cast from/to different generic Cocoa type + + public static func __explicit(_ array: NSArray) -> [T] { + return (array as! NSArray) as! [T] + } + + public static func __explicit(_ array: [T]) -> NSArray { + return (array as! NSArray) as! NSArray + } + + public static func __explicit(_ array: [T]) -> NSMutableArray { + return (array as! NSMutableArray) as! NSMutableArray + } +} +#endif + //#if !COCOA //public extension Swift.Array : ISequence { diff --git a/Source/Character.swift b/Source/Character.swift index 0d6c26d..9bfbb0d 100644 --- a/Source/Character.swift +++ b/Source/Character.swift @@ -6,6 +6,17 @@ return nativeStringValue } + public static func __implicit(_ char: Char) -> Character { + return Character(nativeStringValue: char) + } + + public static func __implicit(_ string: String) -> Character { + if string.characters.count != 1 { // not super efficient + throw Exception("Cannot cast string '\(string)' to Character") + } + return Character(nativeStringValue: string) + } + internal func toHexString() -> NativeString { if length(nativeStringValue) == 1 { return UInt32(nativeStringValue[0]).toHexString(length: 4) diff --git a/Source/Dictionary.Java.swift b/Source/Dictionary.Java.swift index 0c92971..e1f9d39 100644 --- a/Source/Dictionary.Java.swift +++ b/Source/Dictionary.Java.swift @@ -18,11 +18,11 @@ public extension Swift.Dictionary : java.util.Map { } public mutating func put(_ arg1: Key!, _ arg2: Value!) -> Value! { makeUnique() - return dictionary.put(arg1, arg1) + return dictionary.put(arg1, arg2) } public mutating func remove(_ arg1: Object!, _ arg2: Object!) -> Bool { makeUnique() - return dictionary.remove(arg1, arg1) + return dictionary.remove(arg1, arg2) } public mutating func remove(_ arg1: Object!) -> Value! { makeUnique() diff --git a/Source/Dictionary.swift b/Source/Dictionary.swift index e73954e..903d76c 100755 --- a/Source/Dictionary.swift +++ b/Source/Dictionary.swift @@ -79,8 +79,8 @@ public struct Dictionary /*: INSFastEnumeration*/ // Storage // - private var dictionary: PlatformDictionary - private var unique: Boolean = true + internal var dictionary: PlatformDictionary + internal var unique: Boolean = true private mutating func makeUnique() { @@ -95,7 +95,7 @@ public struct Dictionary /*: INSFastEnumeration*/ // @Sequence - public func GetSequence() -> ISequence<(Key, Value)> { + public func GetSequence() -> ISequence<(key: Key, value: Value)> { return DictionaryHelper.Enumerate(dictionary) } @@ -115,40 +115,12 @@ public struct Dictionary /*: INSFastEnumeration*/ // Darwin only: cast from/to Cocoa type - #if DARWIN - #if ISLAND - public static func __implicit(_ dictionary: NSDictionary) -> [Key:Value] { - return PlatformDictionary(dictionary) - } - - public static func __implicit(_ dictionary: [Key:Value]) -> NSDictionary { - return dictionary.dictionary.ToNSDictionary() - } - - public static func __implicit(_ dictionary: [Key:Value]) -> NSMutableDictionary { - return dictionary.dictionary.ToNSMutableDictionary() - } - #else + #if DARWIN && !ISLAND public static func __implicit(_ dictionary: [Key:Value]) -> PlatformImmutableDictionary { return dictionary.platformDictionary } #endif - // Cocoa only: cast from/to different generic Cocoa type - - public static func __explicit(_ dictionary: NSDictionary) -> [Key:Value] { - return (dictionary as! NSDictionary) as! [Key:Value] - } - - public static func __explicit(_ dictionary: [Key:Value]) -> NSDictionary { - return (dictionary as! NSDictionary) as! NSDictionary - } - - public static func __explicit(_ dictionary: [Key:Value]) -> NSMutableDictionary { - return (dictionary as! NSMutableDictionary) as! NSMutableDictionary - } - #endif - // // Operators // @@ -193,7 +165,7 @@ public struct Dictionary /*: INSFastEnumeration*/ } } for k in rhs.keys { - let l = lhs[k]! + let l = lhs[k] if l == nil { return false } @@ -309,7 +281,7 @@ public struct Dictionary /*: INSFastEnumeration*/ #endif } - public mutating func removeValueForKey(_ key: Key) -> Value? { + public mutating func removeValue(forKey key: Key) -> Value? { makeUnique() #if JAVA if dictionary.containsKey(key) { @@ -335,6 +307,12 @@ public struct Dictionary /*: INSFastEnumeration*/ unique = true } + //public func forEach(_ body: ((key: Key, value: Value)) throws -> Void) rethrows { + //for item in self { + //try body(item) + //} + //} + public var count: Int { #if JAVA return dictionary.keySet().Count() @@ -380,30 +358,60 @@ public struct Dictionary /*: INSFastEnumeration*/ } @ToString - public override func description() -> String { + public override func description() -> NativeString { return dictionary.description } } +#if DARWIN && ISLAND +public extension Swift.Dictionary where Key: NSObject, Value: NSObject { + public static func __implicit(_ dictionary: NSDictionary) -> [Key:Value] { + return PlatformDictionary(dictionary) + } + + public static func __implicit(_ dictionary: [Key:Value]) -> NSDictionary { + return dictionary.dictionary.ToNSDictionary() + } + + public static func __implicit(_ dictionary: [Key:Value]) -> NSMutableDictionary { + return dictionary.dictionary.ToNSMutableDictionary() + } + + // Cocoa only: cast from/to different generic Cocoa type + + public static func __explicit(_ dictionary: NSDictionary) -> [Key:Value] { + return (dictionary as! NSDictionary) as! [Key:Value] + } + + public static func __explicit(_ dictionary: [Key:Value]) -> NSDictionary { + return (dictionary as! NSDictionary) as! NSDictionary + } + + public static func __explicit(_ dictionary: [Key:Value]) -> NSMutableDictionary { + return (dictionary as! NSMutableDictionary) as! NSMutableDictionary + } +} +#endif + public static class DictionaryHelper { #if JAVA - public static func Enumerate(_ val: PlatformDictionary) -> ISequence<(Key, Value)> { + public static func Enumerate(_ val: PlatformDictionary) -> ISequence<(Key, Value)> { for entry in val.entrySet() { - var item: (Key, Value) = (entry.Key, entry.Value) + var item: (key: Key, value: Value) = (entry.Key, entry.Value) __yield item } } #elseif CLR | ISLAND - public static func Enumerate(_ val: PlatformDictionary) -> ISequence<(Key, Value)> { + public static func Enumerate(_ val: PlatformDictionary) -> ISequence<(Key, Value)> { for entry in val { - var item: (Key, Value) = (entry.Key, entry.Value) + var item: (key: Key, value: Value) = (entry.Key, entry.Value) __yield item } } #elseif COCOA - public static func Enumerate(_ val: PlatformDictionary) -> ISequence<(Key, Value)> { + public static func Enumerate(_ val: PlatformDictionary) -> ISequence<(Key, Value)> { for entry in val { - var item: (Key, Value) = (entry, val[entry]?) + var item: (key: Key, value: Value) = (entry, val[entry]?) __yield item } } diff --git a/Source/Dispatch.swift b/Source/Dispatch.swift index adee9db..15530b2 100644 --- a/Source/Dispatch.swift +++ b/Source/Dispatch.swift @@ -98,6 +98,22 @@ public class DispatchQueue : DispatchObject { #endif } + public static func __implicit(_ queue: DispatchQueue?) -> dispatch_queue_t? { + if let queue = queue { + return queue.queue + } else { + return nil + } + } + + public static func __implicit(_ queue: dispatch_queue_t?) -> DispatchQueue? { + if let queue = queue { + return DispatchQueue(queue: queue) + } else { + return nil + } + } + internal convenience init(__label: String, attr: dispatch_queue_attr_t?, queue: DispatchQueue?) { var raw: dispatch_queue_t if #defined(COCOA) { @@ -149,7 +165,7 @@ public class DispatchQueue : DispatchObject { } public func concurrentPerform(iterations: Int, execute work: (UInt) -> ()) { - dispatch_apply(iterations, self.queue, work) + dispatch_apply(iterations, self.queue, { work($0) }) } public func async(execute work: () -> ()) { @@ -158,14 +174,14 @@ public class DispatchQueue : DispatchObject { public func async(group: DispatchGroup?, execute work: () -> ()) { if group != nil { - dispatch_group_async(group!.group, self.queue, work) + dispatch_group_async(group!.group, self.queue, { work() }) } else { - dispatch_async(self.queue, work) + dispatch_async(self.queue, { work() }) } } public func sync(execute work: () -> ()) { - dispatch_sync(self.queue, work) + dispatch_sync(self.queue, { work() }) } #if !ISLAND diff --git a/Source/Functions.swift b/Source/Functions.swift index e0164d3..73b8880 100644 --- a/Source/Functions.swift +++ b/Source/Functions.swift @@ -63,17 +63,34 @@ public func debugPrint(_ objects: Object?..., separator: String = " ", terminato @discardableResult func dump(_ value: T, name: String? = nil, indent: Int = 2, maxDepth: Int = -1, maxItems: Int = -1) -> T { - debugPrint(value) + #if ISLAND && DARWIN + switch modelOf(T) { + case "Island": debugPrint((value as? IslandObject)?.ToString()) + case "Cocoa": debugPrint((value as? CocoaObject)?.description) + case "Swift": debugPrint((value as? SwiftObject)?.description) + case "Delphi": throw Exception("This feature is not supported for Delphi Objects (yet)"); + case "COM": throw Exception("This feature is not supported for COM Objects"); + case "JNI": throw Exception("This feature is not supported for JNI Objects"); + default: throw Exception("Unexpected object model \(modelOf(T))") + } + #else + debugPrint(value as? Object) + #endif return value } -public func fatalError(_ message: @autoclosure () -> String, file: String = #file, line: UInt32 = #line) -> Never { +@noreturn public func fatalError(file: String = #file, line: UInt32 = #line) -> Never { + __throw Exception("Fatal Error, file "+file+", line "+line) +} + +@noreturn public func fatalError(_ message: @autoclosure () -> String, file: String = #file, line: UInt32 = #line) -> Never { if let message = message { __throw Exception(message()+", file "+file+", line "+line) } else { __throw Exception("Fatal Error, file "+file+", line "+line) } } + @Conditional("DEBUG") public func precondition(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String, file: String = #file, line: UWord = #line) { if (!condition()) { fatalError(message, file: file, line: line) @@ -164,42 +181,77 @@ public func readLine(# stripNewline: Bool = true) -> String { } public func stride(from start: Int, to end: Int, by stride: Int) -> ISequence { - precondition(stride > 0, "'by' must be larger than zero") var i = start - while i < end { - __yield i; - i += stride + if stride > 0 { + while i < end { + __yield i; + i += stride + } + } else if stride < 0 { + while i > end { + __yield i; + i += stride + } } } -//75284: Silver: can't overload global func on parameter names? -/*public func stride(from start: Int, through end: Int, by stride: Int) -> ISequence { - precondition(stride > 0, "'by' must be larger than zero") +public func stride(from start: Int, through end: Int, by stride: Int) -> ISequence { var i = start - while i <= end { - __yield i; - i += stride + if stride > 0 { + while i <= end { + __yield i; + i += stride + } + } else if stride < 0 { + while i >= end { + __yield i; + i += stride + } } -}*/ +} public func stride(from start: Double, to end: Double, by stride: Double) -> ISequence { - precondition(stride > 0, "'by' must be larger than zero") var i = start - while i < end { - __yield i; - i += stride + if stride > 0 { + while i < end { + __yield i; + i += stride + } + } else if stride < 0 { + while i > end { + __yield i; + i += stride + } } } -//75284: Silver: can't overload global func on parameter names? -/*public func stride(from start: Double, through end: Double, by stride: Double) -> ISequence { - precondition(stride > 0, "'by' must be larger than zero") +#if !TOFFEE +public func stride(from start: Double, through end: Double, by stride: Double) -> ISequence { var i = start - while i <= end { - __yield i; - i += stride + if stride > 0 { + while i <= end { + __yield i; + i += stride + } + } else if stride < 0 { + while i >= end { + __yield i; + i += stride + } } -}*/ +} +#endif + +#if COOPER || TOFFEE +@inline(always) public func type(of value: Any) -> Class { + return typeOf(value) +} +#elseif ECHOES || ISLAND +@inline(always) public func type(of value: Any) -> Type { + return typeOf(value) +} +#endif + #if TOFFEE diff --git a/Source/Integer_Extensions.swift b/Source/Integer_Extensions.swift index 717c977..0c6ad93 100644 --- a/Source/Integer_Extensions.swift +++ b/Source/Integer_Extensions.swift @@ -162,18 +162,18 @@ public extension Int32 /*: AbsoluteValuable*/ { public extension Int32 /*: Strideable*/ { func advancedBy(_ n: Int32) -> Int32 { - return self + n; + return self + n } func distanceTo(_ other: Int32) -> Int32 { - return other - self; + return other - self } public func stride(# through: Int32, by: Int32) -> ISequence { precondition(by > 0, "'by' must be larger than zero") var i = self while i <= through { - __yield i; + __yield i i += by } } @@ -184,7 +184,7 @@ public extension Int32 /*: Strideable*/ { precondition(by > 0, "'by' must be larger than zero") var i = self while i < to { - __yield i; + __yield i i += by } } @@ -242,18 +242,18 @@ public extension Int64 {//: Equatable, Comparable, ForwardIndexType { // Strideable func advancedBy(_ n: Int64) -> Int64 { - return self + n; + return self + n } func distanceTo(_ other: Int64) -> Int64 { - return other - self; + return other - self } public func stride(# through: Int64, by: Int64) -> ISequence { precondition(by > 0, "'by' must be larger than zero") var i = self while i <= through { - __yield i; + __yield i i += by } } @@ -264,7 +264,7 @@ public extension Int64 {//: Equatable, Comparable, ForwardIndexType { precondition(by > 0, "'by' must be larger than zero") var i = self while i < to { - __yield i; + __yield i i += by } } @@ -276,18 +276,18 @@ public extension Float { // Strideable func advancedBy(_ n: Float) -> Float { - return self + n; + return self + n } func distanceTo(_ other: Float) -> Float { - return other - self; + return other - self } public func stride(# through: Float, by: Float) -> ISequence { precondition(by > 0, "'by' must be larger than zero") var i = self while i <= through { - __yield i; + __yield i i += by } } @@ -298,7 +298,7 @@ public extension Float { precondition(by > 0, "'by' must be larger than zero") var i = self while i < to { - __yield i; + __yield i i += by } } @@ -307,21 +307,98 @@ public extension Float { public extension Double { + /*init?(_ stringValue: String?) { + + var stringValue = stringValue//?.Trim() + if length(stringValue) == 0 { + throw Exception("Invalud Double value") + } + + if #defined(COOPER) { + let DecFormat = java.text.DecimalFormat.getInstance(java.util.Locale.Default) as! java.text.DecimalFormat + let Position = java.text.ParsePosition(0) + stringValue = stringValue!.Trim().toUpperCase() + // E+ is not accepted, just E or E- + stringValue = stringValue!.Replace("E+", "E") + if #defined(ANDROID) { + if stringValue.Length > 1 { + let DecimalIndex = stringValue.IndexOf(".") + if DecimalIndex = -1 { + DecimalIndex = stringValue.Length + } + stringValue = stringValue[0] + stringValue.Substring(1, DecimalIndex - 1).Replace(",", "") + stringValue.Substring(DecimalIndex) + } + } + + if stringValue!.StartsWith("+") { + stringValue = stringValue!.Substring(1) + } + let result = DecFormat.parse(stringValue, Position)?.doubleValue() + if Position.Index < stringValue!.Length() { + throw Exception("Invalud Double value") + } + if Double.isInfinite(result) || Double.isNaN(result) { + throw Exception("Invalud Double value") + } + return result + } else if #defined(TOFFEE) { + let Number = TryParseNumber(stringValue, Foundation.NSLocale.systemLocale) + if Number == nil { + throw Exception("Invalud Double value") + } + return Number?.doubleValue + } else if #defined(ECHOES) { + let result: Double + if !Double.TryParse(stringValue, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, &result) { + throw Exception("Invalud Double value") + } + return valueOrDefault(result) + } else if #defined(ISLAND) { + let result: Double + if !Double.TryParse(stringValue, RemObjects.Elements.System.Locale.Invariant, &result) { + throw Exception("Invalud Double value") + } + return valueOrDefault(result) + } + }*/ + + #if TOFFEE + private static func TryParseNumber(_ stringValue: String?, _ aLocale: Foundation.NSLocale? = nil) -> NSNumber? { + + var stringValue = stringValue//?.Trim() + if length(stringValue) == 0 { + return nil + } + + let Formatter = NSNumberFormatter() + Formatter.numberStyle = NSNumberFormatterStyle.NSNumberFormatterDecimalStyle + Formatter.locale = aLocale + if (stringValue as! NSString).rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet).location != NSNotFound { + return nil + } + if stringValue!.hasPrefix("+") && !stringValue!.contains("-") { + stringValue = stringValue!.substring(fromIndex: 1) + return Formatter.numberFromString(stringValue) + } + return nil + } + #endif + // Strideable func advancedBy(_ n: Double) -> Double { - return self + n; + return self + n } func distanceTo(_ other: Double) -> Double { - return other - self; + return other - self } public func stride(# through: Double, by: Double) -> ISequence { precondition(by > 0, "'by' must be larger than zero") - var i = self + let i = self while i <= through { - __yield i; + __yield i i += by } } @@ -332,7 +409,7 @@ public extension Double { precondition(by > 0, "'by' must be larger than zero") var i = self while i < to { - __yield i; + __yield i i += by } } diff --git a/Source/MemoryLayout.swift b/Source/MemoryLayout.swift new file mode 100644 index 0000000..b439c12 --- /dev/null +++ b/Source/MemoryLayout.swift @@ -0,0 +1,7 @@ +//public struct MemoryLayout { + + //var size: Byte { sizeOf } + //var alignment: Byte { sizeOf } + //var stride: Byte { sizeOf } + +//} \ No newline at end of file diff --git a/Source/NSArray_Extensions.swift b/Source/NSArray_Extensions.swift new file mode 100644 index 0000000..306c3a6 --- /dev/null +++ b/Source/NSArray_Extensions.swift @@ -0,0 +1,413 @@ +#if TOFFEE +public extension NSArray { + + init(nativeArray: ObjectType[]) { + let result = NSMutableArray(capacity: length(nativeArray)) + for e in nativeArray { + result.addObject(e) + } + return result + } + + init(array: [ObjectType]) { + return array as! ISequence // 74041: Silver: warning for "as" cast that should be known safe + } + + public func ToSwiftArray() -> [ObjectType] { + //workaround for E25642: Island/Darwin: can't use generic params with Cocoa collection even if consrained to NSObject + //if let array = self as? [ObjectType] { + //return array.platformList + //} + var result = [ObjectType]() + for i in self { + result.append(i) + } + return result + } + + #if !COOPER + public func ToSwiftArray() -> [U] { + var result = [U]() + for i in self { + result.append(i as! U) + } + return result + } + #endif + + public func dropFirst() -> ISequence { + return self.Skip(1) + } + + public func dropFirst(_ n: Int) -> ISequence { + return self.Skip(n) + } + + public func dropLast() -> ISequence { + fatalError("dropLast() is not implemented yet.") + } + + public func dropLast(_ n: Int) -> ISequence { + fatalError("dropLast() is not implemented yet.") + } + + public func enumerated() -> ISequence<(Int, ObjectType)> { + var index = 0 + for element in self { + __yield (index++, element) + } + } + + public func indexOf(@noescape _ predicate: (ObjectType) -> Bool) -> Int? { + for (i, element) in self.enumerated() { + if (predicate(element) == true){ + return i + } + } + return nil + } + + public func filter(_ includeElement: (ObjectType) throws -> Bool) rethrows -> ISequence { + return self.Where() { return try! includeElement($0) } + } + + public func count(`where` countElement: (ObjectType) throws -> Bool) rethrows -> Int { + var result = 0; + for i in self { + if try countElement(i) { + result++ + } + } + return result + } + + public var first: ObjectType? { + return self.FirstOrDefault() + } + + func flatMap(@noescape _ transform: (ObjectType) throws -> ObjectType?) rethrows -> ISequence { + for e in self { + if let e = try! transform(e) { + __yield e + } + } + } + + public func flatten() -> ISequence { // no-op in Silver? i dont get what this does. + return self + } + + public func forEach(@noescape body: (ObjectType) throws -> ()) rethrows { + for e in self { + try! body(e) + } + } + + @Obsolete("generate() is not supported in Silver.", true) public func generate() -> ISequence { // no-op in Silver? i dont get what this does. + fatalError("generate() is not supported in Silver.") + } + + public var isEmpty: Bool { + return !self.Any() + } + + public func joined(separator: String) -> String { + var first = true + var result = "" + for e in self { + if !first { + result += separator + } else { + first = false + } + result += e.description + } + return result + } + + public func joined(separator: ISequence) -> ISequence { + var first = true + for e in self { + if !first { + for i in separator { + __yield i + } + } else { + first = false + } + __yield e + } + } + + public func joined(separator: ObjectType[]) -> ISequence { + var first = true + for e in self { + if !first { + for i in separator { + __yield i + } + } else { + first = false + } + __yield e + } + } + + public var lazy: ISequence { // sequences are always lazy in Silver + return self + } + + public func map(_ transform: (ObjectType) -> U) -> ISequence { + return self.Select() { return transform($0) } + } + + //74101: Silver: still two issues with try! + public func maxElement(_ isOrderedBefore: (ObjectType, ObjectType) /*throws*/ -> Bool) -> ObjectType? { + var m: ObjectType? = nil + for e in self { + if m == nil || /*try!*/ !isOrderedBefore(m!, e) { // ToDo: check if this is the right order + m = e + } + } + return m + } + + public func minElement(_ isOrderedBefore: (ObjectType, ObjectType) /*throws*/ -> Bool) -> ObjectType? { + var m: ObjectType? = nil + for e in self { + if m == nil || /*try!*/ isOrderedBefore(m!, e) { // ToDo: check if this is the right order + m = e + } + } + return m + } + + public func `prefix`(_ maxLength: Int) -> ISequence { + return self.Take(maxLength) + } + + public func reduce(_ initial: U, _ combine: (U, ObjectType) -> U) -> U { + var value = initial + for i in self { + value = combine(value, i) + } + return value + } + + public func reverse() -> ISequence { + return self.Reverse() + } + + public func sorted(by isOrderedBefore: (ObjectType, ObjectType) -> Bool) -> ISequence { + //todo: make more lazy? + #if JAVA + let result = self.ToList() + java.util.Collections.sort(result, class java.util.Comparator { func compare(a: ObjectType, b: ObjectType) -> Int32 { // ToDo: check if this is the right order + if isOrderedBefore(a,b) { + return 1 + } else { + return -1 + } + }}) + return result + #elseif CLR || ISLAND + let result = self.ToList() + result.Sort() { (a: ObjectType, b: ObjectType) -> Integer in // ToDo: check if this is the right order + if isOrderedBefore(a,b) { + return -1 + } else { + return 1 + } + } + return result + #elseif COCOA + return self.ToNSArray().sortedArrayWithOptions(0, usingComparator: { (a: id!, b: id!) -> NSComparisonResult in // ToDo: check if this is the right order + if isOrderedBefore(a == NSNull.null ? nil : a, b == NSNull.null ? nil : b) { + return .NSOrderedDescending + } else { + return .NSOrderedAscending + } + })! + #endif + } + + /*public func split(_ isSeparator: (ObjectType) -> Bool, maxSplit: Int = 0, allowEmptySlices: Bool = false) -> ISequence> { + + let result = [String]() + var currentString = "" + + func appendCurrent() -> Bool { + if maxSplit > 0 && result.count >= maxSplit { + return false + } + if allowEmptySlices || currentString.length() > 0 { + result.append(currentString) + } + return true + } + + for var i = 0; i < elements.length(); i++ { + let ch = elements[i] + if isSeparator(ch) { + if !appendCurrent() { + break + } + currentString = "" + } else { + currentString += ch + } + } + + if currentString.length() > 0 { + appendCurrent() + } + + return result + }*/ + + public func startsWith(`prefix` p: ISequence) -> Bool { + #if JAVA + let sEnum = self.iterator() + let pEnum = p.iterator() + while true { + if pEnum.hasNext() { + let pVal = pEnum.next() + if sEnum.hasNext() { + let sVal = sEnum.next() + if (pVal == nil && sVal == nil) { + // both nil is oke + } else if pVal != nil && sVal != nil && pVal.equals(sVal) { + // Neither nil and equals true is oke + } else { + return false // Different values + } + } else { + return false // reached end of s + } + + } else { + return true // reached end of prefix + } + } + #elseif CLR || ISLAND + let pEnum = p.GetEnumerator() + for c in self { + if pEnum.MoveNext() { + #if CLR + if !EqualityComparer.Default.Equals(c, pEnum.Current) { + return false // cound mismatch + } + #elseif ISLAND + if c == nil && pEnum.Current == nil { + } else if c != nil && pEnum.Current != nil && c.Equals(pEnum.Current) { + } else { + return false + } + #endif + } else { + return true // reached end of prefix + } + } + return true // reached end of s + #elseif COCOA + let LOOP_SIZE = 16 + let sState: NSFastEnumerationState = `default`(NSFastEnumerationState) + let pState: NSFastEnumerationState = `default`(NSFastEnumerationState) + var sObjects = ObjectType[](count: LOOP_SIZE) + var pObjects = ObjectType[](count: LOOP_SIZE) + + while true { + let sCount = self.countByEnumeratingWithState(&sState, objects: sObjects, count: LOOP_SIZE) + let pCount = p.countByEnumeratingWithState(&pState, objects: pObjects, count: LOOP_SIZE) + if pCount > sCount { + return false // s is shorter than prefix + } + if pCount == 0 { + return true // reached end of prefix + } + for i in 0 ..< sCount { + if i > pCount { + return true // reached end of prefix + } + if !(sState.itemsPtr[i] as! Any).isEqual(pState.itemsPtr[i]) { + return false // found mismatch + } + } + } + #endif + } + + public func suffix(_ maxLength: Int) -> ISequence { + fatalError("suffix() is not implemented yet.") + } + + public func underestimateCount() -> Int { // we just return the accurate count here + return self.Count() + } + + // + // Silver-specific extensions not defined in standard Swift.Array: + // + + /*public func nativeArray() -> ObjectType[] { + #if JAVA + //return self.toArray()//ObjectType[]()) + #elseif CLR + return self.ToArray() + #elseif COCOA + //return self.array() + #endif + }*/ + + public func toSwiftArray() -> [ObjectType] { + #if JAVA + let result = ArrayList() + for e in self { + result.add(e); + } + return [ObjectType](result) + #elseif CLR || ISLAND + return [ObjectType](self.ToList()) + #elseif COCOA + return [ObjectType](self.ToNSArray()) + #endif + } + + public func contains(_ item: ObjectType) -> Bool { + return self.Contains(item) + } + + #if COCOA + override var debugDescription: String! { + var result = "Sequence(" + var first = true + for e in self { + if !first { + result += ", " + } else { + first = false + } + result += String(reflecting: e) + } + result += ")" + return result + } + #else + public var debugDescription: String { + var result = "Sequence(" + var first = true + for e in self { + if !first { + result += ", " + } else { + first = false + } + result += String(reflecting: e) + } + result += ")" + return result + } + #endif +} + +#endif \ No newline at end of file diff --git a/Source/Pointers.swift b/Source/Pointers.swift new file mode 100644 index 0000000..06936b0 --- /dev/null +++ b/Source/Pointers.swift @@ -0,0 +1,46 @@ +#if !JAVA +public extension OpaquePointer { + + //init(_ pointer: UnsafePointer) { + + //} + //init(_ pointer: UnsafeMutablePointer) { + + //} + //init?(_ pointer: UnsafePointer?) { + + //} + //init?(_ pointer: UnsafeMutablePointer?) { + + //} + init(_ pointer: UnsafeRawPointer?) { + return pointer + } + init?(bitPattern: Int) { + return bitPattern as! OpaquePointer + } + init?(bitPattern: UInt) { + return bitPattern as! OpaquePointer + } + + //@ToString // E201 Attributes of type "ToStringAspect!" are not allowed on this member + var description: String { + return "0x"+(self as! UInt).toHexString() + } + + var debugDescription: String { + return "0x"+(self as! UInt).toHexString() + } + + //func hash(into: inout Hasher) { + + //} + //static func != (_ rhs: OpaquePointer, _lhs: OpaquePointer) -> Bool { + // handled by compiler + //} + //static func == (OpaquePointer, OpaquePointer) -> Bool { + // handled by compiler + //} +} + +#endif \ No newline at end of file diff --git a/Source/Protocols.swift b/Source/Protocols.swift index 8cb717d..0e13c42 100644 --- a/Source/Protocols.swift +++ b/Source/Protocols.swift @@ -35,6 +35,12 @@ public protocol IHashable /*: Equatable*/ { var hashValue: Int { get } } +typealias Identifiable = IIdentifiable +protocol IIdentifiable { + associatedtype ID: IHashable + var id: ID { get } +} + public typealias OutputStreamType = IOutputStreamType public protocol IOutputStreamType { //mutating func write(_ string: String) @@ -68,4 +74,12 @@ public protocol IStringProtocol : ITextOutputStream { /*public protocol GeneratorType { typealias Element mutating func next() -> Element? -}*/ \ No newline at end of file +}*/ + +public typealias Actor = IActor +protocol IActor : AnyObject, Sendable { +} + +public typealias Sendable = ISendable +protocol ISendable { +} \ No newline at end of file diff --git a/Source/Range.swift b/Source/Range.swift index 9440e9a..2eaf869 100644 --- a/Source/Range.swift +++ b/Source/Range.swift @@ -277,7 +277,14 @@ public class Range/**/: CustomStringConve } #if COCOA - // todo: make a cast operator + public static func __implicit(_ range: Range) -> NSRange { + return range.nativeRange + } + + public static func __implicit(_ range: NSRange) -> Range { + return Range(range.location, range.location+range.length, upperBoundClosed: false) + } + public var nativeRange: NSRange { if let lowerBound = lowerBound, upperBound != nil { return NSMakeRange(lowerBound, length) diff --git a/Source/Sequence_Extensions.swift b/Source/Sequence_Extensions.swift index 5a527dc..62b3a83 100644 --- a/Source/Sequence_Extensions.swift +++ b/Source/Sequence_Extensions.swift @@ -1,5 +1,4 @@ - -public extension ISequence /*: ICustomDebugStringConvertible*/ { // 74092: Silver: interface on class extension fails on not finding the matching method +public extension ISequence : ICustomDebugStringConvertible { // 74092: Silver: interface on class extension fails on not finding the matching method init(nativeArray: T[]) { // 74043: Silver: wrong/confusing error when implementing iterator in nested function @@ -35,6 +34,16 @@ public extension ISequence /*: ICustomDebugStringConvertible*/ { // 74092: Silve return result } + #if !COOPER + public func ToSwiftArray() -> [U] { + var result = [U]() + for i in self { + result.append(i as! U) + } + return result + } + #endif + public var count: Int { return self.Count() } @@ -75,6 +84,16 @@ public extension ISequence /*: ICustomDebugStringConvertible*/ { // 74092: Silve return self.Where() { return try! includeElement($0) } } + public func count(`where` countElement: (T) throws -> Bool) rethrows -> Int { + var result = 0; + for i in self { + if try countElement(i) { + result++ + } + } + return result + } + public var first: T? { return self.FirstOrDefault() } @@ -215,7 +234,7 @@ public extension ISequence /*: ICustomDebugStringConvertible*/ { // 74092: Silve } return result #elseif COCOA - return self.array().sortedArrayWithOptions(0, usingComparator: { (a: id!, b: id!) -> NSComparisonResult in // ToDo: check if this is the right order + return self.ToNSArray().sortedArrayWithOptions(0, usingComparator: { (a: id!, b: id!) -> NSComparisonResult in // ToDo: check if this is the right order if isOrderedBefore(a == NSNull.null ? nil : a, b == NSNull.null ? nil : b) { return .NSOrderedDescending } else { @@ -368,7 +387,7 @@ public extension ISequence /*: ICustomDebugStringConvertible*/ { // 74092: Silve #elseif CLR || ISLAND return [T](self.ToList()) #elseif COCOA - return [T](self.array()) + return [T](self.ToNSArray()) #endif } diff --git a/Source/Set.swift b/Source/Set.swift index 50dd292..6a16154 100644 --- a/Source/Set.swift +++ b/Source/Set.swift @@ -475,7 +475,7 @@ public struct Set //: //var hashValue: Int { get } /// A textual representation of `self`. - @ToString public func description() -> String { + @ToString public func description() -> NativeString { #if JAVA return _set.toString() #elseif CLR || ISLAND diff --git a/Source/Silver.elements b/Source/Silver.elements new file mode 100644 index 0000000..7932957 --- /dev/null +++ b/Source/Silver.elements @@ -0,0 +1,138 @@ + + + + {9E7A4B59-8176-4CAE-B966-7E299171B148} + StaticLibrary + Swift + Release + True + True + True + True + True + + + .\Bin\Debug + True + False + True + DEBUG;TRACE; + + + .\Bin\Release + + + Echoes + .NETFramework4.0 + Library + System.Collections.Generic;System.Linq + + + Echoes + .NETStandard2.0 + NETSTANDARD + Library + System.Collections.Generic;System.Linq + + + Cooper + Java + Library + java.util,remobjects.elements.linq + + + Island + Windows + + + Island + Linux + + + Island + Darwin + macOS + 10.12 + Foundation;RemObjects.Elements.System;rtl + + + Island + Darwin + iOS + 9.0 + True + Foundation;RemObjects.Elements.System;rtl + + + Island + Darwin + tvOS + 9.0 + Foundation;RemObjects.Elements.System;rtl + + + Island + Darwin + visionOS + 1.0 + Foundation;RemObjects.Elements.System;rtl + + + Island + Darwin + watchOS + 3.0 + Foundation;RemObjects.Elements.System;rtl + + + Island + Android + + + Island + WebAssembly + + + Toffee + iOS + True + Foundation;RemObjects.Elements.Linq + + + Toffee + macOS + 10.9 + Foundation;RemObjects.Elements.Linq + + + Toffee + tvOS + 9.0 + Foundation;RemObjects.Elements.Linq + + + Toffee + visionOS + 1.0 + Foundation;RemObjects.Elements.Linq + + + Toffee + watchOS + Foundation;RemObjects.Elements.Linq + + + + + + + + + + + True + + + + + \ No newline at end of file diff --git a/Source/Silver.sln b/Source/Silver.sln new file mode 100644 index 0000000..b3f07cb --- /dev/null +++ b/Source/Silver.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# RemObjects Fire +Project("{656346D9-4656-40DA-A068-22D5425D4639}") = "Silver", "Silver.elements", "{9E7A4B59-8176-4CAE-B966-7E299171B148}" +EndProject +Project("{656346D9-4656-40DA-A068-22D5425D4639}") = "Swift.Shared", "Swift.Shared.elements", "{7952073B-795C-4074-954D-212FE780D7D3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|AnyCPU = Debug|AnyCPU + Release|AnyCPU = Release|AnyCPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9E7A4B59-8176-4CAE-B966-7E299171B148}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU + {9E7A4B59-8176-4CAE-B966-7E299171B148}.Debug|AnyCPU.Build.0 = Debug|AnyCPU + {9E7A4B59-8176-4CAE-B966-7E299171B148}.Release|AnyCPU.ActiveCfg = Release|AnyCPU + {9E7A4B59-8176-4CAE-B966-7E299171B148}.Release|AnyCPU.Build.0 = Release|AnyCPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/Source/String.Views.swift b/Source/String.Views.swift index 0839783..0014d43 100644 --- a/Source/String.Views.swift +++ b/Source/String.Views.swift @@ -40,20 +40,24 @@ public extension SwiftString { while te.MoveNext() { stringData.append(Character(nativeStringValue: te.Current as! NativeString)) } - #elseif COCOA + #elseif DARWIN var i = 0 while i < length(string) { - let sequenceLength = string.rangeOfComposedCharacterSequenceAtIndex(i).length + let sequenceLength = (string as! NSString).rangeOfComposedCharacterSequenceAtIndex(i).length //76192: Silver: can't use range as subscript? (SBL) let ch: NativeString = string.__substring(range: i ..< i+sequenceLength) stringData.append(Character(nativeStringValue: ch)) i += sequenceLength } + #elseif ISLAND + throw NotImplementedException("CharacterView is not fully implemented for Island yet.") + #hint Not implemented yet #endif - /* old logic to detect surrogate pairs; not needed right now + /* old logic to detect surrogate pairs; not needed right now + { let c = string[i] let c2 = Int(c) /*switch Int(c) { @@ -99,8 +103,8 @@ public extension SwiftString { addCharacter() i += 1 - }*/ - //addCharacter() + } + //addCharacter()*/ } public override var count: Int { return stringData.count } @@ -178,6 +182,13 @@ public extension SwiftString { return stringData[index] } + @Sequence + public func GetSequence() -> ISequence { + for i in startIndex ..< endIndex { + __yield self[i] + } + } + @ToString public func description() -> NativeString { var result = "UTF16CharacterView(" for i in startIndex..*/ { + public class UTF32View: BaseCharacterView { private let stringData: Byte[] private init(stringData: Byte[]) { @@ -207,7 +217,7 @@ public extension SwiftString { #elseif CLR stringData = System.Text.UTF32Encoding(/*bigendian:*/false, /*BOM:*/false).GetBytes(string) // todo check order #elseif ISLAND - stringData = Encoding.UTF32LE.GetBytes(aValue, /*BOM:*/false) // todo check order + stringData = System.Encoding.UTF32LE.GetBytes(string, /*BOM:*/false) // todo check order #elseif COCOA if let utf32 = string.dataUsingEncoding(.NSUTF32LittleEndianStringEncoding) { // todo check order stringData = Byte[](capacity: utf32.length); @@ -220,7 +230,13 @@ public extension SwiftString { public override var count: Int { return length(stringData) } - public override var endIndex: SwiftString.Index { return RemObjects.Elements.System.length(stringData)/4 } + public override var endIndex: SwiftString.Index { + #if COOPER + return remobjects.elements.system.length(stringData)/4 + #else + return RemObjects.Elements.System.length(stringData)/4 + #endif + } var first: UTF32Char? { return count > 0 ? self[0] : nil } @@ -263,9 +279,7 @@ public extension SwiftString { return result } } - #endif - #if !ISLAND public class UTF8View: BaseCharacterView { internal let stringData: UTF8Char[] @@ -279,7 +293,7 @@ public extension SwiftString { #elseif CLR stringData = System.Text.UTF8Encoding(/*BOM:*/false).GetBytes(string) #elseif ISLAND - stringData = Encoding.UTF8.GetBytes(aValue, /*BOM:*/false) + stringData = System.Encoding.UTF8.GetBytes(string, /*BOM:*/false) as! UTF8Char[] #elseif COCOA if let utf8 = string.dataUsingEncoding(.NSUTF8StringEncoding) { stringData = UTF8Char[](capacity: utf8.length); @@ -292,7 +306,13 @@ public extension SwiftString { public override var count: Int { return length(stringData) } - public override var endIndex: SwiftString.Index { return RemObjects.Elements.System.length(stringData) } + public override var endIndex: SwiftString.Index { + #if COOPER + return remobjects.elements.system.length(stringData) + #else + return RemObjects.Elements.System.length(stringData) + #endif + } var first: UTF8Char? { return count > 0 ? self[0] : nil } @@ -316,6 +336,11 @@ public extension SwiftString { return stringData[index] } + @Sequence + public func GetSequence() -> ISequence { + return stringData + } + @ToString public func description() -> NativeString { var result = "UTF8CharacterView(" for i in startIndex.., encoding: SwiftString.Encoding) { @@ -160,38 +140,74 @@ public struct SwiftString /*: Streamable*/ { return string.nativeStringValue } + public static func __implicit(_ char: Char) -> SwiftString { + #if TOFFEE + return NSString.string(format: "%c", char) + #else + return SwiftString(char.ToString()) + #endif + } + + public static class func __implicit(_ string: SwiftString) -> Char { + if length(string.nativeStringValue) == 1 { + return string.nativeStringValue[0] + } else { + #if ECHOES || ISLAND + throw InvalidCastException("Cannot cast non-single-character string '\(string.nativeStringValue)' to Char") + #elseif COOPER + throw ClassCastException("Cannto cast non-single-character string '\(string.nativeStringValue)' to Char") + #else + throw Exception("Cannto cast non-single-character string '\(string.nativeStringValue)' to Char") + #endif + } + } + public class func + (_ stringA: SwiftString, _ stringB: SwiftString) -> NativeString { return stringA.nativeStringValue+stringB.nativeStringValue } + // + // Protoools + // + + var hashValue: Int { + #if JAVA + return nativeStringValue.hashCode() + #elseif CLR || ISLAND + return nativeStringValue.GetHashCode() + #elseif COCOA + return nativeStringValue.hashValue() + #endif + } + + func ==(lhs: Self, rhs: Self) -> Bool { + return lhs.nativeStringValue == lhs.nativeStringValue + } + // // Properties // + #if DARWIN || !ISLAND public var characters: SwiftString.CharacterView { return SwiftString.CharacterView(string: nativeStringValue) } + #endif @ToString public func description() -> NativeString { return nativeStringValue } public var endIndex: SwiftString.Index { - return RemObjects.Elements.System.length(nativeStringValue) // for now? + #if COOPER + return remobjects.elements.system.length(nativeStringValue) // for now? + #else + return RemObjects.Elements.System.length(nativeStringValue) + #endif } var fastestEncoding: SwiftString.Encoding { return SwiftString.Encoding.utf16 } - public var hashValue: Int { - #if JAVA - return nativeStringValue.hashCode() - #elseif CLR || ISLAND - return nativeStringValue.GetHashCode() - #elseif COCOA - return nativeStringValue.hashValue() - #endif - } - public var isEmpty : Bool { #if JAVA return nativeStringValue.isEmpty() @@ -226,31 +242,36 @@ public struct SwiftString /*: Streamable*/ { #endif } - #if !ISLAND public var utf8: SwiftString.UTF8View { return SwiftString.UTF8View(string: nativeStringValue) } - #endif - #if COCOA public var utf8CString: UTF8Char[] { + #if JAVA + let buffer = java.nio.charset.Charset.forName("UTF8").encode(self) + let result = Byte[](buffer.remaining()) + buffer.get(result) + return result + #elseif CLR + return System.Text.Encoding.UTF8.GetBytes(nativeStringValue) + #elseif ISLAND + return RemObjects.Elements.System.Encoding.UTF8.GetBytes(nativeStringValue, false) + #elseif COCOA let utf8 = nativeStringValue.cStringUsingEncoding(.UTF8StringEncoding) - let len = strlen(utf8)+1 + let len = strlen(utf8) + 1 let result = UTF8Char[](len) memcpy(result, utf8, len) return result + #endif } - #endif public var utf16: SwiftString.UTF16View { return SwiftString.UTF16View(string: nativeStringValue) } - #if !ISLAND public var unicodeScalars: SwiftString.UnicodeScalarView { return SwiftString.UnicodeScalarView(string: nativeStringValue) } - #endif // // Methods @@ -338,6 +359,10 @@ public struct SwiftString /*: Streamable*/ { //public subscript(range: SwiftString.Index) -> Character // implicitly provided by the compiler, already + public subscript(index: Int) -> Char { + return nativeStringValue[index] + } + public subscript(range: Range/**/) -> SwiftString { if range.upperBound != nil { #if JAVA @@ -432,5 +457,4 @@ public struct SwiftString /*: Streamable*/ { return nil #endif } - } \ No newline at end of file diff --git a/Source/String_Extensions.swift b/Source/String_Extensions.swift index 66a903e..7e20dec 100644 --- a/Source/String_Extensions.swift +++ b/Source/String_Extensions.swift @@ -1,8 +1,8 @@ -public extension NativeString : Streamable { +public extension NativeString /*: Streamable*/ { typealias Index = Int - public init(count: Int, repeatedValue c: Char) { + public init(repeating c: Char, count: Int) { #if JAVA || ISLAND var chars = Char[](count) @@ -18,7 +18,7 @@ } public init(_ c: Char) { - return NativeString(count: 1, repeatedValue: c) + return NativeString(repeating: c, count: 1) } public init(_ object: Object) { @@ -108,7 +108,7 @@ #if JAVA return self.isEmpty() #elseif CLR || ISLAND - return String.IsNullOrEmpty(self) + return NativeString.IsNullOrEmpty(self) #elseif COCOA return length == 0 #endif @@ -141,7 +141,7 @@ //func components(separatedBy separator: CharacterSet) -> [String] { //} - func components(separatedBy separator: String) -> [String] { + public func components(separatedBy separator: String) -> [String] { let separatorLength = separator.length() if separatorLength == 0 { return [self] @@ -184,21 +184,17 @@ #endif } - #if !ISLAND public var utf8: SwiftString.UTF8View { return SwiftString.UTF8View(string: self) } - #endif public var utf16: SwiftString.UTF16View { return SwiftString.UTF16View(string: self) } - #if !ISLAND public var unicodeScalars: SwiftString.UnicodeScalarView { return SwiftString.UnicodeScalarView(string: self) } - #endif // // Methods @@ -249,15 +245,15 @@ // Subscripts // - func `prefix`(through: Index) -> NativeString { + public func `prefix`(through: Index) -> NativeString { return self[...through] // E119 Cannot use the unary operator "..." on type "extension String.Index" } - func `prefix`(upTo: Index) -> NativeString { + public func `prefix`(upTo: Index) -> NativeString { return self[.. NativeString { + public func suffix(from: Index) -> NativeString { return self[from...] } @@ -335,54 +331,4 @@ return nil #endif } - - public __abstract class CharacterView { - /*fileprivate*/internal init(string: NativeString) { - } - - public var startIndex: NativeString.Index { return 0 } - public __abstract var endIndex: NativeString.Index { get } - - } - - public class UTF16CharacterView: CharacterView, ICustomDebugStringConvertible { - private let string: NativeString - - /*fileprivate*/internal init(string: NativeString) { - self.string = string - } - - public override var endIndex: NativeString.Index { return length(string) } - - public subscript(index: Int) -> UTF16Char { - return string[index] - } - - #if COCOA - override var debugDescription: NativeString! { - var result = "UTF16CharacterView(" - for i in startIndex.. startIndex { - result += " " - } - result += UInt64(self[i]).toHexString(length: 4) - } - result += ")" - return result - } - #else - public var debugDescription: NativeString { - var result = "UTF16CharacterView(" - for i in startIndex.. startIndex { - result += " " - } - result += UInt64(self[i]).toHexString(length: 4) - } - result += ")" - return result - } - #endif - } - } \ No newline at end of file diff --git a/Source/Swift.Cooper.elements b/Source/Swift.Cooper.elements index 1e59547..6ec8049 100644 --- a/Source/Swift.Cooper.elements +++ b/Source/Swift.Cooper.elements @@ -2,15 +2,15 @@ 3.5 - 399BE68A-44C3-4357-8D11-4B64C6EC0674 + {399BE68A-44C3-4357-8D11-4B64C6EC0674} Library Release False Swift - swift JW0 - java.util,com.remobjects.elements.linq + java.util,remobjects.elements.linq True + silver .\bin\Debug diff --git a/Source/Swift.Echoes.Standard.elements b/Source/Swift.Echoes.Standard.elements index affc79f..3edd132 100644 --- a/Source/Swift.Echoes.Standard.elements +++ b/Source/Swift.Echoes.Standard.elements @@ -5,7 +5,6 @@ Swift {CDDEBE6E-6B6B-4EF7-B2E1-57239C443426} Library - Swift False False False @@ -13,7 +12,8 @@ False Release System.Collections.Generic;System.Linq - .NETStandard1.3 + .NETStandard2.0 + Silver false @@ -51,14 +51,12 @@ True SIGN - - - True - - + + + \ No newline at end of file diff --git a/Source/Swift.Echoes.elements b/Source/Swift.Echoes.elements index 2dee2a7..b0ea242 100644 --- a/Source/Swift.Echoes.elements +++ b/Source/Swift.Echoes.elements @@ -3,9 +3,8 @@ 3.5 Swift - BAE82ECC-39A5-4A18-9CE1-EAC0653F6E0F + {BAE82ECC-39A5-4A18-9CE1-EAC0653F6E0F} Library - Swift False False False @@ -14,6 +13,7 @@ Release v4.0 System.Collections.Generic;System.Linq + Silver false @@ -57,9 +57,7 @@ - - True - + diff --git a/Source/Swift.Island.Android.elements b/Source/Swift.Island.Android.elements index 4a28550..e09d403 100644 --- a/Source/Swift.Island.Android.elements +++ b/Source/Swift.Island.Android.elements @@ -3,15 +3,15 @@ 3.5 Swift - {fa456b74-3e30-45ed-91b2-6bb7a104f836} + {FA456B74-3E30-45ED-91B2-6BB7A104F836} StaticLibrary - Swift False False False False False Release + Silver false @@ -50,7 +50,6 @@ - diff --git a/Source/Swift.Island.Darwin.iOS.elements b/Source/Swift.Island.Darwin.iOS.elements index d2e4f71..56c1288 100644 --- a/Source/Swift.Island.Darwin.iOS.elements +++ b/Source/Swift.Island.Darwin.iOS.elements @@ -3,9 +3,8 @@ 3.5 Swift - {6f87c50f-069a-4e56-9b2e-044cbb68cc83} + {6F87C50F-069A-4E56-9B2E-044CBB68CC83} StaticLibrary - Swift False False False @@ -14,6 +13,9 @@ Release Foundation;RemObjects.Elements.System;rtl iOS + True + Silver + 9.0 false @@ -53,6 +55,7 @@ + diff --git a/Source/Swift.Island.Darwin.macOS.elements b/Source/Swift.Island.Darwin.macOS.elements index 32d1274..acfcfa1 100644 --- a/Source/Swift.Island.Darwin.macOS.elements +++ b/Source/Swift.Island.Darwin.macOS.elements @@ -3,9 +3,8 @@ 3.5 Swift - {792e19d0-3f6b-4ef5-a113-87c76eb0ce5e} + {792E19D0-3F6B-4EF5-A113-87C76EB0CE5E} StaticLibrary - Swift False False False @@ -14,6 +13,8 @@ Release Foundation;RemObjects.Elements.System;rtl macOS + Silver + 10.12 false @@ -48,12 +49,12 @@ False True SIGN - x86_64 + diff --git a/Source/Swift.Island.Darwin.tvOS.elements b/Source/Swift.Island.Darwin.tvOS.elements index 99a61bc..74458eb 100644 --- a/Source/Swift.Island.Darwin.tvOS.elements +++ b/Source/Swift.Island.Darwin.tvOS.elements @@ -3,9 +3,8 @@ 3.5 Swift - {a037c663-4495-4630-a9ef-39079ba1ec07} + {A037C663-4495-4630-A9EF-39079BA1EC07} StaticLibrary - Swift False False False @@ -14,6 +13,8 @@ Release Foundation;RemObjects.Elements.System;rtl tvOS + Silver + 9.0 false @@ -53,6 +54,7 @@ + diff --git a/Source/Swift.Island.Darwin.watchOS.elements b/Source/Swift.Island.Darwin.watchOS.elements index f02b615..1bbbcaa 100644 --- a/Source/Swift.Island.Darwin.watchOS.elements +++ b/Source/Swift.Island.Darwin.watchOS.elements @@ -3,9 +3,8 @@ 3.5 Swift - {b9065575-47d6-4740-8d96-d8f5a1a30b0b} + {B9065575-47D6-4740-8D96-D8F5A1A30B0B} StaticLibrary - Swift False False False @@ -14,6 +13,8 @@ Release Foundation;RemObjects.Elements.System;rtl watchOS + Silver + 3.0 false @@ -53,6 +54,7 @@ + diff --git a/Source/Swift.Island.Linux.elements b/Source/Swift.Island.Linux.elements index 1c86cd7..194addb 100644 --- a/Source/Swift.Island.Linux.elements +++ b/Source/Swift.Island.Linux.elements @@ -3,15 +3,15 @@ 3.5 Swift - {a764b9ef-be23-43ae-aceb-43f24f45eae9} + {A764B9EF-BE23-43AE-ACEB-43F24F45EAE9} StaticLibrary - Swift False False False False False Release + Silver false diff --git a/Source/Swift.Island.WebAssembly.elements b/Source/Swift.Island.WebAssembly.elements index 4ac3b41..4000898 100644 --- a/Source/Swift.Island.WebAssembly.elements +++ b/Source/Swift.Island.WebAssembly.elements @@ -3,15 +3,15 @@ 3.5 Swift - {d38b4354-35c8-4bc9-9415-4d72a1f77ca1} + {D38B4354-35C8-4BC9-9415-4D72A1F77CA1} StaticLibrary - Swift False False False False False Release + Silver false diff --git a/Source/Swift.Island.Windows.elements b/Source/Swift.Island.Windows.elements index 4539b9b..2307df3 100644 --- a/Source/Swift.Island.Windows.elements +++ b/Source/Swift.Island.Windows.elements @@ -3,15 +3,15 @@ 3.5 Swift - {d32e206a-1255-4da9-8287-64e5e988aba4} + {D32E206A-1255-4DA9-8287-64E5E988ABA4} StaticLibrary - Swift False False False False False Release + Silver false diff --git a/Source/Swift.Shared.projitems b/Source/Swift.Shared.projitems index d8a6e5b..2b48220 100644 --- a/Source/Swift.Shared.projitems +++ b/Source/Swift.Shared.projitems @@ -4,9 +4,8 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) true 7952073B-795C-4074-954D-212FE780D7D3 - - Swift.Shared + {7952073B-795C-4074-954D-212FE780D7D3} @@ -65,7 +64,7 @@ - + String @@ -94,6 +93,18 @@ + + Memory + + + Memory + + + Memory + + + Sequences + @@ -111,5 +122,8 @@ True + + True + \ No newline at end of file diff --git a/Source/Swift.Toffee.iOS.elements b/Source/Swift.Toffee.iOS.elements index eeefb76..5932029 100644 --- a/Source/Swift.Toffee.iOS.elements +++ b/Source/Swift.Toffee.iOS.elements @@ -2,9 +2,8 @@ Swift - 95F9545C-39BE-4A02-8673-8382ECB3F7AD + {95F9545C-39BE-4A02-8673-8382ECB3F7AD} StaticLibrary - Swift False False False @@ -14,9 +13,11 @@ iOS True Foundation,RemObjects.Elements.Linq - 7.1 + 9.0 True NW6 + True + Silver false diff --git a/Source/Swift.Toffee.macOS.elements b/Source/Swift.Toffee.macOS.elements index 3e3fdcb..f6fef88 100644 --- a/Source/Swift.Toffee.macOS.elements +++ b/Source/Swift.Toffee.macOS.elements @@ -2,9 +2,8 @@ Swift - 8F87CCEF-C142-49A8-8828-32211B2CBFBE + {8F87CCEF-C142-49A8-8828-32211B2CBFBE} StaticLibrary - Swift False False False @@ -14,10 +13,11 @@ macOS True Foundation,RemObjects.Elements.Linq - 10.9 + 10.12 True DEBUG;OLD_DEPLOYMENT_TARGET;TRACE NW6 + Silver false @@ -37,7 +37,6 @@ False False True - diff --git a/Source/Swift.Toffee.tvOS.elements b/Source/Swift.Toffee.tvOS.elements index 2f0cc79..f01f909 100644 --- a/Source/Swift.Toffee.tvOS.elements +++ b/Source/Swift.Toffee.tvOS.elements @@ -2,9 +2,8 @@ Swift - EA152C1C-C6DD-48F8-9415-8B7FDA4653D9 + {EA152C1C-C6DD-48F8-9415-8B7FDA4653D9} StaticLibrary - Swift False False False @@ -14,9 +13,10 @@ tvOS True Foundation,RemObjects.Elements.Linq - 9.2 + 9.0 True NW6 + Silver false diff --git a/Source/Swift.Toffee.watchOS.elements b/Source/Swift.Toffee.watchOS.elements index da8e109..8d4954b 100644 --- a/Source/Swift.Toffee.watchOS.elements +++ b/Source/Swift.Toffee.watchOS.elements @@ -2,9 +2,8 @@ Swift - E0C9DDDB-B83F-4164-ADE4-577FB6611F3F + {E0C9DDDB-B83F-4164-ADE4-577FB6611F3F} StaticLibrary - Swift False False False @@ -14,9 +13,10 @@ watchOS True Foundation,RemObjects.Elements.Linq - 2.2 + 3.0 True NW6 + Silver false diff --git a/Source/Char_Extensions.swift b/Source/UnicodeScalar_Extensions.swift similarity index 100% rename from Source/Char_Extensions.swift rename to Source/UnicodeScalar_Extensions.swift diff --git a/Source/Unmanaged.swift b/Source/Unmanaged.swift new file mode 100644 index 0000000..a6f8bd0 --- /dev/null +++ b/Source/Unmanaged.swift @@ -0,0 +1,54 @@ +#if DARWIN +public struct Unmanaged where Instance : AnyObject { + + #if ISLAND + func autorelease() -> Unmanaged { + CFAutorelease(opaque) + return self + } + func release() { + CFRelease(opaque) + } + func retain() -> Unmanaged { + CFRetain(opaque) + return self + } + #endif + + func takeRetainedValue() -> Instance { + return bridge(opaque, BridgeMode.Bridge) + } + + func takeUnretainedValue() -> Instance { + return bridge(opaque, BridgeMode.Transfer) + } + + func toOpaque() -> OpaquePointer { + return opaque + } + + static func fromOpaque(_ value: OpaquePointer) -> Unmanaged { + Unmanaged(with: value) + } + static func passRetained(_ value: Instance) -> Unmanaged { + Unmanaged(retained: value) + } + static func passUnretained(_ value: Instance) -> Unmanaged { + Unmanaged(unretained: value) + } + + private let opaque: OpaquePointer + + private init(with value: OpaquePointer) { + opaque = value + } + + private init(withRetained value: Instance) { + opaque = bridge(value, BridgeMode.Retained) + } + + private init(withUnretained value: Instance) { + opaque = bridge(value, BridgeMode.Bridge) + } +} +#endif \ No newline at end of file diff --git a/Tests/Dictionary.swift b/Tests/Dictionary.swift new file mode 100644 index 0000000..440d565 --- /dev/null +++ b/Tests/Dictionary.swift @@ -0,0 +1,25 @@ +import RemObjects.Elements.EUnit + +public class DictionaryTests : Test { + + public func test82211() { + + var dict = [String: String]() + dict["test"] = "someString" + + writeLn("dict[\"test\"] \(dict["test"])") + + Check.AreEqual(dict["test"], "someString") // good + Check.IsNotNil(dict["test"]) // good + Check.IsTrue(assigned(dict["test"])) // fails + Check.IsTrue(dict["test"] != nil) // fails + writeLn("dict[\"test\"] != nil \(dict["test"] != nil)") // False + writeLn("dict[\"test\"] == nil \(dict["test"] == nil)") // True + + let hasValue: Bool = dict["test"] != nil + writeLn("hasValue \(hasValue)") + if !hasValue { + throw Exception("dict[test] is not nil!") + } + } +} \ No newline at end of file diff --git a/Tests/Program.swift b/Tests/Program.swift index bbad872..020127a 100644 --- a/Tests/Program.swift +++ b/Tests/Program.swift @@ -1,4 +1,4 @@ -import RemObjects.Elements.EUnit +import RemObjects.Elements.EUnit let lTests = Discovery.DiscoverTests() -Runner.RunTests(lTests, withListener: Runner.DefaultListener) \ No newline at end of file +return Runner.RunTests(lTests, withListener: Runner.DefaultListener) == TestState.Succeeded ? 0 : 1 \ No newline at end of file diff --git a/Tests/Swift.Tests.elements b/Tests/Swift.Tests.elements index b6c0df2..a6cdce8 100644 --- a/Tests/Swift.Tests.elements +++ b/Tests/Swift.Tests.elements @@ -8,6 +8,7 @@ Release True Entitlements.entitlements + True False @@ -22,6 +23,7 @@ Cooper Plain + java.util,remobjects.elements.linq Echoes @@ -72,10 +74,16 @@ Cooper + True Cooper - + + Cooper + True + + Cooper + True Echoes @@ -94,9 +102,16 @@ Echoes True + + Echoes + True + Island.Darwin.macOS + + Island.Darwin.macOS + Island.Darwin.macOS @@ -109,6 +124,9 @@ Island.Darwin.iOS + + Island.Darwin.iOS + Island.Darwin.iOS @@ -121,6 +139,9 @@ Island.Darwin.tvOS + + Island.Darwin.tvOS + Island.Darwin.tvOS @@ -133,6 +154,9 @@ Island.Darwin.watchOS + + Island.Darwin.watchOS + Island.Darwin.watchOS @@ -142,10 +166,56 @@ Island.Darwin.watchOS + + Island.Windows + + + Island.Windows + + + Island.Windows + + + Island.Windows + + + Island.Linux + + + Island.Linux + + + Island.Linux + + + Island.Linux + + + Island.WebAssembly + + + Island.WebAssembly + + + Island.WebAssembly + + + Island.Android + + + Island.Android + + + Island.Android + + + Island.Android + + diff --git a/Tests/Swift.Tests.sln b/Tests/Swift.Tests.sln new file mode 100644 index 0000000..4a4915d --- /dev/null +++ b/Tests/Swift.Tests.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# RemObjects Fire +Project("{656346D9-4656-40DA-A068-22D5425D4639}") = "Swift.Tests", "Swift.Tests.elements", "{F22ABF38-8775-4118-8590-30756523030D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|AnyCPU = Debug|AnyCPU + Release|AnyCPU = Release|AnyCPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F22ABF38-8775-4118-8590-30756523030D}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU + {F22ABF38-8775-4118-8590-30756523030D}.Debug|AnyCPU.Build.0 = Debug|AnyCPU + {F22ABF38-8775-4118-8590-30756523030D}.Release|AnyCPU.ActiveCfg = Release|AnyCPU + {F22ABF38-8775-4118-8590-30756523030D}.Release|AnyCPU.Build.0 = Release|AnyCPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file