diff --git a/.swiftformat b/.swiftformat index 5aa81fb..ef7d0bf 100644 --- a/.swiftformat +++ b/.swiftformat @@ -20,3 +20,4 @@ --disable spaceAroundOperators --disable wrapMultilineStatementBraces +--disable noForceUnwrapInTests diff --git a/Package.resolved b/Package.resolved index b39b24a..25b9186 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "b227941dd62d804ef972d6f7cb4bdd5c826497fbd15df926855a4e2751d9219d", + "originHash" : "4606ae1fdb10a0e40d1bda84d2d7bd48531d8cd2d56b8584c27118738cb80182", "pins" : [ { "identity" : "semanticversion", @@ -42,8 +42,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/nicklockwood/SwiftFormat", "state" : { - "revision" : "468a7d32dedc8d352c191594b3b45d9fd8ba291b", - "version" : "0.55.5" + "revision" : "a5fa7a6a57abeb834df1b3fa43ea9133137d5ade", + "version" : "0.61.1" } } ], diff --git a/Package.swift b/Package.swift index b16c321..fddc866 100644 --- a/Package.swift +++ b/Package.swift @@ -48,7 +48,7 @@ let package = Package( .target( name: "PklSwift", dependencies: ["PklMessagePack", "PklSwiftInternals", "SemanticVersion"], - swiftSettings: [.enableUpcomingFeature("StrictConcurrency")], + swiftSettings: [.enableUpcomingFeature("StrictConcurrency")] ), .target( name: "PklSwiftInternals", diff --git a/Sources/PklMessagePack/Decoder/KeyedDecodingContainer.swift b/Sources/PklMessagePack/Decoder/KeyedDecodingContainer.swift index b98d05c..5f75d4e 100644 --- a/Sources/PklMessagePack/Decoder/KeyedDecodingContainer.swift +++ b/Sources/PklMessagePack/Decoder/KeyedDecodingContainer.swift @@ -193,7 +193,7 @@ extension MessagePackValue { } extension _MessagePackDecoder { - final class KeyedContainer where Key: CodingKey { + final class KeyedContainer { var value: [(MessagePackValue, MessagePackValue)] var index: Int var codingPath: [CodingKey] @@ -248,10 +248,9 @@ extension _MessagePackDecoder.KeyedContainer: KeyedDecodingContainerProtocol { } var allEntries: [KeyMessagePackValueEntry] { - let keys = self.value.compactMap { kv in + self.value.compactMap { kv in Key(stringValue: kv.0.stringValue).map { KeyMessagePackValueEntry(key: $0, value: kv.1) } } - return keys } func contains(_ key: Key) -> Bool { @@ -267,7 +266,7 @@ extension _MessagePackDecoder.KeyedContainer: KeyedDecodingContainerProtocol { } } - func decode(_ typ: T.Type, forKey key: Key) throws -> T where T: Decodable { + func decode(_ typ: T.Type, forKey key: Key) throws -> T { defer { index += 1 } @@ -305,8 +304,8 @@ extension _MessagePackDecoder.KeyedContainer: KeyedDecodingContainerProtocol { } } - func nestedContainer(keyedBy nestedKeyType: NestedKey.Type, forKey key: Key) throws - -> KeyedDecodingContainer where NestedKey: CodingKey { + func nestedContainer(keyedBy nestedKeyType: NestedKey.Type, forKey key: Key) throws + -> KeyedDecodingContainer { try checkCanDecodeValue(forKey: key) guard let msgPackValue = strMap[key.stringValue] else { diff --git a/Sources/PklMessagePack/Decoder/KeyedSingleDecodingContainer.swift b/Sources/PklMessagePack/Decoder/KeyedSingleDecodingContainer.swift index 0355c28..1823530 100644 --- a/Sources/PklMessagePack/Decoder/KeyedSingleDecodingContainer.swift +++ b/Sources/PklMessagePack/Decoder/KeyedSingleDecodingContainer.swift @@ -17,7 +17,7 @@ import Foundation extension _MessagePackDecoder { - final class KeyedSingleContainer where Key: CodingKey { + final class KeyedSingleContainer { var value: MessagePackValue var index: Int var codingPath: [CodingKey] @@ -62,7 +62,7 @@ extension _MessagePackDecoder.KeyedSingleContainer: KeyedDecodingContainerProtoc self.value == MessagePackValue.nil } - func decode(_ typ: T.Type, forKey key: Key) throws -> T where T: Decodable { + func decode(_: T.Type, forKey key: Key) throws -> T { _ = self.value.getAs(T.self) // FIXME: make optional let context = DecodingError.Context( @@ -75,8 +75,8 @@ extension _MessagePackDecoder.KeyedSingleContainer: KeyedDecodingContainerProtoc fatalError("\(#function)") } - func nestedContainer(keyedBy nestedKeyType: NestedKey.Type, forKey key: Key) throws - -> KeyedDecodingContainer where NestedKey: CodingKey { + func nestedContainer(keyedBy nestedKeyType: NestedKey.Type, forKey key: Key) throws + -> KeyedDecodingContainer { fatalError("\(#function)") } diff --git a/Sources/PklMessagePack/Decoder/MessagePackDecoder.swift b/Sources/PklMessagePack/Decoder/MessagePackDecoder.swift index ea796e1..33e429d 100644 --- a/Sources/PklMessagePack/Decoder/MessagePackDecoder.swift +++ b/Sources/PklMessagePack/Decoder/MessagePackDecoder.swift @@ -66,14 +66,14 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Unknown msgpack format: \(code.toHex())" - )) + ) + ) } } - public func decode(as type: T.Type) throws -> T where T: Decodable { + public func decode(as type: T.Type) throws -> T { let value = try decodeGeneric() - let converted = try value.decodeInto(type) - return converted + return try value.decodeInto(type) } public func decodeBool() throws -> Bool { @@ -83,7 +83,8 @@ public final class MessagePackDecoder { case .true: return true default: throw DecodingError.dataCorrupted( - .init(codingPath: [], debugDescription: "Invalid code for bool: \(code.toHex())")) + .init(codingPath: [], debugDescription: "Invalid code for bool: \(code.toHex())") + ) } } @@ -93,7 +94,8 @@ public final class MessagePackDecoder { return nil } throw DecodingError.dataCorrupted( - .init(codingPath: [], debugDescription: "Invalid code for nil: \(code.toHex())")) + .init(codingPath: [], debugDescription: "Invalid code for nil: \(code.toHex())") + ) } public func decodeInt() throws -> Int { @@ -156,7 +158,8 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Invalid format for String length: \(code.toHex())" - )) + ) + ) } let bytes = try read(length) @@ -195,7 +198,8 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Invalid format for date \(code.toHex())" - )) + ) + ) } let timeInterval = TimeInterval(seconds) + nanoseconds / Double(NSEC_PER_SEC) @@ -217,14 +221,16 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Invalid format for binary length \(code.toHex())" - )) + ) + ) } let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: length, alignment: 1) let readCount = try reader.read(into: buffer) if readCount < length { throw DecodingError.dataCorrupted( - DecodingError.Context(codingPath: [], debugDescription: "Unexpected end of input")) + DecodingError.Context(codingPath: [], debugDescription: "Unexpected end of input") + ) } return Array(buffer) } @@ -251,7 +257,8 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Invalid code \(code) for array header" - )) + ) + ) } } @@ -268,7 +275,8 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Invalid format \(code) for maps" - )) + ) + ) } } @@ -301,7 +309,8 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Invalid format \(code) for extensions" - )) + ) + ) } } @@ -312,12 +321,13 @@ public final class MessagePackDecoder { let readCount = try reader.read(into: buffer) if readCount < length { throw DecodingError.dataCorrupted( - DecodingError.Context(codingPath: [], debugDescription: "Unexpected end of input")) + DecodingError.Context(codingPath: [], debugDescription: "Unexpected end of input") + ) } return (type, Array(buffer)) } - private func decodeFloatingPoint() throws -> T where T: BinaryFloatingPoint { + private func decodeFloatingPoint() throws -> T { let code = try readByte() let t: T? switch code { @@ -333,18 +343,20 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Invalid format for floating points: \(code.toHex())" - )) + ) + ) } guard let t else { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Unable to decode bytes into BinaryFloatingPoint" - )) + ) + ) } return t } - private func decodeBinaryInteger() throws -> T where T: BinaryInteger { + private func decodeBinaryInteger() throws -> T { let code = try readByte() var t: T? @@ -374,14 +386,16 @@ public final class MessagePackDecoder { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Invalid format for int: \(code.toHex())" - )) + ) + ) } guard let value = t else { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: [], debugDescription: "Unable to decode bytes into BinaryInteger" - )) + ) + ) } return value } @@ -392,7 +406,8 @@ public final class MessagePackDecoder { let readCount = try reader.read(into: out) if readCount == 0 { throw DecodingError.dataCorrupted( - DecodingError.Context(codingPath: [], debugDescription: "Unexpected end of input")) + DecodingError.Context(codingPath: [], debugDescription: "Unexpected end of input") + ) } return out[0] @@ -404,12 +419,13 @@ public final class MessagePackDecoder { let readCount = try reader.read(into: out) if readCount < length { throw DecodingError.dataCorrupted( - DecodingError.Context(codingPath: [], debugDescription: "Unexpected end of input")) + DecodingError.Context(codingPath: [], debugDescription: "Unexpected end of input") + ) } return [UInt8](out) } - private func read(_: T.Type) throws -> T where T: FixedWidthInteger { + private func read(_: T.Type) throws -> T { let stride = MemoryLayout.stride let bytes = try read(stride) return T(bytes: bytes) @@ -461,7 +477,7 @@ extension MessagePackValue { } extension MessagePackValue { - public func decode(_: T.Type) throws -> T where T: Decodable { + public func decode(_: T.Type) throws -> T { try T(from: _MessagePackDecoder(value: self)) } } diff --git a/Sources/PklMessagePack/Decoder/SingleValueDecodingContainer.swift b/Sources/PklMessagePack/Decoder/SingleValueDecodingContainer.swift index 385b20b..1e073a7 100644 --- a/Sources/PklMessagePack/Decoder/SingleValueDecodingContainer.swift +++ b/Sources/PklMessagePack/Decoder/SingleValueDecodingContainer.swift @@ -80,7 +80,7 @@ extension _MessagePackDecoder.SingleValueContainer: SingleValueDecodingContainer } } - func decode(_: T.Type) throws -> T where T: BinaryInteger & Decodable { + func decode(_: T.Type) throws -> T { switch value { case .int(let value): guard let value = value as? T else { @@ -142,7 +142,7 @@ extension _MessagePackDecoder.SingleValueContainer: SingleValueDecodingContainer } } - func decode(_ type: T.Type) throws -> T where T: Decodable { + func decode(_ type: T.Type) throws -> T { switch type { case is Data.Type: return try self.decode(Data.self) as! T @@ -154,8 +154,7 @@ extension _MessagePackDecoder.SingleValueContainer: SingleValueDecodingContainer return try self.decode(URL.self) as! T default: let decoder = _MessagePackDecoder(value: value) - let value = try T(from: decoder) - return value + return try T(from: decoder) } } diff --git a/Sources/PklMessagePack/Decoder/UnkeyedDecodingContainer.swift b/Sources/PklMessagePack/Decoder/UnkeyedDecodingContainer.swift index 86d5010..128af7a 100644 --- a/Sources/PklMessagePack/Decoder/UnkeyedDecodingContainer.swift +++ b/Sources/PklMessagePack/Decoder/UnkeyedDecodingContainer.swift @@ -63,7 +63,7 @@ extension _MessagePackDecoder.UnkeyedContainer: UnkeyedDecodingContainer { } } - func decode(_ typ: T.Type) throws -> T where T: Decodable { + func decode(_ typ: T.Type) throws -> T { try checkCanDecodeValue() defer { currentIndex += 1 @@ -90,7 +90,7 @@ extension _MessagePackDecoder.UnkeyedContainer: UnkeyedDecodingContainer { } } - func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey: CodingKey { + func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer { try checkCanDecodeValue() defer { currentIndex += 1 } diff --git a/Sources/PklMessagePack/Decoder/UnkeyedMapDecodingContainer.swift b/Sources/PklMessagePack/Decoder/UnkeyedMapDecodingContainer.swift index fc9f025..95c8430 100644 --- a/Sources/PklMessagePack/Decoder/UnkeyedMapDecodingContainer.swift +++ b/Sources/PklMessagePack/Decoder/UnkeyedMapDecodingContainer.swift @@ -66,7 +66,7 @@ extension _MessagePackDecoder { self.value.count } - // var value: [(MessagePackValue, MessagePackValue)] + /// var value: [(MessagePackValue, MessagePackValue)] var value: [MessagePackValue] // flattened var currentIndex: Int = 0 @@ -97,7 +97,7 @@ extension _MessagePackDecoder.MapUnkeyedContainer: UnkeyedDecodingContainer { fatalError("Not implemented: \(#function)") } - func decode(_ typ: T.Type) throws -> T where T: Decodable { + func decode(_ typ: T.Type) throws -> T { defer { currentIndex += 1 } @@ -110,7 +110,7 @@ extension _MessagePackDecoder.MapUnkeyedContainer: UnkeyedDecodingContainer { fatalError("Not implemented: \(#function)") } - func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey: CodingKey { + func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer { fatalError("Not implemented: \(#function)") } diff --git a/Sources/PklMessagePack/Decoder/_MessagePackDecoder.swift b/Sources/PklMessagePack/Decoder/_MessagePackDecoder.swift index 8dde646..984e89c 100644 --- a/Sources/PklMessagePack/Decoder/_MessagePackDecoder.swift +++ b/Sources/PklMessagePack/Decoder/_MessagePackDecoder.swift @@ -27,8 +27,7 @@ final class _MessagePackDecoder: Decoder { self.value = value } - func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer - where Key: CodingKey { + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { switch self.value { case .map(let map): let container = _MessagePackDecoder.KeyedContainer( @@ -88,7 +87,7 @@ protocol MessagePackDecodingContainer: AnyObject { } extension MessagePackValue { - func decodeInto(_ typ: T.Type) throws -> T where T: Decodable { + func decodeInto(_ typ: T.Type) throws -> T { let decoder = _MessagePackDecoder(value: self) switch typ { case is Data.Type: diff --git a/Sources/PklMessagePack/Encoder/KeyedEncodingContainer.swift b/Sources/PklMessagePack/Encoder/KeyedEncodingContainer.swift index 9952e12..37ac3dd 100644 --- a/Sources/PklMessagePack/Encoder/KeyedEncodingContainer.swift +++ b/Sources/PklMessagePack/Encoder/KeyedEncodingContainer.swift @@ -17,7 +17,7 @@ import Foundation extension _MessagePackEncoder { - final class KeyedContainer where Key: CodingKey { + final class KeyedContainer { private var storage: [AnyCodingKey: _MessagePackEncodingContainer] = [:] var codingPath: [CodingKey] @@ -62,8 +62,8 @@ extension _MessagePackEncoder.KeyedContainer: KeyedEncodingContainerProtocol { return container } - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) - -> KeyedEncodingContainer where NestedKey: CodingKey { + func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) + -> KeyedEncodingContainer { let container = _MessagePackEncoder.KeyedContainer( codingPath: self.nestedCodingPath(forKey: key), userInfo: self.userInfo ) diff --git a/Sources/PklMessagePack/Encoder/MessagePackEncoder.swift b/Sources/PklMessagePack/Encoder/MessagePackEncoder.swift index b5c5ddb..77de08f 100644 --- a/Sources/PklMessagePack/Encoder/MessagePackEncoder.swift +++ b/Sources/PklMessagePack/Encoder/MessagePackEncoder.swift @@ -96,7 +96,7 @@ extension _MessagePackEncoder: Encoder { precondition(self.container == nil) } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer { self.assertCanCreateContainer() let container = KeyedContainer(codingPath: self.codingPath, userInfo: self.userInfo) diff --git a/Sources/PklMessagePack/Encoder/UnkeyedEncodingContainer.swift b/Sources/PklMessagePack/Encoder/UnkeyedEncodingContainer.swift index ae05138..3b3ccc5 100644 --- a/Sources/PklMessagePack/Encoder/UnkeyedEncodingContainer.swift +++ b/Sources/PklMessagePack/Encoder/UnkeyedEncodingContainer.swift @@ -59,9 +59,9 @@ extension _MessagePackEncoder.UnkeyedContainer: UnkeyedEncodingContainer { return container } - func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer< + func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer< NestedKey - > where NestedKey: CodingKey { + > { let container = _MessagePackEncoder.KeyedContainer( codingPath: self.nestedCodingPath, userInfo: self.userInfo ) diff --git a/Sources/PklSwift/Decoder/PklDecoder.swift b/Sources/PklSwift/Decoder/PklDecoder.swift index 2607910..ae79960 100644 --- a/Sources/PklSwift/Decoder/PklDecoder.swift +++ b/Sources/PklSwift/Decoder/PklDecoder.swift @@ -51,7 +51,8 @@ extension PklSerializableType { .init( codingPath: codingPath, debugDescription: "Expected at least \(min) fields but got \(fields.count)" - )) + ) + ) } } } @@ -74,7 +75,8 @@ extension Decodable where Self: PklSerializableType { .init( codingPath: codingPath, debugDescription: "Expected array but got \(decoder.value.debugDataTypeDescription)" - )) + ) + ) } let code = try arr[0].decode(PklValueType.self) guard arr.count > 0 else { @@ -82,11 +84,13 @@ extension Decodable where Self: PklSerializableType { .init( codingPath: codingPath, debugDescription: "Expected non-empty array" - )) + ) + ) } guard Self.messageTag == code else { throw DecodingError.dataCorrupted( - .init(codingPath: codingPath, debugDescription: "Cannot decode \(code) into \(Self.self)")) + .init(codingPath: codingPath, debugDescription: "Cannot decode \(code) into \(Self.self)") + ) } self = try Self.decode(arr, codingPath: codingPath) } @@ -111,12 +115,14 @@ extension PklSerializableValueUnitType { .init( codingPath: codingPath, debugDescription: "Expected array but got \(value.debugDataTypeDescription)" - )) + ) + ) } let code = try arr[0].decode(PklValueType.self) guard Self.messageTag == code else { throw DecodingError.dataCorrupted( - .init(codingPath: codingPath, debugDescription: "Cannot decode \(code) into \(Self.self)")) + .init(codingPath: codingPath, debugDescription: "Cannot decode \(code) into \(Self.self)") + ) } let value = try arr[1].decode(Self.ValueType.self) @@ -128,7 +134,7 @@ extension PklSerializableValueUnitType { public enum PklDecoder {} extension PklDecoder { - public static func decode(_ type: T.Type, from bytes: [UInt8]) throws -> T where T: Decodable { + public static func decode(_: T.Type, from bytes: [UInt8]) throws -> T { let reader = BufferReader(bytes) let value = try MessagePackDecoder(reader: reader).decodeGeneric() return try T(from: _PklDecoder(value: value)) @@ -138,7 +144,7 @@ extension PklDecoder { final class _PklDecoder: Decoder { var codingPath: [CodingKey] = [] - // not used + /// not used var userInfo: [CodingUserInfoKey: Any] { get { [:] @@ -155,8 +161,7 @@ final class _PklDecoder: Decoder { self.codingPath = codingPath } - func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer - where Key: CodingKey { + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { try _PklDecoder.getNestedKeyedContainer(keyedBy: type, value: self.value, codingPath: self.codingPath) } @@ -169,7 +174,8 @@ final class _PklDecoder: Decoder { .init( codingPath: self.codingPath, debugDescription: "Expected an array type, but got \(self.value.debugDataTypeDescription)" - )) + ) + ) } } @@ -189,7 +195,8 @@ extension _PklDecoder { .init( codingPath: codingPath, debugDescription: "Expected array with at least 2 items, type but got \(value.count)" - )) + ) + ) } let type = try value[0].decode(PklValueType.self) switch type { @@ -231,7 +238,8 @@ extension _PklDecoder { .init( codingPath: codingPath, debugDescription: "Expected array with at least 2 items, type but got \(value.count)" - )) + ) + ) } let type = try value[0].decode(PklValueType.self) switch type { @@ -248,7 +256,8 @@ extension _PklDecoder { .init( codingPath: codingPath, debugDescription: "Expected array type but got \(value[1].debugDescription)" - )) + ) + ) } var arr: [AnyHashable?] = [] arr.reserveCapacity(pklArray.count) @@ -266,7 +275,8 @@ extension _PklDecoder { .init( codingPath: codingPath, debugDescription: "Expected map type but got \(value[1].debugDescription)" - )) + ) + ) } var map: [AnyHashable?: AnyHashable?] = [:] for (k, v) in pklMap { @@ -293,7 +303,8 @@ extension _PklDecoder { .init( codingPath: codingPath, debugDescription: "Expected binary type but got \(value[1].debugDescription)" - )) + ) + ) } return PklAny(value: bytes) default: @@ -301,7 +312,8 @@ extension _PklDecoder { .init( codingPath: codingPath, debugDescription: "Unexpected type \(value[0].debugDescription)" - )) + ) + ) } case .bool(let b): return PklAny(value: b) @@ -364,6 +376,7 @@ public struct PklAny: Decodable, Hashable { .init( codingPath: decoder.codingPath, debugDescription: "Could not decode polymorphic type" - )) + ) + ) } } diff --git a/Sources/PklSwift/Decoder/PklMapDecodingContainer.swift b/Sources/PklSwift/Decoder/PklMapDecodingContainer.swift index 69941eb..fe81ced 100644 --- a/Sources/PklSwift/Decoder/PklMapDecodingContainer.swift +++ b/Sources/PklSwift/Decoder/PklMapDecodingContainer.swift @@ -18,14 +18,14 @@ import PklMessagePack extension _PklDecoder { /// Decoding container that handles `Map` and `Mapping`. - class PklMapDecodingContainer: KeyedDecodingContainerProtocol where Key: CodingKey { - public typealias Key = Key + class PklMapDecodingContainer: KeyedDecodingContainerProtocol { + typealias Key = Key let entries: [(MessagePackValue, MessagePackValue)] let codingPath: [CodingKey] - public init( + init( value: [MessagePackValue], codingPath: [CodingKey] ) throws { @@ -88,7 +88,7 @@ extension _PklDecoder { self.entriesKeyedByString[key.stringValue] == .nil } - func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { + func decode(_ type: T.Type, forKey key: Key) throws -> T { for entry in self.allEntries { if entry.key.stringValue == key.stringValue { // TODO: not great, compare underlying value? // special case for polymorphic types @@ -103,8 +103,8 @@ extension _PklDecoder { throw DecodingError.keyNotFound(key, .init(codingPath: self.codingPath, debugDescription: "Missing key \(key)")) } - func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws - -> KeyedDecodingContainer where NestedKey: CodingKey { + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws + -> KeyedDecodingContainer { guard let value = entriesKeyedByString[key.stringValue] else { throw DecodingError.keyNotFound(key, .init(codingPath: self.codingPath, debugDescription: "Missing key \(key)")) } diff --git a/Sources/PklSwift/Decoder/PklSingleValueDecodingContainer.swift b/Sources/PklSwift/Decoder/PklSingleValueDecodingContainer.swift index 5d9cedb..f211afb 100644 --- a/Sources/PklSwift/Decoder/PklSingleValueDecodingContainer.swift +++ b/Sources/PklSwift/Decoder/PklSingleValueDecodingContainer.swift @@ -131,7 +131,7 @@ class PklSingleValueDecodingContainer: SingleValueDecodingContainer { try self.decodeBinaryInteger() } - func decode(_ type: T.Type) throws -> T where T: Decodable { + func decode(_ type: T.Type) throws -> T { if type == PklAny.self { guard let result = try _PklDecoder.decodePolymorphic(value, codingPath: codingPath) else { throw DecodingError.typeMismatch(T.self, .init(codingPath: self.codingPath, debugDescription: "Tried to decode but got nil")) @@ -143,7 +143,7 @@ class PklSingleValueDecodingContainer: SingleValueDecodingContainer { return try T(from: decoder) } - private func decodeBinaryInteger() throws -> T where T: BinaryInteger { + private func decodeBinaryInteger() throws -> T { switch self.value { case .int(let value): guard let result = T(exactly: value) else { diff --git a/Sources/PklSwift/Decoder/PklTypedDecodingContainer.swift b/Sources/PklSwift/Decoder/PklTypedDecodingContainer.swift index a18da8b..991c82e 100644 --- a/Sources/PklSwift/Decoder/PklTypedDecodingContainer.swift +++ b/Sources/PklSwift/Decoder/PklTypedDecodingContainer.swift @@ -30,7 +30,8 @@ extension _PklDecoder { .init( codingPath: codingPath, debugDescription: "Expected property object member, but got \(pklType)" - )) + ) + ) } if case .string(let propertyName) = parts[1] { result[propertyName] = parts[2] @@ -40,7 +41,8 @@ extension _PklDecoder { codingPath: codingPath, debugDescription: "Expected second object property slot to be a string, but got \(parts[1].debugDataTypeDescription)" - )) + ) + ) } } else { throw DecodingError.dataCorrupted( @@ -48,14 +50,15 @@ extension _PklDecoder { codingPath: codingPath, debugDescription: "Expected object member to be an array, but got \(member.debugDataTypeDescription)" - )) + ) + ) } } return result } /// Decoding container specifically for Typed objects. - class PklTypedDecodingContainer: KeyedDecodingContainerProtocol where Key: CodingKey { + class PklTypedDecodingContainer: KeyedDecodingContainerProtocol { let codingPath: [CodingKey] let className: String @@ -75,7 +78,8 @@ extension _PklDecoder { .init( codingPath: codingPath, debugDescription: "Expected 4 items in array, but found \(value.count)" - )) + ) + ) } self.className = try value[1].decode(String.self) self.enclosingModuleURI = try value[2].decode(String.self) @@ -87,7 +91,8 @@ extension _PklDecoder { codingPath: codingPath, debugDescription: "Expected an array of object members at slot 3, but got \(value[3].debugDataTypeDescription)" - )) + ) + ) } self.codingPath = codingPath self.properties = try deriveProperties(self.objectMembers, codingPath: codingPath) @@ -130,8 +135,8 @@ extension _PklDecoder { return try T(from: decoder) } - func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws - -> KeyedDecodingContainer where NestedKey: CodingKey { + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws + -> KeyedDecodingContainer { guard let propertyValue = properties[key.stringValue] else { throw DecodingError.dataCorruptedError( forKey: key, in: self, debugDescription: "Missing key \(key)" diff --git a/Sources/PklSwift/Decoder/PklUnkeyedDecodingContainer.swift b/Sources/PklSwift/Decoder/PklUnkeyedDecodingContainer.swift index 366c9c0..573a5fb 100644 --- a/Sources/PklSwift/Decoder/PklUnkeyedDecodingContainer.swift +++ b/Sources/PklSwift/Decoder/PklUnkeyedDecodingContainer.swift @@ -24,7 +24,7 @@ extension _PklDecoder { var currentIndex: Int - // either [members] or [bytes] are set + /// either [members] or [bytes] are set var members: [MessagePackValue]? var bytes: [UInt8]? @@ -79,12 +79,12 @@ extension _PklDecoder { } } - private func decodeBytes(_: T.Type, _ bytes: [UInt8]) throws -> T where T: Decodable { + private func decodeBytes(_: T.Type, _ bytes: [UInt8]) throws -> T { let value = bytes[self.currentIndex] return value as! T } - func decode(_ type: T.Type) throws -> T where T: Decodable { + func decode(_ type: T.Type) throws -> T { defer { currentIndex += 1 } if let bytes = self.bytes { return try self.decodeBytes(type, bytes) @@ -100,9 +100,9 @@ extension _PklDecoder { return try T(from: _PklDecoder(value: value)) } - func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer< + func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer< NestedKey - > where NestedKey: CodingKey { + > { if self.bytes != nil { throw self.error("Cannot decode byte into \(type) because the decoded value is a byte array.") } diff --git a/Sources/PklSwift/Evaluator.swift b/Sources/PklSwift/Evaluator.swift index 8156353..852be93 100644 --- a/Sources/PklSwift/Evaluator.swift +++ b/Sources/PklSwift/Evaluator.swift @@ -97,8 +97,7 @@ public struct Evaluator: Sendable { /// - type: The type to decode the result as. /// - Returns: A value of type `type`. /// - Throws: ``PklError`` if an error occurs during evaluation, ``DecodingError`` if an the result could not be decoded into ``type``. - public func evaluateModule(source: ModuleSource, as type: T.Type) async throws -> T - where T: Decodable { + public func evaluateModule(source: ModuleSource, as type: T.Type) async throws -> T { try await self.evaluateExpression(source: source, expression: nil, as: type) } @@ -129,8 +128,7 @@ public struct Evaluator: Sendable { /// - type: The type to decode the result as. /// - Returns: The evaluated result as type `type`. /// - Throws: ``PklError`` if an error occurs during evaluation, ``DecodingError`` if the result could not be decoded into ``type``. - public func evaluateOutputValue(source: ModuleSource, asType type: T.Type) async throws -> T - where T: Decodable { + public func evaluateOutputValue(source: ModuleSource, asType type: T.Type) async throws -> T { try await self.evaluateExpression(source: source, expression: "output.value", as: type) } @@ -169,8 +167,8 @@ public struct Evaluator: Sendable { /// - type: The type to decode the result as. /// - Returns: A value of type `type`. /// - Throws: ``PklError`` if an error occurs during evaluation, ``DecodingError`` if the result could not be decoded into ``type``. - public func evaluateExpression(source: ModuleSource, expression: String?, as type: T.Type) - async throws -> T where T: Decodable { + public func evaluateExpression(source: ModuleSource, expression: String?, as type: T.Type) + async throws -> T { let bytes = try await evaluateExpressionRaw(source: source, expression: expression) return try PklDecoder.decode(type, from: bytes) } @@ -195,7 +193,8 @@ public struct Evaluator: Sendable { let response = try await manager.ask(request) guard let response = response as? EvaluateResponse else { throw PklBugError.invalidMessageCode( - "Expected EvaluateResponse, but got \(type(of: response))") + "Expected EvaluateResponse, but got \(type(of: response))" + ) } if let error = response.error { throw PklError(error) diff --git a/Sources/PklSwift/EvaluatorManager.swift b/Sources/PklSwift/EvaluatorManager.swift index 8871e23..d322da3 100644 --- a/Sources/PklSwift/EvaluatorManager.swift +++ b/Sources/PklSwift/EvaluatorManager.swift @@ -110,7 +110,7 @@ public actor EvaluatorManager { var pklVersion: String? - // note; when our C bindings are released, change `init()` based on compiler flags. + /// note; when our C bindings are released, change `init()` based on compiler flags. public init() { #if os(macOS) || os(Linux) || os(Windows) self.init(transport: ServerMessageTransport()) @@ -119,7 +119,7 @@ public actor EvaluatorManager { #endif } - // Used for testing only. + /// Used for testing only. init(transport: MessageTransport) { self.transport = transport Task { @@ -134,7 +134,8 @@ public actor EvaluatorManager { // idempotent — the isClosed guard makes this a no-op when // close() was already called. await self.closeError( - error: PklError("pkl server process exited unexpectedly")) + error: PklError("pkl server process exited unexpectedly") + ) } } @@ -314,7 +315,8 @@ public actor EvaluatorManager { let req = options.toMessage() guard let response = try await ask(req) as? CreateEvaluatorResponse else { throw PklBugError.invalidMessageCode( - "Received invalid response to create evaluator request") + "Received invalid response to create evaluator request" + ) } if let error = response.error { throw PklError(error) @@ -334,7 +336,7 @@ public actor EvaluatorManager { /// Creates a new evaluator that is configured from the provided project. /// /// `options` is the base set of evaluator options. - // Any `evaluatorSettings` set within the PklProject file overwrites any fields set on `options`. + /// Any `evaluatorSettings` set within the PklProject file overwrites any fields set on `options`. /// /// - Parameters: /// - projectBaseURI: The project base path containing the `PklProject` file. diff --git a/Sources/PklSwift/Logger.swift b/Sources/PklSwift/Logger.swift index f3cf9b1..873093e 100644 --- a/Sources/PklSwift/Logger.swift +++ b/Sources/PklSwift/Logger.swift @@ -74,11 +74,17 @@ public struct FileHandleLogger: Logger, Sendable { public enum Loggers { /// A logger that writes everything to stdout. - public static var standardOutput: Logger { FileHandleLogger(.standardOutput) } + public static var standardOutput: Logger { + FileHandleLogger(.standardOutput) + } /// A logger that writes everything to stderr. - public static var standardError: Logger { FileHandleLogger(.standardError) } + public static var standardError: Logger { + FileHandleLogger(.standardError) + } /// A logger that discards log messages. - public static var noop: Logger { NoopLogger() } + public static var noop: Logger { + NoopLogger() + } } diff --git a/Sources/PklSwift/Message.swift b/Sources/PklSwift/Message.swift index f7b704b..3092b65 100644 --- a/Sources/PklSwift/Message.swift +++ b/Sources/PklSwift/Message.swift @@ -45,20 +45,20 @@ protocol ServerResponseMessage: ServerMessage, ResponseMessage {} protocol ServerOneWayMessage: ServerMessage, OneWayMessage {} -struct ModuleReaderSpec: Codable, Sendable { +struct ModuleReaderSpec: Codable { let scheme: String let hasHierarchicalUris: Bool let isLocal: Bool let isGlobbable: Bool } -struct ResourceReaderSpec: Codable, Sendable { +struct ResourceReaderSpec: Codable { let scheme: String let hasHierarchicalUris: Bool let isGlobbable: Bool } -enum MessageType: Int, Codable, Sendable { +enum MessageType: Int, Codable { case CREATE_EVALUATOR_REQUEST = 0x20 case CREATE_EVALUATOR_RESPONSE = 0x21 case CLOSE_EVALUATOR = 0x22 @@ -123,7 +123,7 @@ extension MessageType { } } -struct CreateEvaluatorRequest: ClientRequestMessage, Sendable { +struct CreateEvaluatorRequest: ClientRequestMessage { var requestId: Int64 = 0 var allowedModules: [String]? var allowedResources: [String]? @@ -143,7 +143,7 @@ struct CreateEvaluatorRequest: ClientRequestMessage, Sendable { var traceMode: String? } -struct ProjectOrDependency: Codable, Sendable { +struct ProjectOrDependency: Codable { var packageUri: String? var type: String var projectFileUri: String? @@ -151,78 +151,78 @@ struct ProjectOrDependency: Codable, Sendable { var dependencies: [String: ProjectOrDependency]? } -struct Checksums: Codable, Hashable, Sendable { +struct Checksums: Codable, Hashable { var sha256: String? } -struct CreateEvaluatorResponse: ServerResponseMessage, Sendable { +struct CreateEvaluatorResponse: ServerResponseMessage { let requestId: Int64 let evaluatorId: Int64? let error: String? } -struct ReadResourceRequest: ServerRequestMessage, Sendable { +struct ReadResourceRequest: ServerRequestMessage { var requestId: Int64 let evaluatorId: Int64 let uri: URL } -struct ReadResourceResponse: ClientResponseMessage, Sendable { +struct ReadResourceResponse: ClientResponseMessage { var requestId: Int64 var evaluatorId: Int64 var contents: [UInt8]? var error: String? } -struct ReadModuleRequest: ServerRequestMessage, Sendable { +struct ReadModuleRequest: ServerRequestMessage { var requestId: Int64 let evaluatorId: Int64 let uri: URL } -struct ReadModuleResponse: ClientResponseMessage, Sendable { +struct ReadModuleResponse: ClientResponseMessage { var requestId: Int64 var evaluatorId: Int64 var contents: String? var error: String? } -struct ListResourcesRequest: ServerRequestMessage, Sendable { +struct ListResourcesRequest: ServerRequestMessage { var requestId: Int64 var evaluatorId: Int64 var uri: URL } -struct ListResourcesResponse: ClientResponseMessage, Sendable { +struct ListResourcesResponse: ClientResponseMessage { var requestId: Int64 var evaluatorId: Int64 var pathElements: [PathElementMessage]? var error: String? } -struct PathElementMessage: Codable, Sendable { +struct PathElementMessage: Codable { var name: String var isDirectory: Bool } -struct ListModulesRequest: ServerRequestMessage, Sendable { +struct ListModulesRequest: ServerRequestMessage { var requestId: Int64 var evaluatorId: Int64 var uri: URL } -struct ListModulesResponse: ClientResponseMessage, Sendable { +struct ListModulesResponse: ClientResponseMessage { var requestId: Int64 var evaluatorId: Int64 var pathElements: [PathElementMessage]? var error: String? } -struct CloseEvaluatorRequest: ClientOneWayMessage, Sendable { +struct CloseEvaluatorRequest: ClientOneWayMessage { var evaluatorId: Int64 } -struct EvaluateRequest: ClientRequestMessage, Sendable { +struct EvaluateRequest: ClientRequestMessage { var requestId: Int64 var evaluatorId: Int64 var moduleUri: URL @@ -230,44 +230,44 @@ struct EvaluateRequest: ClientRequestMessage, Sendable { var expr: String? } -struct EvaluateResponse: ServerResponseMessage, Sendable { +struct EvaluateResponse: ServerResponseMessage { let requestId: Int64 let evaluatorId: Int64 let result: [UInt8]? let error: String? } -enum LogLevel: Int, Codable, Sendable { +enum LogLevel: Int, Codable { case trace = 0 case warn = 1 } -struct LogMessage: ServerOneWayMessage, Sendable { +struct LogMessage: ServerOneWayMessage { let evaluatorId: Int64 let level: LogLevel let message: String - // NOTE: not guaranteed to conform to URL. This might have been transformed by a stack frame transformer. + /// NOTE: not guaranteed to conform to URL. This might have been transformed by a stack frame transformer. let frameUri: String } -struct InitializeModuleReaderRequest: ServerRequestMessage, Sendable { +struct InitializeModuleReaderRequest: ServerRequestMessage { var requestId: Int64 let scheme: String } -struct InitializeModuleReaderResponse: ClientResponseMessage, Sendable { +struct InitializeModuleReaderResponse: ClientResponseMessage { var requestId: Int64 var spec: ModuleReaderSpec? } -struct InitializeResourceReaderRequest: ServerRequestMessage, Sendable { +struct InitializeResourceReaderRequest: ServerRequestMessage { var requestId: Int64 let scheme: String } -struct InitializeResourceReaderResponse: ClientResponseMessage, Sendable { +struct InitializeResourceReaderResponse: ClientResponseMessage { var requestId: Int64 var spec: ResourceReaderSpec? } -struct CloseExternalProcess: ServerOneWayMessage, Sendable {} +struct CloseExternalProcess: ServerOneWayMessage {} diff --git a/Sources/PklSwift/MessageTransport.swift b/Sources/PklSwift/MessageTransport.swift index 1592c02..a4d60d1 100644 --- a/Sources/PklSwift/MessageTransport.swift +++ b/Sources/PklSwift/MessageTransport.swift @@ -83,7 +83,9 @@ public class BaseMessageTransport: MessageTransport, @unchecked Sendable { var encoder: MessagePackEncoder! var decoder: MessagePackDecoder! - var running: Bool { true } + var running: Bool { + true + } func send(_ message: ClientMessage) throws { debug("Sending message: \(message)") @@ -125,7 +127,8 @@ public class BaseMessageTransport: MessageTransport, @unchecked Sendable { let arrayLength = try self.decoder.decodeArrayLength() guard arrayLength == 2 else { throw PklBugError.invalidMessageCode( - "Expected 2-element message array, got \(arrayLength)") + "Expected 2-element message array, got \(arrayLength)" + ) } let code = try self.decoder.decode(as: MessageType.self) let message = try self.decodeMessage(code) @@ -142,7 +145,7 @@ public class BaseMessageTransport: MessageTransport, @unchecked Sendable { } } -/// A ``MessageTransport`` that sends and receives messages by spawning Pkl as a child process. +// A ``MessageTransport`` that sends and receives messages by spawning Pkl as a child process. #if os(macOS) || os(Linux) || os(Windows) public class ServerMessageTransport: BaseMessageTransport, @unchecked Sendable { var process: Process? @@ -150,7 +153,9 @@ public class ServerMessageTransport: BaseMessageTransport, @unchecked Sendable { private let processTerminationGroup = DispatchGroup() - override var running: Bool { self.process?.isRunning == true } + override var running: Bool { + self.process?.isRunning == true + } override convenience init() { self.init(pklCommand: nil) @@ -225,7 +230,10 @@ public class ServerMessageTransport: BaseMessageTransport, @unchecked Sendable { #endif public class ExternalReaderMessageTransport: BaseMessageTransport, @unchecked Sendable { - override var running: Bool { self._running } + override var running: Bool { + self._running + } + private var _running = true init(reader: Reader, writer: Writer) { diff --git a/Sources/PklSwift/ModuleSource.swift b/Sources/PklSwift/ModuleSource.swift index 57e63bb..d2087ae 100644 --- a/Sources/PklSwift/ModuleSource.swift +++ b/Sources/PklSwift/ModuleSource.swift @@ -1,5 +1,5 @@ //===----------------------------------------------------------------------===// -// Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved. +// Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,8 +23,8 @@ public struct ModuleSource: Hashable, Sendable { /// The text contents of the module, if available. /// - // If `nil`, gets resolved by Pkl during evaluation time. - // If the scheme of the uri matches a ``ModuleReader``, it will be used to resolve the module. + /// If `nil`, gets resolved by Pkl during evaluation time. + /// If the scheme of the uri matches a ``ModuleReader``, it will be used to resolve the module. let text: String? } diff --git a/Sources/PklSwift/TypeRegistry.swift b/Sources/PklSwift/TypeRegistry.swift index fb3c3f9..32d0643 100644 --- a/Sources/PklSwift/TypeRegistry.swift +++ b/Sources/PklSwift/TypeRegistry.swift @@ -119,7 +119,7 @@ extension TypeRegistry { static let _sharedLock: PklLock = .init() nonisolated(unsafe) static var _shared: TypeRegistry? - public static func get() -> TypeRegistry { + static func get() -> TypeRegistry { self._sharedLock.withLock { if let _shared { return _shared diff --git a/Sources/PklSwift/locks.swift b/Sources/PklSwift/locks.swift index c551744..1bc168b 100644 --- a/Sources/PklSwift/locks.swift +++ b/Sources/PklSwift/locks.swift @@ -1,5 +1,5 @@ //===----------------------------------------------------------------------===// -// Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved. +// Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -115,34 +115,34 @@ extension LockOperations { } } -// Tail allocate both the mutex and a generic value using ManagedBuffer. -// Both the header pointer and the elements pointer are stable for -// the class's entire lifetime. -// -// However, for safety reasons, we elect to place the lock in the "elements" -// section of the buffer instead of the head. The reasoning here is subtle, -// so buckle in. -// -// _As a practical matter_, the implementation of ManagedBuffer ensures that -// the pointer to the header is stable across the lifetime of the class, and so -// each time you call `withUnsafeMutablePointers` or `withUnsafeMutablePointerToHeader` -// the value of the header pointer will be the same. This is because ManagedBuffer uses -// `Builtin.addressOf` to load the value of the header, and that does ~magic~ to ensure -// that it does not invoke any weird Swift accessors that might copy the value. -// -// _However_, the header is also available via the `.header` field on the ManagedBuffer. -// This presents a problem! The reason there's an issue is that `Builtin.addressOf` and friends -// do not interact with Swift's exclusivity model. That is, the various `with` functions do not -// conceptually trigger a mutating access to `.header`. For elements this isn't a concern because -// there's literally no other way to perform the access, but for `.header` it's entirely possible -// to accidentally recursively read it. -// -// Our implementation is free from these issues, so we don't _really_ need to worry about it. -// However, out of an abundance of caution, we store the Value in the header, and the LockPrimitive -// in the trailing elements. We still don't use `.header`, but it's better to be safe than sorry, -// and future maintainers will be happier that we were cautious. -// -// See also: https://github.com/apple/swift/pull/40000 +/// Tail allocate both the mutex and a generic value using ManagedBuffer. +/// Both the header pointer and the elements pointer are stable for +/// the class's entire lifetime. +/// +/// However, for safety reasons, we elect to place the lock in the "elements" +/// section of the buffer instead of the head. The reasoning here is subtle, +/// so buckle in. +/// +/// _As a practical matter_, the implementation of ManagedBuffer ensures that +/// the pointer to the header is stable across the lifetime of the class, and so +/// each time you call `withUnsafeMutablePointers` or `withUnsafeMutablePointerToHeader` +/// the value of the header pointer will be the same. This is because ManagedBuffer uses +/// `Builtin.addressOf` to load the value of the header, and that does ~magic~ to ensure +/// that it does not invoke any weird Swift accessors that might copy the value. +/// +/// _However_, the header is also available via the `.header` field on the ManagedBuffer. +/// This presents a problem! The reason there's an issue is that `Builtin.addressOf` and friends +/// do not interact with Swift's exclusivity model. That is, the various `with` functions do not +/// conceptually trigger a mutating access to `.header`. For elements this isn't a concern because +/// there's literally no other way to perform the access, but for `.header` it's entirely possible +/// to accidentally recursively read it. +/// +/// Our implementation is free from these issues, so we don't _really_ need to worry about it. +/// However, out of an abundance of caution, we store the Value in the header, and the LockPrimitive +/// in the trailing elements. We still don't use `.header`, but it's better to be safe than sorry, +/// and future maintainers will be happier that we were cautious. +/// +/// See also: https://github.com/apple/swift/pull/40000 @usableFromInline final class LockStorage: ManagedBuffer { @inlinable diff --git a/Sources/test-external-reader/TestExternalReader.swift b/Sources/test-external-reader/TestExternalReader.swift index b12fb7e..652d1b9 100644 --- a/Sources/test-external-reader/TestExternalReader.swift +++ b/Sources/test-external-reader/TestExternalReader.swift @@ -23,16 +23,29 @@ struct TestExternalReader { let client = ExternalReaderClient( options: ExternalReaderClientOptions( resourceReaders: [FibReader()] - )) + ) + ) try await client.run() } } struct FibReader: ResourceReader { - var scheme: String { "fib" } - var isGlobbable: Bool { false } - var hasHierarchicalUris: Bool { false } - func listElements(uri: URL) async throws -> [PathElement] { throw PklError("not implemented") } + var scheme: String { + "fib" + } + + var isGlobbable: Bool { + false + } + + var hasHierarchicalUris: Bool { + false + } + + func listElements(uri: URL) async throws -> [PathElement] { + throw PklError("not implemented") + } + func read(url: URL) async throws -> [UInt8]? { let key = url.absoluteString.dropFirst(self.scheme.count + 1) guard let n = Int(key) else { diff --git a/Tests/PklMessagePackTests/MessagePackDecodingTests.swift b/Tests/PklMessagePackTests/MessagePackDecodingTests.swift index 8347bd3..d5f6c14 100644 --- a/Tests/PklMessagePackTests/MessagePackDecodingTests.swift +++ b/Tests/PklMessagePackTests/MessagePackDecodingTests.swift @@ -14,9 +14,8 @@ // limitations under the License. //===----------------------------------------------------------------------===// -import XCTest - @testable import PklMessagePack +import XCTest struct Person: Codable, Hashable { let name: String @@ -25,7 +24,7 @@ struct Person: Codable, Hashable { } class MessagePackDecodingTests: XCTestCase { - private func decode(_ type: T.Type, from bytes: [UInt8]) throws -> T where T: Decodable { + private func decode(_ type: T.Type, from bytes: [UInt8]) throws -> T { let decoder = MessagePackDecoder(reader: BufferReader(bytes)) return try decoder.decode(as: type) } @@ -221,10 +220,10 @@ class MessagePackDecodingTests: XCTestCase { func testDecodeDictionaryWithNonKeyString() throws { let writer = BufferWriter() let dict: [Person: Bool] = [Person(name: "Jerry", age: 11, hobby: nil): true] - try MessagePackEncoder(writer: writer).encode([Person(name: "Jerry", age: 11, hobby: nil): true] - ) + try MessagePackEncoder(writer: writer).encode([Person(name: "Jerry", age: 11, hobby: nil): true]) let decoded = try MessagePackDecoder(reader: BufferReader(writer.bytes)).decode( - as: [Person: Bool].self) + as: [Person: Bool].self + ) XCTAssertEqual(dict, decoded) } diff --git a/Tests/PklMessagePackTests/MessagePackEncodingTests.swift b/Tests/PklMessagePackTests/MessagePackEncodingTests.swift index 6c973d6..7ade599 100644 --- a/Tests/PklMessagePackTests/MessagePackEncodingTests.swift +++ b/Tests/PklMessagePackTests/MessagePackEncodingTests.swift @@ -14,9 +14,8 @@ // limitations under the License. //===----------------------------------------------------------------------===// -import XCTest - @testable import PklMessagePack +import XCTest final class MessagePackEncodingTests: XCTestCase { var writer: BufferWriter? diff --git a/Tests/PklSwiftTests/API/DataSizeTests.swift b/Tests/PklSwiftTests/API/DataSizeTests.swift index fb49da0..ad5083d 100644 --- a/Tests/PklSwiftTests/API/DataSizeTests.swift +++ b/Tests/PklSwiftTests/API/DataSizeTests.swift @@ -1,5 +1,5 @@ //===----------------------------------------------------------------------===// -// Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved. +// Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,9 +14,8 @@ // limitations under the License. //===----------------------------------------------------------------------===// -import XCTest - @testable import PklSwift +import XCTest class DataSizeTests: XCTestCase { func testStringify() { diff --git a/Tests/PklSwiftTests/Decoder/PklDecoderTest.swift b/Tests/PklSwiftTests/Decoder/PklDecoderTest.swift index 32fad21..f371736 100644 --- a/Tests/PklSwiftTests/Decoder/PklDecoderTest.swift +++ b/Tests/PklSwiftTests/Decoder/PklDecoderTest.swift @@ -1,5 +1,5 @@ //===----------------------------------------------------------------------===// -// Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved. +// Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,9 +14,8 @@ // limitations under the License. //===----------------------------------------------------------------------===// -import XCTest - @testable import PklSwift +import XCTest final class PklDecoderTests: XCTestCase { func testDecodeNil() throws { diff --git a/Tests/PklSwiftTests/EvaluatorManagerTest.swift b/Tests/PklSwiftTests/EvaluatorManagerTest.swift index 85bfa2b..0a04e6f 100644 --- a/Tests/PklSwiftTests/EvaluatorManagerTest.swift +++ b/Tests/PklSwiftTests/EvaluatorManagerTest.swift @@ -1,5 +1,5 @@ //===----------------------------------------------------------------------===// -// Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved. +// Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,11 +14,10 @@ // limitations under the License. //===----------------------------------------------------------------------===// +@testable import PklSwift import SemanticVersion import XCTest -@testable import PklSwift - class FakeMessageTransport: MessageTransport, @unchecked Sendable { var outboundStream: AsyncThrowingStream! diff --git a/Tests/PklSwiftTests/ExternalReaderClientTest.swift b/Tests/PklSwiftTests/ExternalReaderClientTest.swift index 1af2c57..2bce39a 100644 --- a/Tests/PklSwiftTests/ExternalReaderClientTest.swift +++ b/Tests/PklSwiftTests/ExternalReaderClientTest.swift @@ -14,11 +14,10 @@ // limitations under the License. //===----------------------------------------------------------------------===// +@testable import PklSwift import SemanticVersion import XCTest -@testable import PklSwift - #if os(macOS) || os(Linux) || os(Windows) class ExternalReaderClientTest: XCTestCase { func testE2E() async throws { diff --git a/Tests/PklSwiftTests/MessageTransportTest.swift b/Tests/PklSwiftTests/MessageTransportTest.swift index fbcff2b..05621c9 100644 --- a/Tests/PklSwiftTests/MessageTransportTest.swift +++ b/Tests/PklSwiftTests/MessageTransportTest.swift @@ -15,10 +15,9 @@ //===----------------------------------------------------------------------===// import Foundation -import XCTest - @testable import PklMessagePack @testable import PklSwift +import XCTest /// Tests for pipe partial-read handling in ``MessageTransport``. /// @@ -118,14 +117,16 @@ class MessageTransportTest: XCTestCase { try encoder.encode(MessageType.READ_MODULE_REQUEST) try encoder.encode( ReadModuleRequest(requestId: 1, evaluatorId: 42, - uri: URL(string: "file:///test.pkl")!)) + uri: URL(string: "file:///test.pkl")!) + ) // Write a malformed 3-element array header. try encoder.encodeArrayHeader(3) try encoder.encode(MessageType.READ_MODULE_REQUEST) try encoder.encode( ReadModuleRequest(requestId: 2, evaluatorId: 43, - uri: URL(string: "file:///test2.pkl")!)) + uri: URL(string: "file:///test2.pkl")!) + ) try encoder.encode("extra element") let reader = BufferReader(bufWriter.bytes) @@ -162,5 +163,7 @@ class MessageTransportTest: XCTestCase { /// concurrency boundaries in tests. private final class UnsafeSendableBox: @unchecked Sendable { var value: T - init(_ value: T) { self.value = value } + init(_ value: T) { + self.value = value + } } diff --git a/Tests/PklSwiftTests/ProjectTest.swift b/Tests/PklSwiftTests/ProjectTest.swift index 8a34bc0..6c849f6 100644 --- a/Tests/PklSwiftTests/ProjectTest.swift +++ b/Tests/PklSwiftTests/ProjectTest.swift @@ -1,5 +1,5 @@ //===----------------------------------------------------------------------===// -// Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved. +// Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,11 +14,10 @@ // limitations under the License. //===----------------------------------------------------------------------===// +@testable import PklSwift import SemanticVersion import XCTest -@testable import PklSwift - #if os(macOS) || os(Linux) || os(Windows) class ProjectTest: XCTestCase { func testLoadProject() async throws {