diff --git a/Sources/JMESPath/Array.swift b/Sources/JMESPath/Array.swift new file mode 100644 index 0000000..c5e20ea --- /dev/null +++ b/Sources/JMESPath/Array.swift @@ -0,0 +1,26 @@ +/// Array storage for JMES +typealias JMESArray = [Any] + +extension JMESArray { + /// return if arrays are equal by converting entries to `JMESVariable` + func equalTo(_ rhs: JMESArray) -> Bool { + guard self.count == rhs.count else { return false } + for i in 0.. Int { + if index >= 0 { + return index + } else { + return count + index + } + } +} diff --git a/Sources/JMESPath/Ast.swift b/Sources/JMESPath/Ast.swift index a3b50b9..c495f2e 100644 --- a/Sources/JMESPath/Ast.swift +++ b/Sources/JMESPath/Ast.swift @@ -1,5 +1,5 @@ /// JMES expression abstract syntax tree -public indirect enum Ast: Equatable { +indirect enum Ast: Equatable { /// compares two nodes using a comparator case comparison(comparator: Comparator, lhs: Ast, rhs: Ast) /// if `predicate` evaluates to a truthy value returns result from `then` @@ -39,7 +39,7 @@ public indirect enum Ast: Equatable { } /// Comparator used in comparison AST nodes -public enum Comparator: Equatable, JMESSendable { +public enum Comparator: Equatable, Sendable { case equal case notEqual case lessThan @@ -66,4 +66,4 @@ public enum Comparator: Equatable, JMESSendable { // have to force Sendable conformance as enum `.literal` uses `JMESVariable` which // is not necessarily sendable but in the use here it is extension Ast: @unchecked Sendable {} -#endif \ No newline at end of file +#endif diff --git a/Sources/JMESPath/Expression.swift b/Sources/JMESPath/Expression.swift index 43141ef..1510127 100644 --- a/Sources/JMESPath/Expression.swift +++ b/Sources/JMESPath/Expression.swift @@ -1,9 +1,13 @@ +#if canImport(FoundationEssentials) +import FoundationEssentials +#else import Foundation +#endif /// JMES Expression /// /// Holds a compiled JMES expression and allows you to search Json text or a type already in memory -public struct JMESExpression: JMESSendable { +public struct JMESExpression: Sendable { let ast: Ast public static func compile(_ text: String) throws -> Self { @@ -22,8 +26,12 @@ public struct JMESExpression: JMESSendable { /// - runtime: JMES runtime (includes functions) /// - Throws: JMESPathError /// - Returns: Search result - public func search(json: Data, as: Value.Type = Value.self, runtime: JMESRuntime = .init()) throws -> Value? { - try self.search(json: json, runtime: runtime) as? Value + public func search(json: String, as: Value.Type = Value.self, runtime: JMESRuntime = .init()) throws -> Value { + let searchResult = try self.search(json: json, runtime: runtime) + guard let value = searchResult as? Value else { + throw JMESPathError.runtime("Expected \(Value.self)) but got a \(type(of: searchResult))") + } + return value } /// Search JSON @@ -34,8 +42,12 @@ public struct JMESExpression: JMESSendable { /// - runtime: JMES runtime (includes functions) /// - Throws: JMESPathError /// - Returns: Search result - public func search(json: String, as: Value.Type = Value.self, runtime: JMESRuntime = .init()) throws -> Value? { - try self.search(json: json, runtime: runtime) as? Value + public func search(json: some ContiguousBytes, as: Value.Type = Value.self, runtime: JMESRuntime = .init()) throws -> Value { + let searchResult = try self.search(json: json, runtime: runtime) + guard let value = searchResult as? Value else { + throw JMESPathError.runtime("Expected \(Value.self)) but got a \(type(of: searchResult))") + } + return value } /// Search Swift type @@ -46,9 +58,12 @@ public struct JMESExpression: JMESSendable { /// - runtime: JMES runtime (includes functions) /// - Throws: JMESPathError /// - Returns: Search result - public func search(object: Any, as: Value.Type = Value.self, runtime: JMESRuntime = .init()) throws -> Value? { - let value = try self.search(object: object, runtime: runtime) - return value as? Value + public func search(object: Any, as: Value.Type = Value.self, runtime: JMESRuntime = .init()) throws -> Value { + let searchResult = try self.search(object: object, runtime: runtime) + guard let value = searchResult as? Value else { + throw JMESPathError.runtime("Expected \(Value.self)) but got a \(type(of: searchResult))") + } + return value } /// Search JSON @@ -58,9 +73,9 @@ public struct JMESExpression: JMESSendable { /// - runtime: JMES runtime (includes functions) /// - Throws: JMESPathError /// - Returns: Search result - public func search(json: Data, runtime: JMESRuntime = .init()) throws -> Any? { - let value = try JMESVariable.fromJson(json) - return try runtime.interpret(value, ast: self.ast).collapse() + public func search(json: String, runtime: JMESRuntime = .init()) throws -> Any? { + let value = try JMESJSON.parse(json: json) + return try runtime.interpret(JMESVariable(from: value), ast: self.ast).collapse() } /// Search JSON @@ -70,9 +85,9 @@ public struct JMESExpression: JMESSendable { /// - runtime: JMES runtime (includes functions) /// - Throws: JMESPathError /// - Returns: Search result - public func search(json: String, runtime: JMESRuntime = .init()) throws -> Any? { - let value = try JMESVariable.fromJson(json) - return try runtime.interpret(value, ast: self.ast).collapse() + public func search(json: some ContiguousBytes, runtime: JMESRuntime = .init()) throws -> Any? { + let value = try JMESJSON.parse(json: json) + return try runtime.interpret(JMESVariable(from: value), ast: self.ast).collapse() } /// Search Swift type diff --git a/Sources/JMESPath/Functions.swift b/Sources/JMESPath/Functions.swift index 545e1bf..ca75623 100644 --- a/Sources/JMESPath/Functions.swift +++ b/Sources/JMESPath/Functions.swift @@ -1,5 +1,3 @@ -import Foundation - /// Used to validate arguments of a function before it is run public struct FunctionSignature { /// Function argument used in function signature to verify arguments @@ -118,7 +116,7 @@ extension JMESVariable { /// let expression = try Expression.compile(myExpression) /// let result = try expression.search(json: myJson, runtime: runtime) /// ``` -public protocol JMESFunction { +protocol JMESFunction { /// function signature static var signature: FunctionSignature { get } /// Evaluate function @@ -310,7 +308,7 @@ struct MapFunction: JMESFunction { static func evaluate(args: [JMESVariable], runtime: JMESRuntime) throws -> JMESVariable { switch (args[0], args[1]) { case (.expRef(let ast), .array(let array)): - let results = try array.map { try runtime.interpret(JMESVariable(from: $0), ast: ast).collapse() ?? NSNull() } + let results = try array.map { try runtime.interpret(JMESVariable(from: $0), ast: ast).collapse() ?? JMESNull() } return .array(results) default: preconditionFailure() @@ -665,7 +663,7 @@ struct ToArrayFunction: JMESFunction { case .array: return args[0] default: - return .array([args[0].collapse() ?? NSNull()]) + return .array([args[0].collapse() ?? JMESNull()]) } } } diff --git a/Sources/JMESPath/Interpreter.swift b/Sources/JMESPath/Interpreter.swift index 8cf0651..052af8c 100644 --- a/Sources/JMESPath/Interpreter.swift +++ b/Sources/JMESPath/Interpreter.swift @@ -1,5 +1,4 @@ -import Foundation - +/// Extend runtime with intepret function extension JMESRuntime { /// Interpret Ast given object to search /// - Parameters: @@ -78,7 +77,7 @@ extension JMESRuntime { for element in array { let currentResult = try interpret(.init(from: element), ast: rhs) if currentResult != .null { - collected.append(currentResult.collapse() ?? NSNull()) + collected.append(currentResult.collapse() ?? JMESNull()) } } return .array(collected) @@ -108,7 +107,7 @@ extension JMESRuntime { } var collected: JMESArray = [] for node in elements { - collected.append(try self.interpret(data, ast: node).collapse() ?? NSNull()) + collected.append(try self.interpret(data, ast: node).collapse() ?? JMESNull()) } return .array(collected) @@ -119,7 +118,7 @@ extension JMESRuntime { var collected: JMESObject = [:] for element in elements { let valueResult = try self.interpret(data, ast: element.value) - collected[element.key] = valueResult.collapse() ?? NSNull() + collected[element.key] = valueResult.collapse() ?? JMESNull() } return .object(collected) diff --git a/Sources/JMESPath/JSON/BufferView.swift b/Sources/JMESPath/JSON/BufferView.swift new file mode 100644 index 0000000..8cc9a9e --- /dev/null +++ b/Sources/JMESPath/JSON/BufferView.swift @@ -0,0 +1,242 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +struct BufferView { + let start: Index + let count: Int + + private var baseAddress: UnsafePointer { start._rawValue } + + init(_unchecked components: (start: Index, count: Int)) { + (start, count) = components + } + + init(start index: Index, count: Int) { + precondition(count >= 0, "Count must not be negative") + self.init(_unchecked: (index, count)) + } + + init(unsafeBaseAddress: UnsafePointer, count: Int) { + self.init(start: .init(rawValue: unsafeBaseAddress), count: count) + } + + init?(unsafeBufferPointer buffer: UnsafeBufferPointer) { + guard let baseAddress = buffer.baseAddress else { return nil } + self.init(unsafeBaseAddress: baseAddress, count: buffer.count) + } +} + +extension BufferView: Sequence { + typealias Element = UInt8 + + func makeIterator() -> Iterator { + Iterator(from: self.start, to: self.start.advanced(by: self.count)) + } +} + +extension BufferView: Collection { + typealias SubSequence = Self + + @inline(__always) + var startIndex: Index { start } + + @inline(__always) + var endIndex: Index { start.advanced(by: count) } + + @inline(__always) + var indices: Range { + .init(uncheckedBounds: (startIndex, endIndex)) + } + + @inline(__always) + func _checkBounds(_ position: Index) { + precondition( + distance(from: startIndex, to: position) >= 0 + && distance(from: position, to: endIndex) > 0, + "Index out of bounds" + ) + } + + @inline(__always) + func _assertBounds(_ position: Index) { + #if DEBUG + _checkBounds(position) + #endif + } + + @inline(__always) + func _checkBounds(_ bounds: Range) { + precondition( + distance(from: startIndex, to: bounds.lowerBound) >= 0 + && distance(from: bounds.lowerBound, to: bounds.upperBound) >= 0 + && distance(from: bounds.upperBound, to: endIndex) >= 0, + "Range of indices out of bounds" + ) + } + + @inline(__always) + func _assertBounds(_ bounds: Range) { + #if DEBUG + _checkBounds(bounds) + #endif + } + + @inline(__always) + func index(after i: Index) -> Index { + i.advanced(by: +1) + } + + @inline(__always) + func index(before i: Index) -> Index { + i.advanced(by: -1) + } + + @inline(__always) + func formIndex(after i: inout Index) { + i = index(after: i) + } + + @inline(__always) + func formIndex(before i: inout Index) { + i = index(before: i) + } + + @inline(__always) + func index(_ i: Index, offsetBy distance: Int) -> Index { + i.advanced(by: distance) + } + + @inline(__always) + func formIndex(_ i: inout Index, offsetBy distance: Int) { + i = index(i, offsetBy: distance) + } + + @inline(__always) + func distance(from start: Index, to end: Index) -> Int { + start.distance(to: end) + } + + @inline(__always) + subscript(position: Index) -> Element { + get { + _checkBounds(position) + return self[unchecked: position] + } + } + + @inline(__always) + subscript(unchecked position: Index) -> Element { + get { + position._rawValue.pointee + } + } + + @inline(__always) + subscript(bounds: Range) -> Self { + get { + _checkBounds(bounds) + return self[unchecked: bounds] + } + } + + @inline(__always) + subscript(unchecked bounds: Range) -> Self { + get { BufferView(_unchecked: (bounds.lowerBound, bounds.count)) } + } + + subscript(bounds: some RangeExpression) -> Self { + get { + self[bounds.relative(to: self)] + } + } + + subscript(unchecked bounds: some RangeExpression) -> Self { + get { + self[unchecked: bounds.relative(to: self)] + } + } + + subscript(x: UnboundedRange) -> Self { + get { + self[unchecked: indices] + } + } + +} + +//MARK: integer offset subscripts + +extension BufferView { + + @inline(__always) + subscript(offset offset: Int) -> Element { + get { + precondition(0 <= offset && offset < count) + return self[uncheckedOffset: offset] + } + } + + @inline(__always) + subscript(uncheckedOffset offset: Int) -> Element { + get { + self[unchecked: index(startIndex, offsetBy: offset)] + } + } + + func loadUnaligned( + fromByteOffset offset: Int = 0, + as: T.Type + ) -> T { + guard _isPOD(Element.self) && _isPOD(T.self) else { fatalError() } + _checkBounds( + Range( + uncheckedBounds: ( + .init(rawValue: baseAddress.advanced(by: offset)), + .init(rawValue: baseAddress.advanced(by: offset + MemoryLayout.size)) + ) + ) + ) + return UnsafeRawPointer(baseAddress).loadUnaligned(fromByteOffset: offset, as: T.self) + } + + func loadUnaligned( + from index: Index, + as: T.Type + ) -> T { + let o = distance(from: startIndex, to: index) + return loadUnaligned(fromByteOffset: o, as: T.self) + } + +} + +extension BufferView { + var first: Element? { + startIndex == endIndex ? nil : self[unchecked: startIndex] + } + + var last: Element? { + startIndex == endIndex ? nil : self[unchecked: index(before: endIndex)] + } +} + +extension BufferView { + func withUnsafeRawPointer( + _ body: (_ pointer: UnsafeRawPointer, _ count: Int) throws -> R + ) rethrows -> R { + try body(UnsafeRawPointer(baseAddress), count) + } + func withUnsafePointer( + _ body: (_ pointer: UnsafePointer, _ count: Int) throws -> R + ) rethrows -> R { + try body(baseAddress, count) + } +} diff --git a/Sources/JMESPath/JSON/BufferViewCompatibility.swift b/Sources/JMESPath/JSON/BufferViewCompatibility.swift new file mode 100644 index 0000000..8a3ee11 --- /dev/null +++ b/Sources/JMESPath/JSON/BufferViewCompatibility.swift @@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +#if canImport(FoundationEssentials) +import FoundationEssentials +#else +import Foundation +#endif + +extension String { + static func _tryFromUTF8(_ input: BufferView) -> String? { + input.withUnsafePointer { pointer, capacity in + _tryFromUTF8(.init(start: pointer, count: capacity)) + } + } +} + +extension String { + func withBufferView( + _ body: (BufferView) throws -> ResultType + ) rethrows -> ResultType { + guard + let result = try self.utf8.withContiguousStorageIfAvailable({ bytes in + try body(BufferView(unsafeBufferPointer: bytes)!) + }) + else { + var copy = self + copy.makeContiguousUTF8() + return try copy.withBufferView(body) + } + return result + } +} + +extension Array where Element == UInt8 { + func withBufferView( + _ body: (BufferView) throws -> ResultType + ) rethrows -> ResultType { + try self.withUnsafeBufferPointer { + try body(BufferView(unsafeBufferPointer: $0)!) + } + } +} + +extension ContiguousBytes { + func withBufferView( + _ body: (BufferView) throws -> ResultType + ) rethrows -> ResultType { + try self.withUnsafeBytes { bytes in + try bytes.withMemoryRebound(to: UInt8.self) { + try body(BufferView(unsafeBufferPointer: $0)!) + } + } + } +} + +extension BufferView { + internal func slice(from startOffset: Int, count sliceCount: Int) -> BufferView { + precondition( + startOffset >= 0 && startOffset < count && sliceCount >= 0 + && sliceCount <= count && startOffset &+ sliceCount <= count + ) + return uncheckedSlice(from: startOffset, count: sliceCount) + } + + internal func uncheckedSlice(from startOffset: Int, count sliceCount: Int) -> BufferView { + let address = startIndex.advanced(by: startOffset) + return BufferView(start: address, count: sliceCount) + } + + internal subscript(region: JSONMap.Region) -> BufferView { + slice(from: region.startOffset, count: region.count) + } + + internal subscript(unchecked region: JSONMap.Region) -> BufferView { + uncheckedSlice(from: region.startOffset, count: region.count) + } +} diff --git a/Sources/JMESPath/JSON/BufferViewIndex.swift b/Sources/JMESPath/JSON/BufferViewIndex.swift new file mode 100644 index 0000000..b3929b8 --- /dev/null +++ b/Sources/JMESPath/JSON/BufferViewIndex.swift @@ -0,0 +1,48 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +extension BufferView { + struct Index { + let _rawValue: UnsafePointer + + @inline(__always) + internal init(rawValue: UnsafePointer) { + _rawValue = rawValue + } + } +} + +extension BufferView.Index: Equatable {} +extension BufferView.Index: Hashable {} +extension BufferView.Index: Strideable { + typealias Stride = Int + + @inline(__always) + func distance(to other: Self) -> Int { + _rawValue.distance(to: other._rawValue) + } + + @inline(__always) + func advanced(by n: Int) -> Self { + .init(rawValue: _rawValue.advanced(by: n)) + } +} + +extension BufferView.Index: Comparable { + @inline(__always) + static func < (lhs: Self, rhs: Self) -> Bool { + lhs._rawValue < rhs._rawValue + } +} + +@available(*, unavailable) +extension BufferView.Index: Sendable {} diff --git a/Sources/JMESPath/JSON/BufferViewIterator.swift b/Sources/JMESPath/JSON/BufferViewIterator.swift new file mode 100644 index 0000000..b94b260 --- /dev/null +++ b/Sources/JMESPath/JSON/BufferViewIterator.swift @@ -0,0 +1,45 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +extension BufferView { + struct Iterator: IteratorProtocol { + var curPointer: UnsafePointer + let endPointer: UnsafePointer + + init(startPointer: UnsafePointer, endPointer: UnsafePointer) { + self.curPointer = startPointer + self.endPointer = endPointer + } + + init(from start: Index, to end: Index) { + self.init(startPointer: start._rawValue, endPointer: end._rawValue) + } + + mutating func next() -> UInt8? { + guard curPointer < endPointer else { return nil } + defer { + curPointer = curPointer.advanced(by: MemoryLayout.stride) + } + return curPointer.pointee + } + + func peek() -> UInt8? { + guard curPointer < endPointer else { return nil } + return curPointer.pointee + } + + mutating func advance() { + guard curPointer < endPointer else { return } + curPointer = curPointer.advanced(by: MemoryLayout.stride) + } + } +} diff --git a/Sources/JMESPath/JSON/JSONScanner.swift b/Sources/JMESPath/JSON/JSONScanner.swift new file mode 100644 index 0000000..ed4c36d --- /dev/null +++ b/Sources/JMESPath/JSON/JSONScanner.swift @@ -0,0 +1,1439 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +/* + A JSONMap is created by a JSON scanner to describe the values found in a JSON payload, including their size, location, and contents, without copying any of the non-structural data. It is used by the JSONDecoder, which will fully parse only those values that are required to decode the requested Decodable types. + + To minimize the number of allocations required during scanning, the map's contents are implemented using an array of integers, whose values are a serialization of the JSON payload's full structure. Each type has its own unique marker value, which is followed by zero or more other integers that describe that contents of that type, if any. + + Due to the complexity and additional allocations required to parse JSON string values into Swift Strings or JSON number values into the requested integer or floating-point types, their map contents are captured as lengths of bytes and byte offsets into the input. This allows the full parsing to occur at decode time, or to be skipped if the value is not desired. A partial, imperfect parsing is performed by the scanner, simply "skipping" characters which are valid in their given contexts without interpreting or further validating them relative to the other inputs. This incomplete scanning process does however guarantee that the structure of the JSON input is correctly interpreted. + + The JSONMap representation of JSON arrays and objects is a sequence of integers that is delimited by their starting marker and a shared "collection end" marker. Their contents are nested in between those two markers. To facilitate skipping over unwanted elements of a collection, which is especially useful for JSON objects, the map encodes the offset in the map array to the next object after the end of the collection. + + For instance, a JSON payload such as the following: + + ``` + {"array":[1,2,3],"number":42} + ``` + + will be scanned into a map buffer looking like this: + + ``` + Key: + == Object Marker + == Array Marker + == Simple String (a variant of String that can has no escapes and can be passed directly to a UTF-8 parser) + == Number Marker + == Collection End + (See JSONMap.TypeDescriptor comments below for more details) + + Map offset: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 13, 14, 15 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 + Map contents: [ , 26, 2, , 5, 2, , 19, 3, , 1, 10, , 1, 12, , 1, 14, , , 6, 18, , 2, 26, ] + Description: | -- key2 -- ------------------------- value1 -------------------------- --- key2 --- -- value2 -- + | | | --arr elm 0- --arr elm 0- --arr elm 0- + | > Byte offset from the beginning of the input to the contents of the string + | > Offset to the next entry after this array, which is key2 + > Offset to next entry after this object, which is the endIndex of the array, as this is the top level value + + A Decodable type that wishes only to decode the "number" key of this object as an Int will be able to entirely skip the decoding of the "array" value by doing the following. + 1. Find the type of the value at index 0 (object), and its size at index 2. + 2. Begin parsing keys at index 3. It decodes the string, and finds "array", which is not a match for "number". + 3. Skip the key's value by finding its type (array), and then its nextSiblingOffset index (19) + 4. Parse the next key at index 4. It decodes the string and finds "number", which is a match. + 5. Decode the value by findings its type (number), its length (2) and the byte offset from the beginning of the input (26). + 6. Pass that byte offset + length into the number parser to produce the corresponding Swift Int value. +*/ + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#elseif canImport(WinSDK) +import WinSDK +#elseif canImport(Bionic) +import Bionic +#else +#error("Unsupported platform") +#endif + +internal class JSONMap { + enum TypeDescriptor: Int { + case string // [marker, count, sourceByteOffset] + case number // [marker, count, sourceByteOffset] + case null // [marker] + case `true` // [marker] + case `false` // [marker] + + case object // [marker, nextSiblingOffset, count, , .collectionEnd] + case array // [marker, nextSiblingOffset, count, , .collectionEnd] + case collectionEnd + + case simpleString // [marker, count, sourceByteOffset] + case numberContainingExponent // [marker, count, sourceByteOffset] + + @inline(__always) + var mapMarker: Int { + self.rawValue + } + } + + struct Region { + let startOffset: Int + let count: Int + } + + enum Value { + case string(Region, isSimple: Bool) + case number(Region, containsExponent: Bool) + case bool(Bool) + case null + + case object(Region) + case array(Region) + } + + let mapBuffer: [Int] + var data: (buffer: BufferView, allocation: UnsafePointer?) + + init(mapBuffer: [Int], dataBuffer: BufferView) { + self.mapBuffer = mapBuffer + self.data = (buffer: dataBuffer, allocation: nil) + } + + func copyInBuffer() { + + guard self.data.allocation == nil else { + return + } + + // Allocate an additional byte to ensure we have a trailing NUL byte which is important for cases like a floating point number fragment. + let (p, c) = self.data.buffer.withUnsafePointer { pointer, count -> (UnsafePointer, Int) in + let raw = UnsafeMutablePointer.allocate(capacity: count + 1) + raw.initialize(from: pointer, count: count) + raw[count] = 0 //.storeBytes(of: UInt8.zero, toByteOffset: capacity, as: UInt8.self) + return (.init(raw), count + 1) + } + + self.data = (buffer: .init(unsafeBaseAddress: p, count: c), allocation: p) + } + + @inline(__always) + func withBuffer( + for region: Region, + perform closure: @Sendable (_ jsonBytes: BufferView, _ fullSource: BufferView) throws -> T + ) rethrows -> T { + try closure(self.data.buffer[region], self.data.buffer) + } + + deinit { + if let allocatedPointer = self.data.allocation { + precondition(self.data.buffer.startIndex == BufferView.Index(rawValue: allocatedPointer)) + allocatedPointer.deallocate() + } + } + + func loadValue(at mapOffset: Int) -> Value? { + let marker = mapBuffer[mapOffset] + let type = JSONMap.TypeDescriptor(rawValue: marker) + switch type { + case .string, .simpleString: + let length = mapBuffer[mapOffset + 1] + let dataOffset = mapBuffer[mapOffset + 2] + return .string(.init(startOffset: dataOffset, count: length), isSimple: type == .simpleString) + case .number, .numberContainingExponent: + let length = mapBuffer[mapOffset + 1] + let dataOffset = mapBuffer[mapOffset + 2] + return .number(.init(startOffset: dataOffset, count: length), containsExponent: type == .numberContainingExponent) + case .object: + // Skip the offset to the next sibling value. + let count = mapBuffer[mapOffset + 2] + return .object(.init(startOffset: mapOffset + 3, count: count)) + case .array: + // Skip the offset to the next sibling value. + let count = mapBuffer[mapOffset + 2] + return .array(.init(startOffset: mapOffset + 3, count: count)) + case .null: + return .null + case .true: + return .bool(true) + case .false: + return .bool(false) + case .collectionEnd: + return nil + default: + fatalError("Invalid JSON value type code in mapping: \(marker))") + } + } + + func offset(after previousValueOffset: Int) -> Int { + let marker = mapBuffer[previousValueOffset] + let type = JSONMap.TypeDescriptor(rawValue: marker) + switch type { + case .string, .simpleString, .number, .numberContainingExponent: + return previousValueOffset + 3 // Skip marker, length, and data offset + case .null, .true, .false: + return previousValueOffset + 1 // Skip only the marker. + case .object, .array: + // The collection records the offset to the next sibling. + return mapBuffer[previousValueOffset + 1] + case .collectionEnd: + fatalError("Attempt to find next object past the end of collection at offset \(previousValueOffset))") + default: + fatalError("Invalid JSON value type code in mapping: \(marker))") + } + } + + struct ArrayIterator { + var currentOffset: Int + let map: JSONMap + + mutating func next() -> JSONMap.Value? { + guard let next = peek() else { + return nil + } + advance() + return next + } + + func peek() -> JSONMap.Value? { + guard let next = map.loadValue(at: currentOffset) else { + return nil + } + return next + } + + mutating func advance() { + currentOffset = map.offset(after: currentOffset) + } + } + + func makeArrayIterator(from offset: Int) -> ArrayIterator { + .init(currentOffset: offset, map: self) + } + + struct ObjectIterator { + var currentOffset: Int + let map: JSONMap + + mutating func next() -> (key: JSONMap.Value, value: JSONMap.Value)? { + let keyOffset = currentOffset + guard let key = map.loadValue(at: currentOffset) else { + return nil + } + let valueOffset = map.offset(after: keyOffset) + guard let value = map.loadValue(at: valueOffset) else { + preconditionFailure("JSONMap object constructed incorrectly. No value found for key") + } + currentOffset = map.offset(after: valueOffset) + return (key, value) + } + } + + func makeObjectIterator(from offset: Int) -> ObjectIterator { + .init(currentOffset: offset, map: self) + } +} + +extension JSONMap.Value { + var debugDataTypeDescription: String { + switch self { + case .string: return "a string" + case .number: return "number" + case .bool: return "bool" + case .null: return "null" + case .object: return "a dictionary" + case .array: return "an array" + } + } +} + +internal struct JSONScanner { + let options: Options + var reader: DocumentReader + var depth: Int = 0 + var partialMap = JSONPartialMapData() + + internal struct Options { + var assumesTopLevelDictionary = false + } + + struct JSONPartialMapData { + var mapData: [Int] = [] + var prevMapDataSize = 0 + + mutating func resizeIfNecessary(with reader: DocumentReader) { + let currentCount = mapData.count + if currentCount > 0, currentCount.isMultiple(of: 2048) { + // Time to predict how big these arrays are going to be based on the current rate of consumption per processed bytes. + // total objects = (total bytes / current bytes) * current objects + let totalBytes = reader.bytes.count + let consumedBytes = reader.byteOffset(at: reader.readIndex) + let ratio = (Double(totalBytes) / Double(consumedBytes)) + let totalExpectedMapSize = Int(Double(mapData.count) * ratio) + if prevMapDataSize == 0 || Double(totalExpectedMapSize) / Double(prevMapDataSize) > 1.25 { + mapData.reserveCapacity(totalExpectedMapSize) + prevMapDataSize = totalExpectedMapSize + } + + // print("Ratio is \(ratio). Reserving \(totalExpectedObjects) objects and \(totalExpectedMapSize) scratch space") + } + } + + mutating func recordStartCollection(tagType: JSONMap.TypeDescriptor, with reader: DocumentReader) -> Int { + resizeIfNecessary(with: reader) + + mapData.append(tagType.mapMarker) + + // Reserve space for the next object index and object count. + let startIdx = mapData.count + mapData.append(contentsOf: [0, 0]) + return startIdx + } + + mutating func recordEndCollection(count: Int, atStartOffset startOffset: Int, with reader: DocumentReader) { + resizeIfNecessary(with: reader) + + mapData.append(JSONMap.TypeDescriptor.collectionEnd.rawValue) + + let nextValueOffset = mapData.count + mapData.withUnsafeMutableBufferPointer { + $0[startOffset] = nextValueOffset + $0[startOffset + 1] = count + } + } + + mutating func recordEmptyCollection(tagType: JSONMap.TypeDescriptor, with reader: DocumentReader) { + resizeIfNecessary(with: reader) + + let nextValueOffset = mapData.count + 4 + mapData.append(contentsOf: [tagType.mapMarker, nextValueOffset, 0, JSONMap.TypeDescriptor.collectionEnd.mapMarker]) + } + + mutating func record(tagType: JSONMap.TypeDescriptor, count: Int, dataOffset: Int, with reader: DocumentReader) { + resizeIfNecessary(with: reader) + + mapData.append(contentsOf: [tagType.mapMarker, count, dataOffset]) + } + + mutating func record(tagType: JSONMap.TypeDescriptor, with reader: DocumentReader) { + resizeIfNecessary(with: reader) + + mapData.append(tagType.mapMarker) + } + } + + init(bytes: BufferView, options: Options) { + self.options = options + self.reader = DocumentReader(bytes: bytes) + } + + mutating func scan() throws -> JSONMap { + if options.assumesTopLevelDictionary { + switch try reader.consumeWhitespace(allowingEOF: true) { + case ._openbrace?: + // If we've got the open brace anyway, just do a normal object scan. + try self.scanObject() + default: + try self.scanObject(withoutBraces: true) + } + } else { + try self.scanValue() + } + #if DEBUG + defer { + guard self.depth == 0 else { + preconditionFailure("Expected to end parsing with a depth of 0") + } + } + #endif + + // ensure only white space is remaining + var whitespace = 0 + while let next = reader.peek(offset: whitespace) { + switch next { + case ._space, ._tab, ._return, ._newline: + whitespace += 1 + continue + default: + throw JSONError.unexpectedCharacter( + context: "after top-level value", + ascii: next, + location: reader.sourceLocation(atOffset: whitespace) + ) + } + } + + let map = JSONMap(mapBuffer: partialMap.mapData, dataBuffer: self.reader.bytes) + + // If the input contains only a number, we have to copy the input into a form that is guaranteed to have a trailing NUL byte so that strtod doesn't perform a buffer overrun. + if case .number = map.loadValue(at: 0)! { + map.copyInBuffer() + } + + return map + } + + // MARK: Generic Value Scanning + + mutating func scanValue() throws { + let byte = try reader.consumeWhitespace() + switch byte { + case ._quote: + try scanString() + case ._openbrace: + try scanObject() + case ._openbracket: + try scanArray() + case UInt8(ascii: "f"), UInt8(ascii: "t"): + try scanBool() + case UInt8(ascii: "n"): + try scanNull() + case UInt8(ascii: "-"), _asciiNumbers: + try scanNumber() + case ._space, ._return, ._newline, ._tab: + preconditionFailure("Expected that all white space is consumed") + default: + throw JSONError.unexpectedCharacter(ascii: byte, location: reader.sourceLocation) + } + } + + // MARK: - Scan Array - + + mutating func scanArray() throws { + let firstChar = reader.read() + precondition(firstChar == ._openbracket) + guard self.depth < 512 else { + throw JSONError.tooManyNestedArraysOrDictionaries(location: reader.sourceLocation(atOffset: 1)) + } + self.depth &+= 1 + defer { depth &-= 1 } + + // parse first value or end immediately + switch try reader.consumeWhitespace() { + case ._space, ._return, ._newline, ._tab: + preconditionFailure("Expected that all white space is consumed") + case ._closebracket: + // if the first char after whitespace is a closing bracket, we found an empty array + reader.moveReaderIndex(forwardBy: 1) + return partialMap.recordEmptyCollection(tagType: .array, with: reader) + default: + break + } + + var count = 0 + let startOffset = partialMap.recordStartCollection(tagType: .array, with: reader) + defer { + partialMap.recordEndCollection(count: count, atStartOffset: startOffset, with: reader) + } + + ScanValues: while true { + try scanValue() + count += 1 + + // consume the whitespace after the value before the comma + let ascii = try reader.consumeWhitespace() + switch ascii { + case ._space, ._return, ._newline, ._tab: + preconditionFailure("Expected that all white space is consumed") + case ._closebracket: + reader.moveReaderIndex(forwardBy: 1) + break ScanValues + case ._comma: + // consume the comma + reader.moveReaderIndex(forwardBy: 1) + // consume the whitespace before the next value + if try reader.consumeWhitespace() == ._closebracket { + // the foundation json implementation does support trailing commas + reader.moveReaderIndex(forwardBy: 1) + break ScanValues + } + continue + default: + throw JSONError.unexpectedCharacter(context: "in array", ascii: ascii, location: reader.sourceLocation) + } + } + } + + // MARK: - Scan Object - + + mutating func scanObject() throws { + let firstChar = self.reader.read() + precondition(firstChar == ._openbrace) + guard self.depth < 512 else { + throw JSONError.tooManyNestedArraysOrDictionaries(location: reader.sourceLocation(atOffset: -1)) + } + try scanObject(withoutBraces: false) + } + + @inline(never) + mutating func _scanObjectLoop(withoutBraces: Bool, count: inout Int, done: inout Bool) throws { + try scanString() + + let colon = try reader.consumeWhitespace() + guard colon == ._colon else { + throw JSONError.unexpectedCharacter(context: "in object", ascii: colon, location: reader.sourceLocation) + } + reader.moveReaderIndex(forwardBy: 1) + + try self.scanValue() + count += 2 + + let commaOrBrace = try reader.consumeWhitespace(allowingEOF: withoutBraces) + switch commaOrBrace { + case ._comma?: + reader.moveReaderIndex(forwardBy: 1) + switch try reader.consumeWhitespace(allowingEOF: withoutBraces) { + case ._closebrace?: + if withoutBraces { + throw JSONError.unexpectedCharacter(ascii: ._closebrace, location: reader.sourceLocation) + } + + // the foundation json implementation does support trailing commas + reader.moveReaderIndex(forwardBy: 1) + done = true + case .none: + done = true + default: + return + } + case ._closebrace?: + if withoutBraces { + throw JSONError.unexpectedCharacter(ascii: ._closebrace, location: reader.sourceLocation) + } + reader.moveReaderIndex(forwardBy: 1) + done = true + case .none: + // If withoutBraces was false, then reaching EOF here would have thrown. + precondition(withoutBraces == true) + done = true + + default: + throw JSONError.unexpectedCharacter(context: "in object", ascii: commaOrBrace.unsafelyUnwrapped, location: reader.sourceLocation) + } + } + + mutating func scanObject(withoutBraces: Bool) throws { + self.depth &+= 1 + defer { depth &-= 1 } + + // parse first value or end immediately + switch try reader.consumeWhitespace(allowingEOF: withoutBraces) { + case ._closebrace?: + if withoutBraces { + throw JSONError.unexpectedCharacter(ascii: ._closebrace, location: reader.sourceLocation) + } + + // if the first char after whitespace is a closing bracket, we found an empty object + self.reader.moveReaderIndex(forwardBy: 1) + return partialMap.recordEmptyCollection(tagType: .object, with: reader) + case .none: + // If withoutBraces was false, then reaching EOF here would have thrown. + precondition(withoutBraces == true) + return partialMap.recordEmptyCollection(tagType: .object, with: reader) + default: + break + } + + var count = 0 + let startOffset = partialMap.recordStartCollection(tagType: .object, with: reader) + defer { + partialMap.recordEndCollection(count: count, atStartOffset: startOffset, with: reader) + } + + var done = false + while !done { + try _scanObjectLoop(withoutBraces: withoutBraces, count: &count, done: &done) + } + } + + mutating func scanString() throws { + var isSimple = false + let start = try reader.skipUTF8StringTillNextUnescapedQuote(isSimple: &isSimple) + let end = reader.readIndex + + // skipUTF8StringTillNextUnescapedQuote will have either thrown an error, or already peek'd the quote. + let shouldBePostQuote = reader.read() + precondition(shouldBePostQuote == ._quote) + + // skip initial quote + return partialMap.record( + tagType: isSimple ? .simpleString : .string, + count: reader.distance(from: start, to: end), + dataOffset: reader.byteOffset(at: start), + with: reader + ) + } + + mutating func scanNumber() throws { + let start = reader.readIndex + var containsExponent = false + reader.skipNumber(containsExponent: &containsExponent) + let end = reader.readIndex + return partialMap.record( + tagType: containsExponent ? .numberContainingExponent : .number, + count: reader.distance(from: start, to: end), + dataOffset: reader.byteOffset(at: start), + with: reader + ) + } + + mutating func scanBool() throws { + if try reader.readBool() { + return partialMap.record(tagType: .true, with: reader) + } else { + return partialMap.record(tagType: .false, with: reader) + } + } + + mutating func scanNull() throws { + try reader.readNull() + return partialMap.record(tagType: .null, with: reader) + } + +} + +extension JSONScanner { + + struct DocumentReader { + let bytes: BufferView + private(set) var readIndex: BufferView.Index + private let endIndex: BufferView.Index + + @inline(__always) + func checkRemainingBytes(_ count: Int) -> Bool { + bytes.distance(from: readIndex, to: endIndex) >= count + } + + @inline(__always) + func requireRemainingBytes(_ count: Int) throws { + guard checkRemainingBytes(count) else { + throw JSONError.unexpectedEndOfFile + } + } + + var sourceLocation: JSONError.SourceLocation { + self.sourceLocation(atOffset: 0) + } + + func sourceLocation(atOffset offset: Int) -> JSONError.SourceLocation { + .sourceLocation(at: bytes.index(readIndex, offsetBy: offset), fullSource: bytes) + } + + @inline(__always) + var isEOF: Bool { + readIndex == endIndex + } + + @inline(__always) + func byteOffset(at index: BufferView.Index) -> Int { + bytes.distance(from: bytes.startIndex, to: index) + } + + init(bytes: BufferView) { + self.bytes = bytes + self.readIndex = bytes.startIndex + self.endIndex = bytes.endIndex + } + + @inline(__always) + mutating func read() -> UInt8? { + guard !isEOF else { + return nil + } + + defer { bytes.formIndex(after: &readIndex) } + + return bytes[unchecked: readIndex] + } + + @inline(__always) + func peek(offset: Int = 0) -> UInt8? { + precondition(offset >= 0) + assert(bytes.startIndex <= readIndex) + let peekIndex = bytes.index(readIndex, offsetBy: offset) + guard peekIndex < endIndex else { + return nil + } + + return bytes[unchecked: peekIndex] + } + + @inline(__always) + mutating func moveReaderIndex(forwardBy offset: Int) { + bytes.formIndex(&readIndex, offsetBy: offset) + } + + @inline(__always) + func distance(from start: BufferView.Index, to end: BufferView.Index) -> Int { + bytes.distance(from: start, to: end) + } + + static var whitespaceBitmap: UInt64 { 1 << UInt8._space | 1 << UInt8._return | 1 << UInt8._newline | 1 << UInt8._tab } + + @inline(__always) + @discardableResult + mutating func consumeWhitespace() throws -> UInt8 { + assert(bytes.startIndex <= readIndex) + while readIndex < endIndex { + let ascii = bytes[unchecked: readIndex] + if Self.whitespaceBitmap & (1 << ascii) != 0 { + bytes.formIndex(after: &readIndex) + continue + } else { + return ascii + } + } + + throw JSONError.unexpectedEndOfFile + } + + @inline(__always) + @discardableResult + mutating func consumeWhitespace(allowingEOF: Bool) throws -> UInt8? { + assert(bytes.startIndex <= readIndex) + while readIndex < endIndex { + let ascii = bytes[unchecked: readIndex] + if Self.whitespaceBitmap & (1 << ascii) != 0 { + bytes.formIndex(after: &readIndex) + continue + } else { + return ascii + } + } + guard allowingEOF else { + throw JSONError.unexpectedEndOfFile + } + return nil + } + + @inline(__always) + mutating func readExpectedString(_ str: StaticString, typeDescriptor: String) throws { + let cmp = try bytes[unchecked: readIndex.. Bool { + switch self.read() { + case UInt8(ascii: "t"): + try readExpectedString("rue", typeDescriptor: "boolean") + return true + case UInt8(ascii: "f"): + try readExpectedString("alse", typeDescriptor: "boolean") + return false + default: + preconditionFailure("Expected to have `t` or `f` as first character") + } + } + + @inline(__always) + mutating func readNull() throws { + try readExpectedString("null", typeDescriptor: "null") + } + + // MARK: - Private Methods - + + // MARK: String + + mutating func skipUTF8StringTillQuoteOrBackslashOrInvalidCharacter() throws -> UInt8 { + while let byte = self.peek() { + switch byte { + case ._quote, ._backslash: + return byte + default: + // Any control characters in the 0-31 range are invalid. Any other characters will have at least one bit in a 0xe0 mask. + guard _fastPath(byte & 0xe0 != 0) else { + return byte + } + self.moveReaderIndex(forwardBy: 1) + } + } + throw JSONError.unexpectedEndOfFile + } + + mutating func skipUTF8StringTillNextUnescapedQuote(isSimple: inout Bool) throws -> BufferView.Index { + // Skip the open quote. + guard let shouldBeQuote = self.read() else { + throw JSONError.unexpectedEndOfFile + } + guard shouldBeQuote == ._quote else { + throw JSONError.unexpectedCharacter(ascii: shouldBeQuote, location: sourceLocation) + } + let firstNonQuote = readIndex + + // If there aren't any escapes, then this is a simple case and we can exit early. + if try skipUTF8StringTillQuoteOrBackslashOrInvalidCharacter() == ._quote { + isSimple = true + return firstNonQuote + } + + while let byte = self.peek() { + // Checking for invalid control characters deferred until parse time. + switch byte { + case ._quote: + isSimple = false + return firstNonQuote + case ._backslash: + try skipEscapeSequence() + default: + moveReaderIndex(forwardBy: 1) + continue + } + } + throw JSONError.unexpectedEndOfFile + } + + private mutating func skipEscapeSequence() throws { + let firstChar = self.read() + precondition(firstChar == ._backslash, "Expected to have a backslash first") + + guard let ascii = self.read() else { + throw JSONError.unexpectedEndOfFile + } + + // Invalid escaped characters checking deferred to parse time. + if ascii == UInt8(ascii: "u") { + try skipUnicodeHexSequence() + } + } + + private mutating func skipUnicodeHexSequence() throws { + // As stated in RFC-8259 an escaped unicode character is 4 HEXDIGITs long + // https://tools.ietf.org/html/rfc8259#section-7 + try requireRemainingBytes(4) + + // We'll validate the actual characters following the '\u' escape during parsing. Just make sure that the string doesn't end prematurely. + let hs = bytes.loadUnaligned(from: readIndex, as: UInt32.self) + guard JSONScanner.noByteMatches(UInt8(ascii: "\""), in: hs) else { + let hexString = _withUnprotectedUnsafeBytes(of: hs) { String(decoding: $0, as: UTF8.self) } + throw JSONError.invalidHexDigitSequence(hexString, location: sourceLocation) + } + self.moveReaderIndex(forwardBy: 4) + } + + // MARK: Numbers + + mutating func skipNumber(containsExponent: inout Bool) { + guard let ascii = read() else { + preconditionFailure("Why was this function called, if there is no 0...9 or -") + } + switch ascii { + case _asciiNumbers, UInt8(ascii: "-"): + break + default: + preconditionFailure("Why was this function called, if there is no 0...9 or -") + } + while let byte = peek() { + if _fastPath(_asciiNumbers.contains(byte)) { + moveReaderIndex(forwardBy: 1) + continue + } + switch byte { + case UInt8(ascii: "."), UInt8(ascii: "+"), UInt8(ascii: "-"): + moveReaderIndex(forwardBy: 1) + case UInt8(ascii: "e"), UInt8(ascii: "E"): + moveReaderIndex(forwardBy: 1) + containsExponent = true + default: + return + } + } + } + } + + @inline(__always) + internal static func noByteMatches(_ asciiByte: UInt8, in hexString: UInt32) -> Bool { + assert(asciiByte & 0x80 == 0) + // Copy asciiByte of interest to mask. + let t0 = UInt32(0x0101_0101) &* UInt32(asciiByte) + // xor input and mask, then locate potential matches. + let t1 = ((hexString ^ t0) & 0x7f7f_7f7f) &+ 0x7f7f_7f7f + // Positions with matches are 0x7f. + // Positions with non-matching ascii bytes have their MSB set. + // Positions with non-ascii bytes do not have their MSB set. + // Eliminate non-ascii bytes with a bitwise-or of t1 with the input, + // then select the positions whose MSB is not set. + let t2 = ((hexString | t1) & 0x8080_8080) ^ 0x8080_8080 + // There is no match when no bit is set. + return t2 == 0 + } +} + +// MARK: - Deferred Parsing Methods - + +extension JSONScanner { + + // MARK: String + + static func stringValue( + from jsonBytes: BufferView, + fullSource: BufferView + ) throws -> String { + // Assume easy path first -- no escapes, no characters requiring escapes. + var index = jsonBytes.startIndex + let endIndex = jsonBytes.endIndex + while index < endIndex { + let byte = jsonBytes[unchecked: index] + guard byte != ._backslash && _fastPath(byte & 0xe0 != 0) else { break } + jsonBytes.formIndex(after: &index) + } + + guard var output = String._tryFromUTF8(jsonBytes[unchecked: jsonBytes.startIndex.. BufferView.Index { + precondition(!jsonBytes.isEmpty, "Scanning should have ensured that all escape sequences are valid shape") + switch jsonBytes[unchecked: jsonBytes.startIndex] { + case UInt8(ascii: "\""): string.append("\"") + case UInt8(ascii: "\\"): string.append("\\") + case UInt8(ascii: "/"): string.append("/") + case UInt8(ascii: "b"): string.append("\u{08}") // \b + case UInt8(ascii: "f"): string.append("\u{0C}") // \f + case UInt8(ascii: "n"): string.append("\u{0A}") // \n + case UInt8(ascii: "r"): string.append("\u{0D}") // \r + case UInt8(ascii: "t"): string.append("\u{09}") // \t + case UInt8(ascii: "u"): + return try parseUnicodeSequence(from: jsonBytes.dropFirst(), into: &string, fullSource: fullSource) + case let ascii: // default + throw JSONError.unexpectedEscapedCharacter(ascii: ascii, location: .sourceLocation(at: jsonBytes.startIndex, fullSource: fullSource)) + } + return jsonBytes.index(after: jsonBytes.startIndex) + } + + // Shared with JSON5, which requires allowNulls = false for compatibility. + internal static func parseUnicodeSequence( + from jsonBytes: BufferView, + into string: inout String, + fullSource: BufferView, + allowNulls: Bool = true + ) throws -> BufferView.Index { + // we build this for utf8 only for now. + let (bitPattern, index1) = try parseUnicodeHexSequence(from: jsonBytes, fullSource: fullSource, allowNulls: allowNulls) + + // check if lead surrogate + if UTF16.isLeadSurrogate(bitPattern) { + // if we have a lead surrogate we expect a trailing surrogate next + let leadingSurrogateBitPattern = bitPattern + var trailingBytes = jsonBytes.suffix(from: index1) + guard trailingBytes.count >= 2 else { + throw JSONError.expectedLowSurrogateUTF8SequenceAfterHighSurrogate(location: .sourceLocation(at: index1, fullSource: fullSource)) + } + guard trailingBytes[uncheckedOffset: 0] == ._backslash, + trailingBytes[uncheckedOffset: 1] == UInt8(ascii: "u") + else { + throw JSONError.expectedLowSurrogateUTF8SequenceAfterHighSurrogate(location: .sourceLocation(at: index1, fullSource: fullSource)) + } + trailingBytes = trailingBytes.dropFirst(2) + + let (trailingSurrogateBitPattern, index2) = try parseUnicodeHexSequence(from: trailingBytes, fullSource: fullSource, allowNulls: true) + guard UTF16.isTrailSurrogate(trailingSurrogateBitPattern) else { + throw JSONError.expectedLowSurrogateUTF8SequenceAfterHighSurrogate( + location: .sourceLocation(at: trailingBytes.startIndex, fullSource: fullSource) + ) + } + + let encodedScalar = UTF16.EncodedScalar([leadingSurrogateBitPattern, trailingSurrogateBitPattern]) + let unicode = UTF16.decode(encodedScalar) + string.unicodeScalars.append(unicode) + return index2 + } else { + guard let unicode = Unicode.Scalar(bitPattern) else { + throw JSONError.couldNotCreateUnicodeScalarFromUInt32( + location: .sourceLocation(at: jsonBytes.startIndex, fullSource: fullSource), + unicodeScalarValue: UInt32(bitPattern) + ) + } + string.unicodeScalars.append(unicode) + return index1 + } + } + + internal static func parseUnicodeHexSequence( + from jsonBytes: BufferView, + fullSource: BufferView, + allowNulls: Bool = true + ) throws -> (scalar: UInt16, nextIndex: BufferView.Index) { + let digitBytes = jsonBytes.prefix(4) + precondition(digitBytes.count == 4, "Scanning should have ensured that all escape sequences are valid shape") + + guard let result: UInt16 = _parseHexIntegerDigits(digitBytes, isNegative: false) + else { + let hexString = String(decoding: digitBytes, as: Unicode.UTF8.self) + throw JSONError.invalidHexDigitSequence(hexString, location: .sourceLocation(at: digitBytes.startIndex, fullSource: fullSource)) + } + guard allowNulls || result != 0 else { + throw JSONError.invalidEscapedNullValue(location: .sourceLocation(at: jsonBytes.startIndex, fullSource: fullSource)) + } + assert(digitBytes.endIndex <= jsonBytes.endIndex) + return (result, digitBytes.endIndex) + } + + // MARK: Numbers + + static func validateLeadingZero(in jsonBytes: BufferView, fullSource: BufferView) throws { + // Leading zeros are very restricted. + if jsonBytes.isEmpty { + // Yep, this is valid. + return + } + switch jsonBytes[uncheckedOffset: 0] { + case UInt8(ascii: "."), UInt8(ascii: "e"), UInt8(ascii: "E"): + // This is valid after a leading zero. + return + case _asciiNumbers: + throw JSONError.numberWithLeadingZero(location: .sourceLocation(at: jsonBytes.startIndex, fullSource: fullSource)) + case let byte: // default + throw JSONError.unexpectedCharacter( + context: "in number", + ascii: byte, + location: .sourceLocation(at: jsonBytes.startIndex, fullSource: fullSource) + ) + } + } + + // Returns the pointer at which the number's digits begin. If there are no digits, the function throws. + static func prevalidateJSONNumber( + from jsonBytes: BufferView, + hasExponent: Bool, + fullSource: BufferView + ) throws -> BufferView.Index { + // Just make sure we (A) don't have a leading zero, and (B) We have at least one digit. + guard !jsonBytes.isEmpty else { + preconditionFailure("Why was this function called, if there is no 0...9 or -") + } + let firstDigitIndex: BufferView.Index + switch jsonBytes[uncheckedOffset: 0] { + case UInt8(ascii: "0"): + try validateLeadingZero(in: jsonBytes.dropFirst(1), fullSource: fullSource) + firstDigitIndex = jsonBytes.startIndex + case UInt8(ascii: "1")...UInt8(ascii: "9"): + firstDigitIndex = jsonBytes.startIndex + case UInt8(ascii: "-"): + guard jsonBytes.count > 1 else { + throw JSONError.unexpectedCharacter( + context: "at end of number", + ascii: UInt8(ascii: "-"), + location: .sourceLocation(at: jsonBytes.startIndex, fullSource: fullSource) + ) + } + switch jsonBytes[uncheckedOffset: 1] { + case UInt8(ascii: "0"): + try validateLeadingZero(in: jsonBytes.dropFirst(2), fullSource: fullSource) + case UInt8(ascii: "1")...UInt8(ascii: "9"): + // Good, we need at least one digit following the '-' + break + case let byte: // default + // Any other character is invalid. + throw JSONError.unexpectedCharacter( + context: "after '-' in number", + ascii: byte, + location: .sourceLocation(at: jsonBytes.index(after: jsonBytes.startIndex), fullSource: fullSource) + ) + } + firstDigitIndex = jsonBytes.index(after: jsonBytes.startIndex) + default: + preconditionFailure("Why was this function called, if there is no 0...9 or -") + } + + // If the number was found to have an exponent, we have to guarantee that there are digits preceding it, which is a JSON requirement. If we don't, then our floating point parser, which is tolerant of that construction, will succeed and not produce the required error. + if hasExponent { + var index = jsonBytes.index(after: firstDigitIndex) + exponentLoop: while index < jsonBytes.endIndex { + switch jsonBytes[unchecked: index] { + case UInt8(ascii: "e"), UInt8(ascii: "E"): + let previous = jsonBytes.index(before: index) + guard case _asciiNumbers = jsonBytes[unchecked: previous] else { + throw JSONError.unexpectedCharacter( + context: "in number", + ascii: jsonBytes[index], + location: .sourceLocation(at: index, fullSource: fullSource) + ) + } + // We're done iterating. + break exponentLoop + default: + jsonBytes.formIndex(after: &index) + } + } + } + + let lastIndex = jsonBytes.index(before: jsonBytes.endIndex) + assert(lastIndex >= jsonBytes.startIndex) + switch jsonBytes[unchecked: lastIndex] { + case _asciiNumbers: + break // In JSON, all numbers must end with a digit. + case let lastByte: // default + throw JSONError.unexpectedCharacter( + context: "at end of number", + ascii: lastByte, + location: .sourceLocation(at: lastIndex, fullSource: fullSource) + ) + } + return firstDigitIndex + } + + // This function is intended to be called after prevalidateJSONNumber() (which provides the digitsBeginPtr) and after parsing fails. It will provide more useful information about the invalid input. + static func validateNumber(from jsonBytes: BufferView, fullSource: BufferView) -> JSONError { + enum ControlCharacter { + case operand + case decimalPoint + case exp + case expOperator + } + + var index = jsonBytes.startIndex + let endIndex = jsonBytes.endIndex + // Fast-path, assume all digits. + while index < endIndex { + guard _asciiNumbers.contains(jsonBytes[index]) else { break } + jsonBytes.formIndex(after: &index) + } + + var pastControlChar: ControlCharacter = .operand + var digitsSinceControlChar = jsonBytes.distance(from: jsonBytes.startIndex, to: index) + + // parse everything else + while index < endIndex { + let byte = jsonBytes[index] + switch byte { + case _asciiNumbers: + digitsSinceControlChar += 1 + case UInt8(ascii: "."): + guard digitsSinceControlChar > 0, pastControlChar == .operand else { + return JSONError.unexpectedCharacter( + context: "in number", + ascii: byte, + location: .sourceLocation(at: index, fullSource: fullSource) + ) + } + pastControlChar = .decimalPoint + digitsSinceControlChar = 0 + + case UInt8(ascii: "e"), UInt8(ascii: "E"): + guard digitsSinceControlChar > 0, + pastControlChar == .operand || pastControlChar == .decimalPoint + else { + return JSONError.unexpectedCharacter( + context: "in number", + ascii: byte, + location: .sourceLocation(at: index, fullSource: fullSource) + ) + } + pastControlChar = .exp + digitsSinceControlChar = 0 + + case UInt8(ascii: "+"), UInt8(ascii: "-"): + guard digitsSinceControlChar == 0, pastControlChar == .exp else { + return JSONError.unexpectedCharacter( + context: "in number", + ascii: byte, + location: .sourceLocation(at: index, fullSource: fullSource) + ) + } + pastControlChar = .expOperator + digitsSinceControlChar = 0 + + default: + return JSONError.unexpectedCharacter(context: "in number", ascii: byte, location: .sourceLocation(at: index, fullSource: fullSource)) + } + jsonBytes.formIndex(after: &index) + } + + if digitsSinceControlChar > 0 { + preconditionFailure("Invalid number expected in \(#function). Input code unit buffer contained valid input.") + } else { // prevalidateJSONNumber() already checks for trailing `e`/`E` characters. + preconditionFailure("Found trailing non-digit. Number character buffer was not validated with prevalidateJSONNumber()") + } + } +} + +// Protocol conformed to by the numeric types we parse. For each of them, the +protocol PrevalidatedJSONNumberBufferConvertible { + init?(prevalidatedBuffer buffer: BufferView) +} + +extension Double: PrevalidatedJSONNumberBufferConvertible { + init?(prevalidatedBuffer buffer: BufferView) { + let decodedValue = buffer.withUnsafePointer { nptr, count -> Double? in + var endPtr: UnsafeMutablePointer? = nil + + let decodedValue = strtod(nptr, &endPtr) + if let endPtr, nptr.advanced(by: count) == endPtr { + return decodedValue + } else { + return nil + } + } + guard let decodedValue else { return nil } + self = decodedValue + } +} + +extension Float: PrevalidatedJSONNumberBufferConvertible { + init?(prevalidatedBuffer buffer: BufferView) { + let decodedValue = buffer.withUnsafePointer { nptr, count -> Float? in + var endPtr: UnsafeMutablePointer? = nil + let decodedValue = strtof(nptr, &endPtr) + if let endPtr, nptr.advanced(by: count) == endPtr { + return decodedValue + } else { + return nil + } + } + guard let decodedValue else { return nil } + self = decodedValue + } +} + +internal func _parseInteger(_ codeUnits: BufferView) -> Result? { + guard _fastPath(!codeUnits.isEmpty) else { return nil } + + // ASCII constants, named for clarity: + let _plus = 43 as UInt8 + let _minus = 45 as UInt8 + + let first = codeUnits[uncheckedOffset: 0] + if first == _minus { + return _parseIntegerDigits(codeUnits.dropFirst(), isNegative: true) + } + if first == _plus { + return _parseIntegerDigits(codeUnits.dropFirst(), isNegative: false) + } + return _parseIntegerDigits(codeUnits, isNegative: false) +} + +extension FixedWidthInteger { + init?(prevalidatedBuffer buffer: BufferView) { + guard let val: Self = _parseInteger(buffer) else { + return nil + } + self = val + } +} + +enum JSONError: Swift.Error, Equatable { + struct SourceLocation: Equatable { + let line: Int + let column: Int + let index: Int + + static func sourceLocation( + at location: BufferView.Index, + fullSource: BufferView + ) -> SourceLocation { + precondition(fullSource.startIndex <= location && location <= fullSource.endIndex) + var index = fullSource.startIndex + var line = 1 + var col = 0 + let end = min(location.advanced(by: 1), fullSource.endIndex) + while index < end { + switch fullSource[index] { + case ._return: + let next = fullSource.index(after: index) + if next <= location, fullSource[next] == ._newline { + index = next + } + line += 1 + col = 0 + case ._newline: + line += 1 + col = 0 + default: + col += 1 + } + fullSource.formIndex(after: &index) + } + let offset = fullSource.distance(from: fullSource.startIndex, to: location) + return SourceLocation(line: line, column: col, index: offset) + } + } + + case cannotConvertEntireInputDataToUTF8 + case cannotConvertInputStringDataToUTF8(location: SourceLocation) + case unexpectedCharacter(context: String? = nil, ascii: UInt8, location: SourceLocation) + case unexpectedEndOfFile + case tooManyNestedArraysOrDictionaries(location: SourceLocation? = nil) + case invalidHexDigitSequence(String, location: SourceLocation) + case invalidEscapedNullValue(location: SourceLocation) + case invalidSpecialValue(expected: String, location: SourceLocation) + case unexpectedEscapedCharacter(ascii: UInt8, location: SourceLocation) + case unescapedControlCharacterInString(ascii: UInt8, location: SourceLocation) + case expectedLowSurrogateUTF8SequenceAfterHighSurrogate(location: SourceLocation) + case couldNotCreateUnicodeScalarFromUInt32(location: SourceLocation, unicodeScalarValue: UInt32) + case numberWithLeadingZero(location: SourceLocation) + case numberIsNotRepresentableInSwift(parsed: String) + case singleFragmentFoundButNotAllowed + + // JSON5 + + case unterminatedBlockComment + + var debugDescription: String { + switch self { + case .cannotConvertEntireInputDataToUTF8: + return "Unable to convert data to a string using the detected encoding. The data may be corrupt." + case let .cannotConvertInputStringDataToUTF8(location): + let line = location.line + let col = location.column + return "Unable to convert data to a string around line \(line), column \(col)." + case let .unexpectedCharacter(context, ascii, location): + let line = location.line + let col = location.column + if let context { + return "Unexpected character '\(String(UnicodeScalar(ascii)))' \(context) around line \(line), column \(col)." + } else { + return "Unexpected character '\(String(UnicodeScalar(ascii)))' around line \(line), column \(col)." + } + case .unexpectedEndOfFile: + return "Unexpected end of file" + case .tooManyNestedArraysOrDictionaries(let location): + if let location { + let line = location.line + let col = location.column + return "Too many nested arrays or dictionaries around line \(line), column \(col)." + } else { + return "Too many nested arrays or dictionaries." + } + case let .invalidHexDigitSequence(hexSequence, location): + let line = location.line + let col = location.column + return "Invalid hex digit in unicode escape sequence '\(hexSequence)' around line \(line), column \(col)." + case let .invalidEscapedNullValue(location): + let line = location.line + let col = location.column + return "Unsupported escaped null around line \(line), column \(col)." + case let .invalidSpecialValue(expected, location): + let line = location.line + let col = location.column + return "Invalid \(expected) value around line \(line), column \(col)." + case let .unexpectedEscapedCharacter(ascii, location): + let line = location.line + let col = location.column + return "Invalid escape sequence '\(String(UnicodeScalar(ascii)))' around line \(line), column \(col)." + case let .unescapedControlCharacterInString(ascii, location): + let line = location.line + let col = location.column + return "Unescaped control character '0x\(String(ascii, radix: 16))' around line \(line), column \(col)." + case let .expectedLowSurrogateUTF8SequenceAfterHighSurrogate(location): + let line = location.line + let col = location.column + return "Missing low code point in surrogate pair around line \(line), column \(col)." + case let .couldNotCreateUnicodeScalarFromUInt32(location, unicodeScalarValue): + let line = location.line + let col = location.column + return "Invalid unicode scalar value '0x\(String(unicodeScalarValue, radix: 16))' around line \(line), column \(col)." + case let .numberWithLeadingZero(location): + let line = location.line + let col = location.column + return "Number with leading zero around line \(line), column \(col)." + case let .numberIsNotRepresentableInSwift(parsed): + return "Number \(parsed) is not representable in Swift." + case .singleFragmentFoundButNotAllowed: + return "JSON input did not start with array or object as required by options." + + // JSON5 + + case .unterminatedBlockComment: + return "Unterminated block comment" + } + } + + var sourceLocation: SourceLocation? { + switch self { + case let .cannotConvertInputStringDataToUTF8(location), let .unexpectedCharacter(_, _, location): + return location + case let .tooManyNestedArraysOrDictionaries(location): + return location + case let .invalidHexDigitSequence(_, location), let .invalidEscapedNullValue(location), let .invalidSpecialValue(_, location): + return location + case let .unexpectedEscapedCharacter(_, location), let .unescapedControlCharacterInString(_, location), + let .expectedLowSurrogateUTF8SequenceAfterHighSurrogate(location): + return location + case let .couldNotCreateUnicodeScalarFromUInt32(location, _), let .numberWithLeadingZero(location): + return location + default: + return nil + } + } +} diff --git a/Sources/JMESPath/JSON/JSONUtilities.swift b/Sources/JMESPath/JSON/JSONUtilities.swift new file mode 100644 index 0000000..0ea8d7d --- /dev/null +++ b/Sources/JMESPath/JSON/JSONUtilities.swift @@ -0,0 +1,110 @@ +extension UInt8 { + internal static var _space: UInt8 { UInt8(ascii: " ") } + internal static var _return: UInt8 { UInt8(ascii: "\r") } + internal static var _newline: UInt8 { UInt8(ascii: "\n") } + internal static var _tab: UInt8 { UInt8(ascii: "\t") } + + internal static var _colon: UInt8 { UInt8(ascii: ":") } + internal static let _semicolon = UInt8(ascii: ";") + internal static var _comma: UInt8 { UInt8(ascii: ",") } + + internal static var _openbrace: UInt8 { UInt8(ascii: "{") } + internal static var _closebrace: UInt8 { UInt8(ascii: "}") } + + internal static var _openbracket: UInt8 { UInt8(ascii: "[") } + internal static var _closebracket: UInt8 { UInt8(ascii: "]") } + + internal static let _openangle = UInt8(ascii: "<") + internal static let _closeangle = UInt8(ascii: ">") + + internal static var _quote: UInt8 { UInt8(ascii: "\"") } + internal static var _backslash: UInt8 { UInt8(ascii: "\\") } + internal static var _forwardslash: UInt8 { UInt8(ascii: "/") } + + internal static var _equal: UInt8 { UInt8(ascii: "=") } + internal static var _minus: UInt8 { UInt8(ascii: "-") } + internal static var _plus: UInt8 { UInt8(ascii: "+") } + internal static var _question: UInt8 { UInt8(ascii: "?") } + internal static var _exclamation: UInt8 { UInt8(ascii: "!") } + internal static var _ampersand: UInt8 { UInt8(ascii: "&") } + internal static var _pipe: UInt8 { UInt8(ascii: "|") } + internal static var _period: UInt8 { UInt8(ascii: ".") } + internal static var _e: UInt8 { UInt8(ascii: "e") } + internal static var _E: UInt8 { UInt8(ascii: "E") } +} + +internal var _asciiNumbers: ClosedRange { UInt8(ascii: "0")...UInt8(ascii: "9") } + +internal func _parseIntegerDigits( + _ codeUnits: BufferView, + isNegative: Bool +) -> Result? { + guard _fastPath(!codeUnits.isEmpty) else { return nil } + + // ASCII constants, named for clarity: + let _0 = 48 as UInt8 + + let numericalUpperBound: UInt8 = _0 &+ 10 + let multiplicand: Result = 10 + var result: Result = 0 + + var iter = codeUnits.makeIterator() + while let digit = iter.next() { + let digitValue: Result + if _fastPath(digit >= _0 && digit < numericalUpperBound) { + digitValue = Result(truncatingIfNeeded: digit &- _0) + } else { + return nil + } + let overflow1: Bool + (result, overflow1) = result.multipliedReportingOverflow(by: multiplicand) + let overflow2: Bool + (result, overflow2) = + isNegative + ? result.subtractingReportingOverflow(digitValue) + : result.addingReportingOverflow(digitValue) + guard _fastPath(!overflow1 && !overflow2) else { return nil } + } + return result +} + +internal func _parseHexIntegerDigits( + _ codeUnits: BufferView, + isNegative: Bool +) -> Result? { + guard _fastPath(!codeUnits.isEmpty) else { return nil } + + // ASCII constants, named for clarity: + let _0 = 48 as UInt8 + let _A = 65 as UInt8 + let _a = 97 as UInt8 + + let numericalUpperBound = _0 &+ 10 + let uppercaseUpperBound = _A &+ 6 + let lowercaseUpperBound = _a &+ 6 + let multiplicand: Result = 16 + + var result = 0 as Result + for digit in codeUnits { + let digitValue: Result + if _fastPath(digit >= _0 && digit < numericalUpperBound) { + digitValue = Result(truncatingIfNeeded: digit &- _0) + } else if _fastPath(digit >= _A && digit < uppercaseUpperBound) { + digitValue = Result(truncatingIfNeeded: digit &- _A &+ 10) + } else if _fastPath(digit >= _a && digit < lowercaseUpperBound) { + digitValue = Result(truncatingIfNeeded: digit &- _a &+ 10) + } else { + return nil + } + + let overflow1: Bool + (result, overflow1) = result.multipliedReportingOverflow(by: multiplicand) + let overflow2: Bool + (result, overflow2) = + isNegative + ? result.subtractingReportingOverflow(digitValue) + : result.addingReportingOverflow(digitValue) + guard _fastPath(!overflow1 && !overflow2) else { return nil } + } + return result +} diff --git a/Sources/JMESPath/Number.swift b/Sources/JMESPath/Number.swift index c8d6728..b309e6e 100644 --- a/Sources/JMESPath/Number.swift +++ b/Sources/JMESPath/Number.swift @@ -13,7 +13,7 @@ import Bionic #endif /// Number type that can store integer or floating point -public struct JMESNumber: Sendable, Equatable { +struct JMESNumber: Sendable, Equatable { fileprivate enum _Internal { case int(Int) case double(Double) diff --git a/Sources/JMESPath/Object.swift b/Sources/JMESPath/Object.swift new file mode 100644 index 0000000..b84cf6a --- /dev/null +++ b/Sources/JMESPath/Object.swift @@ -0,0 +1,17 @@ +/// JMES Object type +typealias JMESObject = [String: Any] + +extension JMESObject { + /// return if objects are equal by converting values to `JMESVariable` + func equalTo(_ rhs: JMESObject) -> Bool { + guard self.count == rhs.count else { return false } + for element in self { + guard let rhsValue = rhs[element.key], + JMESVariable(from: rhsValue) == JMESVariable(from: element.value) + else { + return false + } + } + return true + } +} diff --git a/Sources/JMESPath/Runtime.swift b/Sources/JMESPath/Runtime.swift index 07c4f9e..7df3754 100644 --- a/Sources/JMESPath/Runtime.swift +++ b/Sources/JMESPath/Runtime.swift @@ -11,12 +11,12 @@ public class JMESRuntime { /// - Parameters: /// - name: Function name /// - function: Function object - public func registerFunction(_ name: String, function: JMESFunction.Type) { + func registerFunction(_ name: String, function: JMESFunction.Type) { self.functions[name] = function } func getFunction(_ name: String) -> JMESFunction.Type? { - return self.functions[name] + self.functions[name] } private var functions: [String: JMESFunction.Type] diff --git a/Sources/JMESPath/Sendable.swift b/Sources/JMESPath/Sendable.swift deleted file mode 100644 index 3b0d9fb..0000000 --- a/Sources/JMESPath/Sendable.swift +++ /dev/null @@ -1,7 +0,0 @@ -// Sendable support - -#if compiler(>=5.6) -public typealias JMESSendable = Sendable -#else -public typealias JMESSendable = Any -#endif \ No newline at end of file diff --git a/Sources/JMESPath/Variable.swift b/Sources/JMESPath/Variable.swift index ddeee24..09ffef1 100644 --- a/Sources/JMESPath/Variable.swift +++ b/Sources/JMESPath/Variable.swift @@ -1,14 +1,20 @@ -import Foundation - -public typealias JMESArray = [Any] -public typealias JMESObject = [String: Any] +import Foundation // required for JSONSerialization public protocol JMESPropertyWrapper { var anyValue: Any { get } } +protocol JMESVariableProtocol { + var value: JMESVariable { get } + func getField(_ key: String) -> Self + func getIndex(_ index: Int) -> Self +} + +/// Null value in JSON +public struct JMESNull {} + /// Internal representation of a variable -public enum JMESVariable { +enum JMESVariable { case null case string(String) case number(JMESNumber) @@ -27,22 +33,18 @@ public enum JMESVariable { self = .number(.init(integer)) case let float as any BinaryFloatingPoint: self = .number(.init(float)) - case let number as NSNumber: - // both booleans and integer/float point types can be converted to a `NSNumber` - // We have to check to see the type id to see if it is a boolean - if type(of: number) == Self.nsNumberBoolType { - self = .boolean(number.boolValue) - } else { - self = .number(.init(number.doubleValue)) - } - case let array as [Any]: + case let bool as Bool: + self = .boolean(bool) + case let array as JMESArray: self = .array(array) case let set as Set: self = .array(set.map { $0 }) - case let dictionary as [String: Any]: + case let dictionary as JMESObject: self = .object(dictionary) - case is NSNull: + case is JMESNull: self = .null + case let variable as JMESVariable: + self = variable default: // use Mirror to build JMESVariable.object let mirror = Mirror(reflecting: any) @@ -53,7 +55,7 @@ public enum JMESVariable { switch mirror.displayStyle { case .collection: let array = mirror.children.map { - Self.unwrap($0.value) ?? NSNull() + Self.unwrap($0.value) ?? JMESNull() } self = .array(array) case .dictionary: @@ -62,7 +64,7 @@ public enum JMESVariable { while let key = mirror.descendant(index, "key") as? String, let value = mirror.descendant(index, "value") { - object[key] = Self.unwrap(value) ?? NSNull() + object[key] = Self.unwrap(value) ?? JMESNull() index += 1 } self = .object(object) @@ -73,10 +75,10 @@ public enum JMESVariable { self = .null return } - var unwrapValue = Self.unwrap(child.value) ?? NSNull() + var unwrapValue = Self.unwrap(child.value) ?? JMESNull() if let wrapper = unwrapValue as? JMESPropertyWrapper, label.first == "_" { label = String(label.dropFirst()) - unwrapValue = Self.unwrap(wrapper.anyValue) ?? NSNull() + unwrapValue = Self.unwrap(wrapper.anyValue) ?? JMESNull() } object[label] = unwrapValue } @@ -87,13 +89,7 @@ public enum JMESVariable { /// create JMESVariable from json public static func fromJson(_ json: String) throws -> Self { - try self.fromJson(Data(json.utf8)) - } - - /// create JMESVariable from json - public static func fromJson(_ json: Data) throws -> Self { - let object = try JSONSerialization.jsonObject(with: json, options: [.allowFragments]) - return JMESVariable(from: object) + try JMESVariable(from: JMESJSON.parse(json: json)) } /// Collapse JMESVariable back to its equivalent Swift type @@ -116,7 +112,7 @@ public enum JMESVariable { case .string(let string): return string case .number(let number): - return String(describing: number) + return String(describing: number.collapse()) case .boolean(let bool): return String(describing: bool) case .array(let array): @@ -175,25 +171,6 @@ public enum JMESVariable { } } - /// Get variable for field from object type - public func getField(_ key: String) -> JMESVariable { - if case .object(let object) = self { - return object[key].map { JMESVariable(from: $0) } ?? .null - } - return .null - } - - /// Get variable for index from array type - public func getIndex(_ index: Int) -> JMESVariable { - if case .array(let array) = self { - let index = array.calculateIndex(index) - if index >= 0, index < array.count { - return JMESVariable(from: array[index]) - } - } - return .null - } - public func isTruthy() -> Bool { switch self { case .boolean(let bool): return bool @@ -276,7 +253,6 @@ public enum JMESVariable { } fileprivate static var nsNumberBoolType = type(of: NSNumber(value: true)) - fileprivate static var nsNumberIntType = type(of: NSNumber(value: Int(1))) } extension JMESVariable: Equatable { @@ -304,42 +280,26 @@ extension JMESVariable: Equatable { } } -extension JMESArray { - /// return if arrays are equal by converting entries to `JMESVariable` - fileprivate func equalTo(_ rhs: JMESArray) -> Bool { - guard self.count == rhs.count else { return false } - for i in 0.. Bool { - guard self.count == rhs.count else { return false } - for element in self { - guard let rhsValue = rhs[element.key], - JMESVariable(from: rhsValue) == JMESVariable(from: element.value) - else { - return false - } + /// Get variable for field from object type + public func getField(_ key: String) -> JMESVariable { + if case .object(let object) = self { + return object[key].map { JMESVariable(from: $0) } ?? .null } - return true + return .null } -} -extension Array { - /// calculate actual index. Negative indices read backwards from end of array - func calculateIndex(_ index: Int) -> Int { - if index >= 0 { - return index - } else { - return count + index + /// Get variable for index from array type + public func getIndex(_ index: Int) -> JMESVariable { + if case .array(let array) = self { + let index = array.calculateIndex(index) + if index >= 0, index < array.count { + return JMESVariable(from: array[index]) + } } + return .null } } diff --git a/Sources/JMESPath/json.swift b/Sources/JMESPath/json.swift new file mode 100644 index 0000000..4aab8b4 --- /dev/null +++ b/Sources/JMESPath/json.swift @@ -0,0 +1,137 @@ +#if canImport(FoundationEssentials) +import FoundationEssentials +#else +import Foundation +#endif + +/// Namespace to wrap JSON parsing code +enum JMESJSON { + /// Parse JSON into object + /// - Parameter json: json string + /// - Returns: object + static func parse(json: String) throws -> Any { + try json.withBufferView { view in + var scanner = JSONScanner(bytes: view, options: .init()) + let map = try scanner.scan() + guard let value = map.loadValue(at: 0) else { throw JMESPathError.runtime("Empty JSON file") } + return try JMESJSONVariable(value: value).getValue(map) + } + } + + /// Parse JSON into object + /// - Parameter json: json string + /// - Returns: object + static func parse(json: some ContiguousBytes) throws -> Any { + try json.withBufferView { view in + var scanner = JSONScanner(bytes: view, options: .init()) + let map = try scanner.scan() + guard let value = map.loadValue(at: 0) else { throw JMESPathError.runtime("Empty JSON file") } + return try JMESJSONVariable(value: value).getValue(map) + } + } + +} + +struct JMESJSONVariable { + let value: JSONMap.Value + init(value: JSONMap.Value) { + self.value = value + } + + init?(json: String) throws { + guard + let variable = try json.withBufferView({ view -> JMESJSONVariable? in + var scanner = JSONScanner(bytes: view, options: .init()) + let map = try scanner.scan() + guard let value = map.loadValue(at: 0) else { return nil } + return JMESJSONVariable(value: value) + }) + else { return nil } + self = variable + } +} + +extension JMESJSONVariable { + func getValue(_ map: JSONMap) throws -> Any { + switch self.value { + case .string(let region, let isSimple): + return try map.withBuffer(for: region) { stringBuffer, fullSource in + if isSimple { + guard let result = String._tryFromUTF8(stringBuffer) else { + throw JSONError.cannotConvertInputStringDataToUTF8( + location: .sourceLocation(at: stringBuffer.startIndex, fullSource: fullSource) + ) + } + return result + } + return try JSONScanner.stringValue(from: stringBuffer, fullSource: fullSource) + } + + case .bool(let value): + return value + + case .null: + return JMESNull() + + case .number(let region, let hasExponent): + return try map.withBuffer(for: region) { numberBuffer, fullSource in + if hasExponent { + let digitsStartPtr = try JSONScanner.prevalidateJSONNumber(from: numberBuffer, hasExponent: hasExponent, fullSource: fullSource) + + if let floatingPoint = Double(prevalidatedBuffer: numberBuffer) { + // Check for overflow (which results in an infinite result), or rounding to zero. + // While strtod does set ERANGE in the either case, we don't rely on it because setting errno to 0 first and then check the result is surprisingly expensive. For values "rounded" to infinity, we reject those out of hand. For values "rounded" down to zero, we perform check for any non-zero digits in the input, which turns out to be much faster. + if floatingPoint.isFinite { + // Should also check for underflow here + return floatingPoint + } else { + throw JSONError.numberIsNotRepresentableInSwift(parsed: String(decoding: numberBuffer, as: UTF8.self)) + } + } + throw JSONScanner.validateNumber(from: numberBuffer.suffix(from: digitsStartPtr), fullSource: fullSource) + + } else { + let digitBeginning = try JSONScanner.prevalidateJSONNumber(from: numberBuffer, hasExponent: hasExponent, fullSource: fullSource) + // This is the fast pass. Number directly convertible to Integer. + if let integer = Int(prevalidatedBuffer: numberBuffer) { + return integer + } + if let double = Double(prevalidatedBuffer: numberBuffer) { + return double + } + throw JSONScanner.validateNumber(from: numberBuffer.suffix(from: digitBeginning), fullSource: fullSource) + } + } + + case .array(let region): + var entries = [JMESJSONVariable]() + var iterator = map.makeArrayIterator(from: region.startOffset) + while let value = iterator.next() { + entries.append(.init(value: value)) + } + return try entries.map { try $0.getValue(map) } + + case .object(let region): + var entries = [String: JMESJSONVariable]() + var iterator = map.makeObjectIterator(from: region.startOffset) + while let value = iterator.next() { + guard case .string(let region, let isSimple) = value.key else { + throw JMESPathError.runtime("Non string dictionary keys are not supported.") + } + let key = try map.withBuffer(for: region) { stringBuffer, fullSource in + if isSimple { + guard let result = String._tryFromUTF8(stringBuffer) else { + throw JSONError.cannotConvertInputStringDataToUTF8( + location: .sourceLocation(at: stringBuffer.startIndex, fullSource: fullSource) + ) + } + return result + } + return try JSONScanner.stringValue(from: stringBuffer, fullSource: fullSource) + } + entries[key] = .init(value: value.value) + } + return try entries.mapValues { try $0.getValue(map) } + } + } +} diff --git a/Tests/JMESPathTests/ComplianceTests.swift b/Tests/JMESPathTests/ComplianceTests.swift index ae8e157..68a7326 100644 --- a/Tests/JMESPathTests/ComplianceTests.swift +++ b/Tests/JMESPathTests/ComplianceTests.swift @@ -58,14 +58,56 @@ final class ComplianceTests: XCTestCase { let expression: String let error: String? let bench: String? - let result: AnyDecodable? + let result: String? let comment: String? + + init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.expression = try container.decode(String.self, forKey: .expression) + self.error = try container.decodeIfPresent(String.self, forKey: .error) + self.bench = try container.decodeIfPresent(String.self, forKey: .bench) + self.comment = try container.decodeIfPresent(String.self, forKey: .comment) + guard let anyDecodable = try container.decodeIfPresent(AnyDecodable.self, forKey: .result) else { + self.result = nil + return + } + let jsonData = try JSONSerialization.data( + withJSONObject: anyDecodable.value, + options: [.fragmentsAllowed, .sortedKeys] + ) + self.result = String(decoding: jsonData, as: Unicode.UTF8.self) + } + + private enum CodingKeys: String, CodingKey { + case expression + case error + case bench + case result + case comment + } } - let given: AnyDecodable + let given: String let cases: [Case] let comment: String? + init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.cases = try container.decode([Case].self, forKey: .cases) + self.comment = try container.decodeIfPresent(String.self, forKey: .comment) + let anyDecodable = try container.decode(AnyDecodable.self, forKey: .given) + let jsonData = try JSONSerialization.data( + withJSONObject: anyDecodable.value, + options: [.fragmentsAllowed, .sortedKeys] + ) + self.given = String(decoding: jsonData, as: Unicode.UTF8.self) + } + + private enum CodingKeys: String, CodingKey { + case given + case cases + case comment + } @available(iOS 11.0, tvOS 11.0, watchOS 5.0, *) func run() throws { for c in self.cases { @@ -74,7 +116,7 @@ final class ComplianceTests: XCTestCase { } else if let error = c.error { self.testError(c, error: error) } else { - self.testResult(c, result: c.result?.value) + self.testResult(c) } } } @@ -82,7 +124,7 @@ final class ComplianceTests: XCTestCase { func testBenchmark(_ c: Case) { do { let expression = try JMESExpression.compile(c.expression) - _ = try expression.search(object: self.given.value) + _ = try expression.search(json: self.given) } catch { XCTFail("\(error)") } @@ -91,7 +133,7 @@ final class ComplianceTests: XCTestCase { func testError(_ c: Case, error: String) { do { let expression = try JMESExpression.compile(c.expression) - _ = try expression.search(object: self.given.value) + _ = try expression.search(json: self.given) } catch { return } @@ -102,27 +144,34 @@ final class ComplianceTests: XCTestCase { XCTFail("Should throw an error") } + func convertNulls(_ value: Any) -> Any { + switch value { + case is JMESNull: + NSNull() + case let array as [Any]: + array.map { convertNulls($0) } + case let object as [String: Any]: + object.mapValues { convertNulls($0) } + default: + value + } + } + @available(iOS 11.0, tvOS 11.0, watchOS 5.0, *) - func testResult(_ c: Case, result: Any?) { + func testResult(_ c: Case) { + let expectedResult = c.result do { let expression = try JMESExpression.compile(c.expression) - let resultJson: String? = try result.map { - let data = try JSONSerialization.data( - withJSONObject: $0, - options: [.fragmentsAllowed, .sortedKeys] - ) - return String(decoding: data, as: Unicode.UTF8.self) - } - if let value = try expression.search(object: self.given.value) { + if let value = try expression.search(json: self.given) { let valueData = try JSONSerialization.data( - withJSONObject: value, + withJSONObject: convertNulls(value), options: [.fragmentsAllowed, .sortedKeys] ) let valueJson = String(decoding: valueData, as: Unicode.UTF8.self) - XCTAssertEqual(resultJson, valueJson) + XCTAssertEqual(expectedResult, valueJson, c.comment ?? c.expression) } else { - XCTAssertNil(result) + XCTAssertNil(expectedResult) } } catch { XCTFail("\(error)") @@ -132,16 +181,11 @@ final class ComplianceTests: XCTestCase { @available(iOS 11.0, tvOS 11.0, watchOS 5.0, *) func output(_ c: Case, expected: String?, result: String?) { if expected != result { - let data = try! JSONSerialization.data( - withJSONObject: self.given.value, - options: [.fragmentsAllowed, .sortedKeys] - ) - let givenJson = String(decoding: data, as: Unicode.UTF8.self) if let comment = c.comment { print("Comment: \(comment)") } print("Expression: \(c.expression)") - print("Given: \(givenJson)") + print("Given: \(given)") print("Expected: \(expected ?? "nil")") print("Result: \(result ?? "nil")") } diff --git a/Tests/JMESPathTests/JSONTests.swift b/Tests/JMESPathTests/JSONTests.swift new file mode 100644 index 0000000..054de09 --- /dev/null +++ b/Tests/JMESPathTests/JSONTests.swift @@ -0,0 +1,43 @@ +import XCTest + +@testable import JMESPath + +final class JSONTests: XCTestCase { + func testInterpreter(_ expression: String, json: String, result: Value) { + do { + let expression = try JMESExpression.compile(expression) + let searchResult = try XCTUnwrap(expression.search(json: json)) + guard let value = searchResult as? Value else { + XCTFail("Expected \(Value.self), instead we got \(type(of: searchResult))") + return + } + XCTAssertEqual(value, result) + } catch { + XCTFail("\(error)") + } + } + + func testString() { + self.testInterpreter("s", json: #"{"s": "test"}"#, result: "test") + } + + func testNumbers() { + let json = #"{"i": 34, "d": 1.4, "b": true}"# + self.testInterpreter("i", json: json, result: 34) + self.testInterpreter("d", json: json, result: 1.4) + self.testInterpreter("b", json: json, result: true) + } + + func testArray() { + let json = #"{"a":[1,2,3,4,5]}"# + self.testInterpreter("a", json: json, result: [1, 2, 3, 4, 5]) + self.testInterpreter("a[2]", json: json, result: 3) + self.testInterpreter("a[-2]", json: json, result: 4) + self.testInterpreter("a[1]", json: json, result: 2) + } + + func testObjects() { + let json = #"{"sub": {"a": "hello"}}"# + self.testInterpreter("sub.a", json: json, result: "hello") + } +} diff --git a/Tests/JMESPathTests/MirrorTests.swift b/Tests/JMESPathTests/MirrorTests.swift index c138b91..f12af83 100644 --- a/Tests/JMESPathTests/MirrorTests.swift +++ b/Tests/JMESPathTests/MirrorTests.swift @@ -6,7 +6,11 @@ final class MirrorTests: XCTestCase { func testInterpreter(_ expression: String, data: Any, result: Value) { do { let expression = try JMESExpression.compile(expression) - let value = try XCTUnwrap(expression.search(object: data, as: Value.self)) + let searchResult = try XCTUnwrap(expression.search(object: data)) + guard let value = searchResult as? Value else { + XCTFail("Expected \(Value.self), instead we got \(type(of: searchResult))") + return + } XCTAssertEqual(value, result) } catch { XCTFail("\(error)")