From d96606e7f73fa09a2f2919623c907632af146252 Mon Sep 17 00:00:00 2001 From: Philippe Hausler Date: Fri, 18 Feb 2022 00:05:36 -0800 Subject: [PATCH] Clean up the marble diagram implementation and factor it into a per Task based queue system (#44) * Split the marble diagram code out into their own files for easier refactoring * Update latest landing InstantProtocol definition stub * Migrate to a per Task based queue system to avoid blocking valid future jobs * Factor inputs to be specialized waits for side tracking * Add grouping support * Add tests for grouping and parse failures * Fixup misstep in package definition for clock stub imports for the marable diagrams * Add descriptions for partial iterations for debugging aides * Simplify Task.select implementation to handle continuations more encapsulatedly * Add descriptions for WorkQueue items for debugging and use stable work queue drains --- Package.swift | 2 +- .../AsyncAlgorithms/PartialIteration.swift | 10 +- Sources/AsyncAlgorithms/TaskSelect.swift | 18 +- Sources/ClockStub/Instant.swift | 22 +- Sources/MarbleDiagram/Clock.swift | 111 +++ Sources/MarbleDiagram/Event.swift | 132 ++++ Sources/MarbleDiagram/Expectation.swift | 72 ++ Sources/MarbleDiagram/Input.swift | 113 +++ Sources/MarbleDiagram/Job.swift | 24 + Sources/MarbleDiagram/MarbleDiagram.swift | 658 +----------------- Sources/MarbleDiagram/TaskDriver.swift | 61 ++ Sources/MarbleDiagram/Test.swift | 290 ++++++++ Sources/MarbleDiagram/Theme.swift | 49 ++ Sources/MarbleDiagram/WorkQueue.swift | 299 ++++++++ .../Support}/ManualClock.swift | 2 +- .../Support/MarbleDiagram.swift | 21 +- .../TestCombineLatest.swift | 1 - .../TestManualClock.swift | 7 +- .../TestMarbleDiagram.swift | 43 ++ .../AsyncAlgorithmsTests/TestValidator.swift | 1 - 20 files changed, 1270 insertions(+), 666 deletions(-) create mode 100644 Sources/MarbleDiagram/Clock.swift create mode 100644 Sources/MarbleDiagram/Event.swift create mode 100644 Sources/MarbleDiagram/Expectation.swift create mode 100644 Sources/MarbleDiagram/Input.swift create mode 100644 Sources/MarbleDiagram/Job.swift create mode 100644 Sources/MarbleDiagram/TaskDriver.swift create mode 100644 Sources/MarbleDiagram/Test.swift create mode 100644 Sources/MarbleDiagram/Theme.swift create mode 100644 Sources/MarbleDiagram/WorkQueue.swift rename {Sources/MarbleDiagram => Tests/AsyncAlgorithmsTests/Support}/ManualClock.swift (99%) diff --git a/Package.swift b/Package.swift index 55e0ece..95a2312 100644 --- a/Package.swift +++ b/Package.swift @@ -24,7 +24,7 @@ let package = Package( name: "AsyncAlgorithms", dependencies: ["ClockStub"]), .target(name: "ClockStub"), - .target(name: "MarbleDiagram", dependencies: ["CMarbleDiagram"]), + .target(name: "MarbleDiagram", dependencies: ["CMarbleDiagram", "ClockStub"]), .target(name: "CMarbleDiagram", publicHeadersPath: "Headers", cxxSettings: [ diff --git a/Sources/AsyncAlgorithms/PartialIteration.swift b/Sources/AsyncAlgorithms/PartialIteration.swift index 3927515..226d3c6 100644 --- a/Sources/AsyncAlgorithms/PartialIteration.swift +++ b/Sources/AsyncAlgorithms/PartialIteration.swift @@ -9,11 +9,19 @@ // //===----------------------------------------------------------------------===// -enum PartialIteration: Sendable where Iterator: Sendable, Iterator.Element: Sendable { +enum PartialIteration: CustomStringConvertible, Sendable where Iterator: Sendable, Iterator.Element: Sendable { case idle(Iterator) case pending(Task) case terminal + var description: String { + switch self { + case .idle: return "idle" + case .pending: return "pending" + case .terminal: return "terminal" + } + } + mutating func resolve(_ result: Result, _ iterator: Iterator) rethrows -> Iterator.Element? { do { guard let value = try result._rethrowGet() else { diff --git a/Sources/AsyncAlgorithms/TaskSelect.swift b/Sources/AsyncAlgorithms/TaskSelect.swift index 922d27a..8ff93e0 100644 --- a/Sources/AsyncAlgorithms/TaskSelect.swift +++ b/Sources/AsyncAlgorithms/TaskSelect.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// struct TaskSelectState: Sendable { - var continuation: UnsafeContinuation, Never>? + var complete = false var tasks: [Task]? = [] mutating func add(_ task: Task) -> Task? { @@ -30,7 +30,7 @@ extension Task { /// - Parameters: /// - tasks: The running tasks to obtain a result from /// - Returns: The first task to complete from the running tasks - public static func select( + public static func select( _ tasks: Tasks ) async -> Task where Tasks.Element == Task { @@ -45,16 +45,16 @@ extension Task { } } operation: { await withUnsafeContinuation { continuation in - state.withCriticalRegion { state in - state.continuation = continuation - } for task in tasks { Task { _ = await task.result - state.withCriticalRegion { state -> UnsafeResumption, Never>? in - defer { state.continuation = nil } - return state.continuation.map { UnsafeResumption(continuation: $0, success: task) } - }?.resume() + let winner = state.withCriticalRegion { state -> Bool in + defer { state.complete = true } + return !state.complete + } + if winner { + continuation.resume(returning: task) + } } state.withCriticalRegion { state in state.add(task) diff --git a/Sources/ClockStub/Instant.swift b/Sources/ClockStub/Instant.swift index 0ddf3c7..396f23c 100644 --- a/Sources/ClockStub/Instant.swift +++ b/Sources/ClockStub/Instant.swift @@ -16,25 +16,37 @@ public protocol InstantProtocol: Comparable, Hashable, Sendable { func duration(to other: Self) -> Duration } +/* +disabled for now - this perturbs operator resolution extension InstantProtocol { + @_alwaysEmitIntoClient + @inlinable public static func + (_ lhs: Self, _ rhs: Duration) -> Self { lhs.advanced(by: rhs) } - + + @_alwaysEmitIntoClient + @inlinable public static func += (_ lhs: inout Self, _ rhs: Duration) { lhs = lhs.advanced(by: rhs) } - + + @_alwaysEmitIntoClient + @inlinable public static func - (_ lhs: Self, _ rhs: Duration) -> Self { lhs.advanced(by: .zero - rhs) } - + + @_alwaysEmitIntoClient + @inlinable public static func -= (_ lhs: inout Self, _ rhs: Duration) { lhs = lhs.advanced(by: .zero - rhs) } - + + @_alwaysEmitIntoClient + @inlinable public static func - (_ lhs: Self, _ rhs: Self) -> Duration { rhs.duration(to: lhs) } } - +*/ diff --git a/Sources/MarbleDiagram/Clock.swift b/Sources/MarbleDiagram/Clock.swift new file mode 100644 index 0000000..668e6ed --- /dev/null +++ b/Sources/MarbleDiagram/Clock.swift @@ -0,0 +1,111 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import ClockStub + +extension MarbleDiagram { + public struct Clock { + let queue: WorkQueue + + init(queue: WorkQueue) { + self.queue = queue + } + } +} + +extension MarbleDiagram.Clock: Clock { + public struct Step: DurationProtocol, Hashable, CustomStringConvertible { + internal var rawValue: Int + + internal init(_ rawValue: Int) { + self.rawValue = rawValue + } + + public static func + (lhs: Step, rhs: Step) -> Step { + return .init(lhs.rawValue + rhs.rawValue) + } + + public static func - (lhs: Step, rhs: Step) -> Step { + .init(lhs.rawValue - rhs.rawValue) + } + + public static func / (lhs: Step, rhs: Int) -> Step { + .init(lhs.rawValue / rhs) + } + + public static func * (lhs: Step, rhs: Int) -> Step { + .init(lhs.rawValue * rhs) + } + + public static func / (lhs: Step, rhs: Step) -> Double { + Double(lhs.rawValue) / Double(rhs.rawValue) + } + + public static func < (lhs: Step, rhs: Step) -> Bool { + lhs.rawValue < rhs.rawValue + } + + public static var zero: Step { .init(0) } + + public static func steps(_ amount: Int) -> Step { + return Step(amount) + } + + public var description: String { + return "step \(rawValue)" + } + } + + public struct Instant: InstantProtocol, CustomStringConvertible { + public typealias Duration = Step + + let when: Step + + public func advanced(by duration: Step) -> Instant { + Instant(when: when + duration) + } + + public func duration(to other: Instant) -> Step { + other.when - when + } + + public static func < (lhs: Instant, rhs: Instant) -> Bool { + lhs.when < rhs.when + } + + public var description: String { + // the raw value is 1 indexed in execution but we should report it as 0 indexed + return "tick \(when.rawValue - 1)" + } + } + + public var now: Instant { + queue.now + } + + public var minimumResolution: Step { + .steps(1) + } + + public func sleep( + until deadline: Instant, + tolerance: Step? = nil + ) async throws { + let token = queue.prepare() + try await withTaskCancellationHandler { + queue.cancel(token) + } operation: { + try await withUnsafeThrowingContinuation { continuation in + queue.enqueue(MarbleDiagram.Context.currentJob, deadline: deadline, continuation: continuation, token: token) + } + } + } +} diff --git a/Sources/MarbleDiagram/Event.swift b/Sources/MarbleDiagram/Event.swift new file mode 100644 index 0000000..d1e9983 --- /dev/null +++ b/Sources/MarbleDiagram/Event.swift @@ -0,0 +1,132 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +extension MarbleDiagram { + struct Failure: Error, Equatable { } + + enum ParseFailure: Error, CustomStringConvertible { + case stepInGroup(String, String.Index) + case nestedGroup(String, String.Index) + case unbalancedNesting(String, String.Index) + + var description: String { + switch self { + case .stepInGroup: + return "marble diagram step symbol in group" + case .nestedGroup: + return "marble diagram nested grouping" + case .unbalancedNesting: + return "marble diagram unbalanced grouping" + } + } + } + + enum Event { + case value(String, String.Index) + case failure(Error, String.Index) + case finish(String.Index) + + var results: [Result] { + switch self { + case .value(let value, _): return [.success(value)] + case .failure(let failure, _): return [.failure(failure)] + case .finish: return [.success(nil)] + } + } + + var index: String.Index { + switch self { + case .value(_, let index): return index + case .failure(_, let index): return index + case .finish(let index): return index + } + } + + static func parse(_ dsl: String, theme: Theme) throws -> [(Clock.Instant, Event)] { + var emissions = [(Clock.Instant, Event)]() + var when = Clock.Instant(when: .steps(0)) + var string: String? + var grouping = 0 + + for index in dsl.indices { + let ch = dsl[index] + switch theme.token(dsl[index], inValue: string != nil) { + case .step: + if string == nil { + if grouping == 0 { + when = when.advanced(by: .steps(1)) + } else { + throw ParseFailure.stepInGroup(dsl, index) + } + } else { + string?.append(ch) + } + case .error: + if string == nil { + if grouping == 0 { + when = when.advanced(by: .steps(1)) + } + emissions.append((when, .failure(Failure(), index))) + } else { + string?.append(ch) + } + case .finish: + if string == nil { + if grouping == 0 { + when = when.advanced(by: .steps(1)) + } + emissions.append((when, .finish(index))) + } else { + string?.append(ch) + } + case .beginValue: + string = "" + case .endValue: + if let value = string { + string = nil + if grouping == 0 { + when = when.advanced(by: .steps(1)) + } + emissions.append((when, .value(value, index))) + } + case .beginGroup: + if grouping == 0 { + when = when.advanced(by: .steps(1)) + } else { + throw ParseFailure.nestedGroup(dsl, index) + } + grouping += 1 + case .endGroup: + grouping -= 1 + if grouping < 0 { + throw ParseFailure.unbalancedNesting(dsl, index) + } + case .skip: + string?.append(ch) + continue + case .value(let str): + if string == nil { + if grouping == 0 { + when = when.advanced(by: .steps(1)) + } + emissions.append((when, .value(String(ch), index))) + } else { + string?.append(str) + } + } + } + if grouping != 0 { + throw ParseFailure.unbalancedNesting(dsl, dsl.endIndex) + } + return emissions + } + } +} diff --git a/Sources/MarbleDiagram/Expectation.swift b/Sources/MarbleDiagram/Expectation.swift new file mode 100644 index 0000000..293cef3 --- /dev/null +++ b/Sources/MarbleDiagram/Expectation.swift @@ -0,0 +1,72 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +extension MarbleDiagram { + public struct ExpectationResult { + public var expected: [(Clock.Instant, Result)] + public var actual: [(Clock.Instant, Result)] + } + + public struct ExpectationFailure: CustomStringConvertible { + public enum Kind { + case expectedFinishButGotValue(String) + case expectedMismatch(String, String) + case expectedValueButGotFinished(String) + case expectedFailureButGotValue(Error, String) + case expectedFailureButGotFinish(Error) + case expectedValueButGotFailure(String, Error) + case expectedFinishButGotFailure(Error) + case expectedValue(String) + case expectedFinish + case expectedFailure(Error) + case unexpectedValue(String) + case unexpectedFinish + case unexpectedFailure(Error) + } + public var when: Clock.Instant + public var kind: Kind + + var reason: String { + switch kind { + case .expectedFinishButGotValue(let actual): + return "expected finish but got \"\(actual)\"" + case .expectedMismatch(let expected, let actual): + return "expected \"\(expected)\" but got \"\(actual)\"" + case .expectedValueButGotFinished(let expected): + return "expected \"\(expected)\" but got finish" + case .expectedFailureButGotValue(_, let actual): + return "expected failure but got \"\(actual)\"" + case .expectedFailureButGotFinish: + return "expected failure but got finish" + case .expectedValueButGotFailure(let expected, _): + return "expected \"\(expected)\" but got failure" + case .expectedFinishButGotFailure: + return "expected finish but got failure" + case .expectedValue(let expected): + return "expected \"\(expected)\"" + case .expectedFinish: + return "expected finish" + case .expectedFailure: + return "expected failure" + case .unexpectedValue(let actual): + return "unexpected \"\(actual)\"" + case .unexpectedFinish: + return "unexpected finish" + case .unexpectedFailure: + return "unexpected failure" + } + } + + public var description: String { + return reason + " at tick \(when.when.rawValue - 1)" + } + } +} diff --git a/Sources/MarbleDiagram/Input.swift b/Sources/MarbleDiagram/Input.swift new file mode 100644 index 0000000..7eea21d --- /dev/null +++ b/Sources/MarbleDiagram/Input.swift @@ -0,0 +1,113 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +extension MarbleDiagram { + public struct Input: AsyncSequence, Sendable { + public typealias Element = String + + struct State { + var emissions = [(Clock.Instant, Event)]() + } + + let state = ManagedCriticalState(State()) + let queue: WorkQueue + let index: Int + + public struct Iterator: AsyncIteratorProtocol { + let state: ManagedCriticalState + let queue: WorkQueue + let index: Int + var active: (Clock.Instant, [Result])? + var eventIndex = 0 + + mutating func apply(when: Clock.Instant, results: [Result]) async throws -> Element? { + let token = queue.prepare() + if eventIndex + 1 >= results.count { + active = nil + } + defer { + if active != nil { + eventIndex += 1 + } else { + eventIndex = 0 + } + } + return try await withTaskCancellationHandler { [queue] in + queue.cancel(token) + } operation: { + try await withUnsafeThrowingContinuation { continuation in + queue.enqueue(Context.currentJob, deadline: when, continuation: continuation, results[eventIndex], index: index, token: token) + } + } + } + + public mutating func next() async throws -> Element? { + if let (when, results) = active { + return try await apply(when: when, results: results) + } else { + let next = state.withCriticalRegion { state -> (Clock.Instant, Event)? in + guard state.emissions.count > 0 else { + return nil + } + return state.emissions.removeFirst() + } + guard let next = next else { + return nil + } + let when = next.0 + let results = next.1.results + active = (when, results) + return try await apply(when: when, results: results) + } + } + } + + public func makeAsyncIterator() -> Iterator { + Iterator(state: state, queue: queue, index: index) + } + + func parse(_ dsl: String, theme: Theme) throws { + let emissions = try Event.parse(dsl, theme: theme) + state.withCriticalRegion { state in + state.emissions = emissions + } + } + + var end: Clock.Instant? { + return state.withCriticalRegion { state in + state.emissions.map { $0.0 }.sorted().last + } + } + } + + public struct InputList: RandomAccessCollection, Sendable { + let state = ManagedCriticalState([Input]()) + let queue: WorkQueue + + public var startIndex: Int { return 0 } + public var endIndex: Int { + state.withCriticalRegion { $0.count } + } + + public subscript(position: Int) -> MarbleDiagram.Input { + get { + return state.withCriticalRegion { state in + if position >= state.count { + for _ in state.count...position { + state.append(Input(queue: queue, index: position)) + } + } + return state[position] + } + } + } + } +} diff --git a/Sources/MarbleDiagram/Job.swift b/Sources/MarbleDiagram/Job.swift new file mode 100644 index 0000000..4c06f71 --- /dev/null +++ b/Sources/MarbleDiagram/Job.swift @@ -0,0 +1,24 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import CMarableDiagram + +struct Job: Hashable, @unchecked Sendable { + let job: JobRef + + init(_ job: JobRef) { + self.job = job + } + + func execute() { + _swiftJobRun(unsafeBitCast(job, to: UnownedJob.self), MarbleDiagram.Context.executor.asUnownedSerialExecutor()) + } +} diff --git a/Sources/MarbleDiagram/MarbleDiagram.swift b/Sources/MarbleDiagram/MarbleDiagram.swift index 98b54d8..e5cd4ce 100644 --- a/Sources/MarbleDiagram/MarbleDiagram.swift +++ b/Sources/MarbleDiagram/MarbleDiagram.swift @@ -1,255 +1,18 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + import CMarableDiagram -import ClockStub - -@_silgen_name("swift_job_run") -@usableFromInline -internal func _swiftJobRun( - _ job: UnownedJob, - _ executor: UnownedSerialExecutor -) -> () - -func start_thread(_ raw: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? { - Unmanaged.fromOpaque(raw).takeRetainedValue().run() - return nil -} - -final class TaskDriver { - struct State { - var queue = [() -> Void]() - var executing = false - } - - let work: (TaskDriver) -> Void - var thread: pthread_t? - let state = ManagedCriticalState(State()) - - init(_ work: @escaping (TaskDriver) -> Void) { - self.work = work - } - - func start() { - pthread_create(&thread, nil, start_thread, - Unmanaged.passRetained(self).toOpaque()) - } - - func run() { - pthread_setname_np("Marble Diagram Clock Driver") - work(self) - } - - func join() { - pthread_join(thread!, nil) - } - - func enqueue(_ job: JobRef, _ execute: @escaping () -> Void) { - state.withCriticalRegion { state in - state.queue.append(execute) - } - } - - func drain() -> Bool { - let items: [() -> Void] = state.withCriticalRegion { state in - defer { state.queue.removeAll() } - state.executing = true - return state.queue - } - - for item in items { - item() - } - - return state.withCriticalRegion { state in - state.executing = false - return state.queue.count > 0 - } - } -} - -public protocol MarbleDiagramTest: Sendable { - var inputs: [String] { get } - var output: String { get } - - func test(_ event: (String) -> Void) async throws -} - -public protocol MarbleDiagramTheme { - func token(_ character: Character, inValue: Bool) -> MarbleDiagram.Token -} - -extension MarbleDiagramTheme where Self == MarbleDiagram.ASCIITheme { - public static var ascii: MarbleDiagram.ASCIITheme { - return MarbleDiagram.ASCIITheme() - } -} @resultBuilder public struct MarbleDiagram : Sendable { - public enum Token { - case step - case error - case finish - case beginValue - case endValue - case skip - case value(String) - } - - public struct ASCIITheme: MarbleDiagramTheme { - public func token(_ character: Character, inValue: Bool) -> MarbleDiagram.Token { - switch character { - case "-": return .step - case "^": return .error - case "|": return .finish - case "'": return inValue ? .endValue : .beginValue - case " ": return .skip - default: return .value(String(character)) - } - } - } - - struct Failure: Error, Equatable { } - - fileprivate struct Test: MarbleDiagramTest, @unchecked Sendable where Operation.Element == String { - let inputs: [String] - let sequence: Operation - let output: String - - func test(_ event: (String) -> Void) async throws { - for try await item in sequence { - event(item) - } - } - } - - enum Event { - case value(String, String.Index) - case failure(Error, String.Index) - case finish(String.Index) - - var result: Result { - switch self { - case .value(let value, _): return .success(value) - case .failure(let failure, _): return .failure(failure) - case .finish: return .success(nil) - } - } - - var index: String.Index { - switch self { - case .value(_, let index): return index - case .failure(_, let index): return index - case .finish(let index): return index - } - } - - fileprivate static func parse(_ dsl: String, theme: Theme) -> [(ManualClock.Instant, Event)] { - var emissions = [(ManualClock.Instant, Event)]() - var when = ManualClock.Instant(0) - var string: String? - - for index in dsl.indices { - let ch = dsl[index] - switch theme.token(dsl[index], inValue: string != nil) { - case .step: - if string == nil { - when += .steps(1) - } else { - string?.append(ch) - } - case .error: - if string == nil { - when += .steps(1) - emissions.append((when, .failure(Failure(), index))) - } else { - string?.append(ch) - } - case .finish: - if string == nil { - when += .steps(1) - emissions.append((when, .finish(index))) - } else { - string?.append(ch) - } - case .beginValue: - string = "" - case .endValue: - if let value = string { - string = nil - when += .steps(1) - emissions.append((when, .value(value, index))) - } - case .skip: - string?.append(ch) - continue - case .value(let str): - if string == nil { - when += .steps(1) - emissions.append((when, .value(String(ch), index))) - } else { - string?.append(str) - } - } - } - return emissions - } - - } - - public struct Input: AsyncSequence, Sendable { - public typealias Element = String - - fileprivate struct State { - var emissions = [(ManualClock.Instant, Event)]() - } - - fileprivate let state = ManagedCriticalState(State()) - fileprivate let clock: ManualClock - - public struct Iterator: AsyncIteratorProtocol { - fileprivate let state: ManagedCriticalState - fileprivate let clock: ManualClock - - public mutating func next() async throws -> Element? { - let next = state.withCriticalRegion { state -> (ManualClock.Instant, Event)? in - guard state.emissions.count > 0 else { - return nil - } - return state.emissions.removeFirst() - } - guard let next = next else { - return nil - } - try? await clock.sleep(until: next.0) - return try next.1.result.get() - } - } - - public func makeAsyncIterator() -> Iterator { - Iterator(state: state, clock: clock) - } - - func parse(_ dsl: String, theme: Theme) { - let emissions = Event.parse(dsl, theme: theme) - state.withCriticalRegion { state in - state.emissions = emissions - } - } - - var end: ManualClock.Instant? { - return state.withCriticalRegion { state in - state.emissions.map { $0.0 }.sorted().last - } - } - } - - public struct Clock { - fileprivate let manualClock: ManualClock - - fileprivate init(_ manualClock: ManualClock) { - self.manualClock = manualClock - } - } - public static func buildBlock( _ input: String, _ sequence: Operation, @@ -277,401 +40,16 @@ public struct MarbleDiagram : Sendable { Test(inputs: [input1, input2, input3], sequence: sequence, output: output) } - public struct InputList: RandomAccessCollection, Sendable { - fileprivate let state = ManagedCriticalState([Input]()) - fileprivate let clock: ManualClock - - public var startIndex: Int { return 0 } - public var endIndex: Int { - state.withCriticalRegion { $0.count } - } - - public subscript(position: Int) -> MarbleDiagram.Input { - get { - return state.withCriticalRegion { state in - if position >= state.count { - for _ in state.count...position { - state.append(Input(clock: clock)) - } - } - return state[position] - } - } - } - } + let queue: WorkQueue - fileprivate let manualClock: ManualClock public var inputs: InputList + public let clock: Clock - public var clock: Clock { - Clock(manualClock) - } - - internal init(_ clock: ManualClock) { - manualClock = clock - inputs = InputList(clock: clock) - } - - struct Context { - final class ClockExecutor: SerialExecutor { - func enqueue(_ job: UnownedJob) { - job._runSynchronously(on: asUnownedSerialExecutor()) - } - - func asUnownedSerialExecutor() -> UnownedSerialExecutor { - UnownedSerialExecutor(ordinary: self) - } - } - - static var clock: ManualClock? - - static let executor = ClockExecutor() - - static var driver: TaskDriver? - } - - public struct ExpectationFailure: CustomDebugStringConvertible { - public enum Kind { - case expectedFinishButGotValue(String) - case expectedMismatch(String, String) - case expectedValueButGotFinished(String) - case expectedFailureButGotValue(Error, String) - case expectedFailureButGotFinish(Error) - case expectedValueButGotFailure(String, Error) - case expectedFinishButGotFailure(Error) - case expectedValue(String) - case expectedFinish - case expectedFailure(Error) - case unexpectedValue(String) - case unexpectedFinish - case unexpectedFailure(Error) - } - public var when: ManualClock.Instant - public var kind: Kind - public var index: String.Index - public var output: String - - var reason: String { - switch kind { - case .expectedFinishButGotValue(let actual): - return "expected finish but got \"\(actual)\"" - case .expectedMismatch(let expected, let actual): - return "expected \"\(expected)\" but got \"\(actual)\"" - case .expectedValueButGotFinished(let expected): - return "expected \"\(expected)\" but got finish" - case .expectedFailureButGotValue(_, let actual): - return "expected failure but got \"\(actual)\"" - case .expectedFailureButGotFinish: - return "expected failure but got finish" - case .expectedValueButGotFailure(let expected, _): - return "expected \"\(expected)\" but got failure" - case .expectedFinishButGotFailure: - return "expected finish but got failure" - case .expectedValue(let expected): - return "expected \"\(expected)\"" - case .expectedFinish: - return "expected finish" - case .expectedFailure: - return "expected failure" - case .unexpectedValue(let actual): - return "unexpected \"\(actual)\"" - case .unexpectedFinish: - return "unexpected finish" - case .unexpectedFailure: - return "unexpected failure" - } - } - - public var description: String { - return reason + " at tick \(when.rawValue - 1)" - } - - public var debugDescription: String { - let delta = output.distance(from: output.startIndex, to: index) - let padding = String(repeating: " ", count: delta) - return output + "\n" + - padding + "^----- " + reason - } - } - - static func validate( - output: String, - theme: Theme, - expected: [ManualClock.Instant : Result], - actual: [(ManualClock.Instant, Result)] - ) -> [ExpectationFailure] { -#if false - // useful to debug the marble diagram itself - print("expected") - for (when, result) in expected.map({ $0 }).sorted(by: { lhs, rhs in - lhs.key < rhs.key - }) { - print(when.rawValue, result) - } - print("actual") - for (when, result) in actual { - print(when.rawValue, result) - } -#endif - var processed = Set() - var failures = [ExpectationFailure]() - // reparse the output to fetch indicies - let events = Event.parse(output, theme: theme).map { when, emission in - return (when, emission.index) - } - let times = events.map { $0.0 }.sorted() - let parsedOutput = Dictionary(uniqueKeysWithValues: events) - func index(for when: ManualClock.Instant) -> String.Index { - if let index = parsedOutput[when] { - return index - } - // calculate a best guess for the index - if let firstAfter = times.first(where: { $0 > when }) { - if let followingEvent = parsedOutput[firstAfter] { - if followingEvent > output.startIndex { - return output.index(before: followingEvent) - } - } - } - return output.startIndex - } - for (when, actualResult) in actual { - processed.insert(when) - if let expectedResult = expected[when] { - switch (expectedResult, actualResult) { - case (.success(let expected), .success(let actual)): - switch (expected, actual) { - case (.some(let expected), .some(let actual)): - if expected != actual { - let failure = ExpectationFailure( - when: when, - kind: .expectedMismatch(expected, actual), - index: index(for: when), - output: output) - failures.append(failure) - } - case (.none, .some(let actual)): - let failure = ExpectationFailure( - when: when, - kind: .expectedFinishButGotValue(actual), - index: index(for: when), - output: output) - failures.append(failure) - case (.some(let expected), .none): - let failure = ExpectationFailure( - when: when, - kind: .expectedValueButGotFinished(expected), - index: index(for: when), - output: output) - failures.append(failure) - case (.none, .none): - break - } - case (.failure, .failure): - break - case (.failure(let expected), .success(let actual)): - if let actual = actual { - let failure = ExpectationFailure( - when: when, - kind: .expectedFailureButGotValue(expected, actual), - index: index(for: when), - output: output) - failures.append(failure) - } else { - let failure = ExpectationFailure( - when: when, - kind: .expectedFailureButGotFinish(expected), - index: index(for: when), - output: output) - failures.append(failure) - } - case (.success(let expected), .failure(let actual)): - if let expected = expected { - let failure = ExpectationFailure( - when: when, - kind: .expectedValueButGotFailure(expected, actual), - index: index(for: when), - output: output) - failures.append(failure) - } else { - let failure = ExpectationFailure( - when: when, - kind: .expectedFinishButGotFailure(actual), - index: index(for: when), - output: output) - failures.append(failure) - } - } - } else { - switch actualResult { - case .success(let actual): - switch actual { - case .some(let actual): - let failure = ExpectationFailure( - when: when, - kind: .unexpectedValue(actual), - index: index(for: when), - output: output) - failures.append(failure) - case .none: - let failure = ExpectationFailure( - when: when, - kind: .unexpectedFinish, - index: index(for: when), - output: output) - failures.append(failure) - } - case .failure(let actual): - let failure = ExpectationFailure( - when: when, - kind: .unexpectedFailure(actual), - index: index(for: when), - output: output) - failures.append(failure) - } - } - } - - let unchecked = expected.keys.filter { !processed.contains($0) } - for when in unchecked { - guard let expectation = expected[when] else { - continue - } - switch expectation { - case .success(let expected): - switch expected { - case .some(let expected): - let failure = ExpectationFailure( - when: when, - kind: .expectedValue(expected), - index: index(for: when), - output: output) - failures.append(failure) - case .none: - let failure = ExpectationFailure( - when: when, - kind: .expectedFinish, - index: index(for: when), - output: output) - failures.append(failure) - } - case .failure(let error): - let failure = ExpectationFailure( - when: when, - kind: .expectedFailure(error), - index: index(for: when), - output: output) - failures.append(failure) - } - } - return failures - } - - public static func test( - theme: Theme, - @MarbleDiagram _ build: (inout MarbleDiagram) -> Test - ) -> [ExpectationFailure] { - let clock = ManualClock() - - var diagram = MarbleDiagram(clock) - let test = build(&diagram) - - for (index, input) in diagram.inputs.enumerated() { - input.parse(test.inputs[index], theme: theme) - } - - let parsedOutput = Event.parse(test.output, theme: theme) - let expected = Dictionary(uniqueKeysWithValues: parsedOutput.map { ($0, $1.result) }) - - guard let end = (expected.keys + diagram.inputs.compactMap { $0.end }).max() else { - return [] - } - - let actual = ManagedCriticalState([(ManualClock.Instant, Result)]()) - Context.clock = clock - // This all needs to be isolated from potential Tasks (the caller function might be async!) - Context.driver = TaskDriver { driver in - swift_task_enqueueGlobal_hook = { job, original in - Context.driver?.enqueue(job) { - _swiftJobRun(unsafeBitCast(job, to: UnownedJob.self), Context.executor.asUnownedSerialExecutor()) - } - } - - let runner = Task { - do { - try await test.test { event in - actual.withCriticalRegion { values in - values.append((clock.now, .success(event))) - } - } - actual.withCriticalRegion { values in - values.append((clock.now, .success(nil))) - } - } catch { - actual.withCriticalRegion { values in - values.append((clock.now, .failure(error))) - } - } - } - - // Drain off any initial work. Work may spawn additional work to be done. - // If the driver ever becomes blocked on the clock, exit early out of that - // drain, because the drain cant make any forward progress if it is blocked - // by a needed clock advancement. - while driver.drain() { - if clock.hasSleepers { - break - } - } - // Next make sure to iterate a decent amount past the end of the maximum - // scheduled things (that way we ensure any reasonable errors are caught) - for _ in 0..<(end.rawValue * 2) { - clock.advance() - // While the clock is not blocking any sleepers drain off any work. - while !clock.hasSleepers { - guard driver.drain() else { - break - } - } - } - - runner.cancel() - Context.clock = nil - swift_task_enqueueGlobal_hook = nil - } - Context.driver?.start() - // This is only valid since we are doing tests here - // else wise this would cause QoS inversions - Context.driver?.join() - Context.driver = nil - - return validate( - output: test.output, - theme: theme, - expected: expected, - actual: actual.withCriticalRegion { $0 }) - } - - public static func test( - @MarbleDiagram _ build: (inout MarbleDiagram) -> Test - ) -> [ExpectationFailure] { - self.test(theme: .ascii, build) + internal init() { + let queue = WorkQueue() + self.queue = queue + self.inputs = InputList(queue: queue) + self.clock = Clock(queue: queue) } } -extension MarbleDiagram.Clock: Clock { - public var now: ManualClock.Instant { - manualClock.now - } - - public var minimumResolution: ManualClock.Step { - manualClock.minimumResolution - } - - public func sleep( - until deadline: ManualClock.Instant, - tolerance: ManualClock.Step? = nil - ) async throws { - try await manualClock.sleep(until: deadline, tolerance: tolerance) - } -} diff --git a/Sources/MarbleDiagram/TaskDriver.swift b/Sources/MarbleDiagram/TaskDriver.swift new file mode 100644 index 0000000..42876b1 --- /dev/null +++ b/Sources/MarbleDiagram/TaskDriver.swift @@ -0,0 +1,61 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import CMarableDiagram + +#if canImport(Darwin) +@_implementationOnly import Darwin +#elseif canImport(Glibc) +@_implementationOnly import Glibc +#elseif canImport(WinSDK) +#error("TODO: Port TaskDriver threading to windows") +#endif + +func start_thread(_ raw: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? { + Unmanaged.fromOpaque(raw).takeRetainedValue().run() + return nil +} + +final class TaskDriver { + let work: (TaskDriver) -> Void + let queue: WorkQueue + var thread: pthread_t? + + init(queue: WorkQueue, _ work: @escaping (TaskDriver) -> Void) { + self.queue = queue + self.work = work + } + + func start() { + pthread_create(&thread, nil, start_thread, + Unmanaged.passRetained(self).toOpaque()) + } + + func run() { + pthread_setname_np("Marble Diagram Clock Driver") + work(self) + } + + func join() { + pthread_join(thread!, nil) + } + + func enqueue(_ job: JobRef) { + let job = Job(job) + queue.enqueue(MarbleDiagram.Context.currentJob) { + let previous = MarbleDiagram.Context.currentJob + MarbleDiagram.Context.currentJob = job + job.execute() + MarbleDiagram.Context.currentJob = previous + } + } +} + diff --git a/Sources/MarbleDiagram/Test.swift b/Sources/MarbleDiagram/Test.swift new file mode 100644 index 0000000..d1f8860 --- /dev/null +++ b/Sources/MarbleDiagram/Test.swift @@ -0,0 +1,290 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import CMarableDiagram + +@_silgen_name("swift_job_run") +@usableFromInline +internal func _swiftJobRun( + _ job: UnownedJob, + _ executor: UnownedSerialExecutor +) -> () + +public protocol MarbleDiagramTest: Sendable { + var inputs: [String] { get } + var output: String { get } + + func test(_ event: (String) -> Void) async throws +} + +extension MarbleDiagram { + struct Test: MarbleDiagramTest, @unchecked Sendable where Operation.Element == String { + let inputs: [String] + let sequence: Operation + let output: String + + func test(_ event: (String) -> Void) async throws { + for try await item in sequence { + event(item) + } + } + } + + struct Context { + final class ClockExecutor: SerialExecutor { + func enqueue(_ job: UnownedJob) { + job._runSynchronously(on: asUnownedSerialExecutor()) + } + + func asUnownedSerialExecutor() -> UnownedSerialExecutor { + UnownedSerialExecutor(ordinary: self) + } + } + + static var clock: Clock? + + static let executor = ClockExecutor() + + static var driver: TaskDriver? + + static var currentJob: Job? + } + + enum ActualResult { + case success(String?) + case failure(Error) + case none + + init(_ result: Result?) { + if let result = result { + switch result { + case .success(let value): + self = .success(value) + case .failure(let error): + self = .failure(error) + } + } else { + self = .none + } + } + } + + static func validate( + output: String, + theme: Theme, + expected: [(Clock.Instant, Result)], + actual: [(Clock.Instant, Result)] + ) -> (ExpectationResult, [ExpectationFailure]) { + let result = ExpectationResult(expected: expected, actual: actual) + var failures = [ExpectationFailure]() + + let actualTimes = actual.map { when, _ in when } + let expectedTimes = expected.map { when, _ in when } + + var expectedMap = [Clock.Instant: [Result]]() + var actualMap = [Clock.Instant: [Result]]() + + for (when, result) in expected { + expectedMap[when, default: []].append(result) + } + + for (when, result) in actual { + actualMap[when, default: []].append(result) + } + + let allTimes = Set(actualTimes + expectedTimes).sorted() + for when in allTimes { + let expectedResults = expectedMap[when] ?? [] + let actualResults = actualMap[when] ?? [] + var expectedIterator = expectedResults.makeIterator() + var actualIterator = actualResults.makeIterator() + while let expectedResult = expectedIterator.next() { + let actualResult = ActualResult(actualIterator.next()) + switch (expectedResult, actualResult) { + case (.success(let expected), .success(let actual)): + switch (expected, actual) { + case (.some(let expected), .some(let actual)): + if expected != actual { + let failure = ExpectationFailure( + when: when, + kind: .expectedMismatch(expected, actual)) + failures.append(failure) + } + case (.none, .some(let actual)): + let failure = ExpectationFailure( + when: when, + kind: .expectedFinishButGotValue(actual)) + failures.append(failure) + case (.some(let expected), .none): + let failure = ExpectationFailure( + when: when, + kind: .expectedValueButGotFinished(expected)) + failures.append(failure) + case (.none, .none): + break + } + case (.success(let expected), .failure(let actual)): + if let expected = expected { + let failure = ExpectationFailure( + when: when, + kind: .expectedValueButGotFailure(expected, actual)) + failures.append(failure) + } else { + let failure = ExpectationFailure( + when: when, + kind: .expectedFinishButGotFailure(actual)) + failures.append(failure) + } + case (.success(let expected), .none): + switch expected { + case .some(let expected): + let failure = ExpectationFailure( + when: when, + kind: .expectedValue(expected)) + failures.append(failure) + case .none: + let failure = ExpectationFailure( + when: when, + kind: .expectedFinish) + failures.append(failure) + } + case (.failure(let expected), .success(let actual)): + if let actual = actual { + let failure = ExpectationFailure( + when: when, + kind: .expectedFailureButGotValue(expected, actual)) + failures.append(failure) + } else { + let failure = ExpectationFailure( + when: when, + kind: .expectedFailureButGotFinish(expected)) + failures.append(failure) + } + case (.failure, .failure): + break + case (.failure(let expected), .none): + let failure = ExpectationFailure( + when: when, + kind: .expectedFailure(expected)) + failures.append(failure) + } + } + while let unexpectedResult = actualIterator.next() { + switch unexpectedResult { + case .success(let actual): + switch actual { + case .some(let actual): + let failure = ExpectationFailure( + when: when, + kind: .unexpectedValue(actual)) + failures.append(failure) + case .none: + let failure = ExpectationFailure( + when: when, + kind: .unexpectedFinish) + failures.append(failure) + } + case .failure(let actual): + let failure = ExpectationFailure( + when: when, + kind: .unexpectedFailure(actual)) + failures.append(failure) + } + } + } + + return (result, failures) + } + + public static func test( + theme: Theme, + @MarbleDiagram _ build: (inout MarbleDiagram) -> Test + ) throws -> (ExpectationResult, [ExpectationFailure]) { + var diagram = MarbleDiagram() + let clock = diagram.clock + let test = build(&diagram) + + for (index, input) in diagram.inputs.enumerated() { + try input.parse(test.inputs[index], theme: theme) + } + + let parsedOutput = try Event.parse(test.output, theme: theme) + var expected = [(Clock.Instant, Result)]() + for (when, event) in parsedOutput { + for result in event.results { + expected.append((when, result)) + } + } + let times = parsedOutput.map { when, _ in when } + + guard let end = (times + diagram.inputs.compactMap { $0.end }).max() else { + return (ExpectationResult(expected: [], actual: []), []) + } + + let actual = ManagedCriticalState([(Clock.Instant, Result)]()) + Context.clock = clock + // This all needs to be isolated from potential Tasks (the caller function might be async!) + Context.driver = TaskDriver(queue: diagram.queue) { driver in + swift_task_enqueueGlobal_hook = { job, original in + Context.driver?.enqueue(job) + } + + let runner = Task { + do { + try await test.test { event in + actual.withCriticalRegion { values in + values.append((clock.now, .success(event))) + } + } + actual.withCriticalRegion { values in + values.append((clock.now, .success(nil))) + } + } catch { + actual.withCriticalRegion { values in + values.append((clock.now, .failure(error))) + } + } + } + + // Drain off any initial work. Work may spawn additional work to be done. + // If the driver ever becomes blocked on the clock, exit early out of that + // drain, because the drain cant make any forward progress if it is blocked + // by a needed clock advancement. + diagram.queue.drain() + // Next make sure to iterate a decent amount past the end of the maximum + // scheduled things (that way we ensure any reasonable errors are caught) + for _ in 0..<(end.when.rawValue * 2) { + diagram.queue.advance() + } + + runner.cancel() + Context.clock = nil + swift_task_enqueueGlobal_hook = nil + } + Context.driver?.start() + // This is only valid since we are doing tests here + // else wise this would cause QoS inversions + Context.driver?.join() + Context.driver = nil + + return validate( + output: test.output, + theme: theme, + expected: expected, + actual: actual.withCriticalRegion { $0 }) + } + + public static func test( + @MarbleDiagram _ build: (inout MarbleDiagram) -> Test + ) throws -> (ExpectationResult, [ExpectationFailure]) { + try self.test(theme: .ascii, build) + } +} diff --git a/Sources/MarbleDiagram/Theme.swift b/Sources/MarbleDiagram/Theme.swift new file mode 100644 index 0000000..720f87b --- /dev/null +++ b/Sources/MarbleDiagram/Theme.swift @@ -0,0 +1,49 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +public protocol MarbleDiagramTheme { + func token(_ character: Character, inValue: Bool) -> MarbleDiagram.Token +} + +extension MarbleDiagramTheme where Self == MarbleDiagram.ASCIITheme { + public static var ascii: MarbleDiagram.ASCIITheme { + return MarbleDiagram.ASCIITheme() + } +} + +extension MarbleDiagram { + public enum Token { + case step + case error + case finish + case beginValue + case endValue + case beginGroup + case endGroup + case skip + case value(String) + } + + public struct ASCIITheme: MarbleDiagramTheme { + public func token(_ character: Character, inValue: Bool) -> MarbleDiagram.Token { + switch character { + case "-": return .step + case "^": return .error + case "|": return .finish + case "'": return inValue ? .endValue : .beginValue + case "[": return .beginGroup + case "]": return .endGroup + case " ": return .skip + default: return .value(String(character)) + } + } + } +} diff --git a/Sources/MarbleDiagram/WorkQueue.swift b/Sources/MarbleDiagram/WorkQueue.swift new file mode 100644 index 0000000..aebfcd4 --- /dev/null +++ b/Sources/MarbleDiagram/WorkQueue.swift @@ -0,0 +1,299 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +struct WorkQueue: Sendable { + enum Item: CustomStringConvertible, Comparable { + case blocked(Token, MarbleDiagram.Clock.Instant, UnsafeContinuation) + case emit(Token, MarbleDiagram.Clock.Instant, UnsafeContinuation, Result, Int) + case work(Token, @Sendable () -> Void) + case cancelled(Token) + + func run() { + switch self { + case .blocked(_, _, let continuation): + continuation.resume() + case .emit(_, _, let continuation, let result, _): + continuation.resume(with: result) + case .work(_, let work): + work() + case .cancelled: + break + } + } + + var description: String { + switch self { + case .blocked(let token, let when, _): + return "wakeup #\(token) @\(when) " + case .emit(let token, let when, _, let result, let side): + return "emit #\(token) @\(when) result \(result) side \(side)" + case .work(let token, _): + return "work #\(token)" + case .cancelled(let token): + return "cancelled #\(token)" + } + } + + var token: Token { + switch self { + case .blocked(let token, _, _): return token + case .emit(let token, _, _, _, _): return token + case .work(let token, _): return token + case .cancelled(let token): return token + } + } + + var isCancelled: Bool { + switch self { + case .cancelled: return true + default: return false + } + } + + func cancelling() -> Item { + switch self { + case .blocked(let token, _, let continuation): + return .work(token) { + continuation.resume(throwing: CancellationError()) + } + case .emit(let token, _, let continuation, _, _): + return .work(token) { + continuation.resume(returning: nil) + } + default: return self + } + } + + // the side order is repsected first since that is the logical flow of predictable events + // then the generation is taken into account + static func < (_ lhs: Item, _ rhs: Item) -> Bool { + switch (lhs, rhs) { + case (.emit(_, _, _, _, let lhs), .emit(_, _, _, _, let rhs)): + return lhs < rhs + default: + return lhs.token.generation < rhs.token.generation + } + } + + // all tokens are distinct so we know the generation of when it was enqueued + // always means distinct equality (for ordering) + static func == (_ lhs: Item, _ rhs: Item) -> Bool { + return lhs.token == rhs.token + } + } + + struct State { + // the nil Job in these two structures represent the root job in the TaskDriver + var queues = [Job? : [Item]]() + var jobs: [Job?] = [nil] + var items = [Token : Item]() + + var now = MarbleDiagram.Clock.Instant(when: .zero) + var generation = 0 + + mutating func drain() -> [Item] { + var items = [Item]() + // store off the jobs such that we can only visit the active queues + var jobs = self.jobs + + while true { + let startingCount = items.count + var jobsToRemove = Set() + // iterate in order of the jobs from when they have been seen + // the dictionary is not ordered for its keys so make sure we iterate stably + for jobIndex in 0.. Token { + state.withCriticalRegion { state in + defer { state.generation += 1 } + return Token(generation: state.generation) + } + } + + func cancel(_ token: Token) { + state.withCriticalRegion { state in + if let existing = state.items[token] { + // find any existing items that are present and patch them up as cancelled + let item = existing.cancelling() + state.items[token] = item + for (job, var queue) in state.queues { + var finished = false + for index in 0.., token: Token) { + state.withCriticalRegion { state in + if state.queues[job] == nil, let job = job { + state.jobs.append(job) + } + if state.items[token]?.isCancelled == true { + let item: Item = .work(token, { + continuation.resume(throwing: CancellationError()) + }) + state.queues[job, default: []].append(item) + state.items[token] = item + } else { + let item: Item = .blocked(token, deadline, continuation) + state.queues[job, default: []].append(item) + state.items[token] = item + } + } + } + + func enqueue(_ job: Job?, deadline: MarbleDiagram.Clock.Instant, continuation: UnsafeContinuation, _ result: Result, index: Int, token: Token) { + state.withCriticalRegion { state in + if state.queues[job] == nil, let job = job { + state.jobs.append(job) + } + if state.items[token]?.isCancelled == true { + let item: Item = .work(token, { + continuation.resume(throwing: CancellationError()) + }) + state.queues[job, default: []].append(item) + state.items[token] = item + } else { + let item: Item = .emit(token, deadline, continuation, result, index) + state.queues[job, default: []].append(item) + state.items[token] = item + } + } + } + + func enqueue(_ job: Job?, work: @Sendable @escaping () -> Void) { + state.withCriticalRegion { state in + if state.queues[job] == nil, let job = job { + state.jobs.append(job) + } + let token = Token(generation: state.generation) + let item: Item = .work(token, work) + state.queues[job, default: []].append(item) + state.generation += 1 + state.items[token] = item + } + } + + func drain() { + // keep draining until there is no recursive work to do + while true { + var items: [Item] = state.withCriticalRegion { $0.drain() } + if items.count == 0 { + break + } + // ensure deterministic order of execution + // first by source order, then by enqueue order + items.sort() + for item in items { + item.run() + } + } + } + + func advance() { + // drain off the advancement + var items: [Item] = state.withCriticalRegion { state in + state.now = state.now.advanced(by: .steps(1)) + return state.drain() + } + // ensure deterministic order of execution + // first by source order, then by enqueue order + items.sort() + for item in items { + item.run() + } + + // and cleanup any additional recursive items + drain() + } +} diff --git a/Sources/MarbleDiagram/ManualClock.swift b/Tests/AsyncAlgorithmsTests/Support/ManualClock.swift similarity index 99% rename from Sources/MarbleDiagram/ManualClock.swift rename to Tests/AsyncAlgorithmsTests/Support/ManualClock.swift index eb48f86..6704b39 100644 --- a/Sources/MarbleDiagram/ManualClock.swift +++ b/Tests/AsyncAlgorithmsTests/Support/ManualClock.swift @@ -185,7 +185,7 @@ public struct ManualClock: Clock { public func advance() { let pending = state.withCriticalRegion { state -> Set in - state.now += .steps(1) + state.now = state.now.advanced(by: .steps(1)) let pending = state.scheduled.filter { item in if let deadline = item.deadline { return deadline <= state.now diff --git a/Tests/AsyncAlgorithmsTests/Support/MarbleDiagram.swift b/Tests/AsyncAlgorithmsTests/Support/MarbleDiagram.swift index 1922118..9f84ba2 100644 --- a/Tests/AsyncAlgorithmsTests/Support/MarbleDiagram.swift +++ b/Tests/AsyncAlgorithmsTests/Support/MarbleDiagram.swift @@ -17,10 +17,25 @@ extension XCTestCase { public func marbleDiagram(theme: Theme, @MarbleDiagram _ build: (inout MarbleDiagram) -> Test, file: StaticString = #file, line: UInt = #line) { let location = XCTSourceCodeLocation(filePath: file.description, lineNumber: Int(line)) let context = XCTSourceCodeContext(location: location) - for failure in MarbleDiagram.test(theme: theme, build) { - let issue = XCTIssue(type: .assertionFailure, compactDescription: failure.description, detailedDescription: failure.debugDescription, sourceCodeContext: context, associatedError: nil, attachments: []) + do { + let (result, failures) = try MarbleDiagram.test(theme: theme, build) + if failures.count > 0 { + print("Expected") + for (when, result) in result.expected { + print(when, result) + } + print("Actual") + for (when, result) in result.actual { + print(when, result) + } + } + for failure in failures { + let issue = XCTIssue(type: .assertionFailure, compactDescription: failure.description, detailedDescription: nil, sourceCodeContext: context, associatedError: nil, attachments: []) + record(issue) + } + } catch { + let issue = XCTIssue(type: .system, compactDescription: "\(error)", detailedDescription: nil, sourceCodeContext: context, associatedError: nil, attachments: []) record(issue) - print(failure.debugDescription) } } diff --git a/Tests/AsyncAlgorithmsTests/TestCombineLatest.swift b/Tests/AsyncAlgorithmsTests/TestCombineLatest.swift index c14012e..b468432 100644 --- a/Tests/AsyncAlgorithmsTests/TestCombineLatest.swift +++ b/Tests/AsyncAlgorithmsTests/TestCombineLatest.swift @@ -11,7 +11,6 @@ import XCTest import AsyncAlgorithms -import MarbleDiagram final class TestCombineLatest2: XCTestCase { func test_combineLatest() async { diff --git a/Tests/AsyncAlgorithmsTests/TestManualClock.swift b/Tests/AsyncAlgorithmsTests/TestManualClock.swift index ee0cb21..045ba2d 100644 --- a/Tests/AsyncAlgorithmsTests/TestManualClock.swift +++ b/Tests/AsyncAlgorithmsTests/TestManualClock.swift @@ -11,7 +11,6 @@ import XCTest import AsyncAlgorithms -import MarbleDiagram final class TestManualClock: XCTestCase { func test_sleep() async { @@ -20,7 +19,7 @@ final class TestManualClock: XCTestCase { let afterSleep = expectation(description: "after sleep") let state = ManagedCriticalState(false) Task { - try await clock.sleep(until: start + .steps(3)) + try await clock.sleep(until: start.advanced(by: .steps(3))) state.withCriticalRegion { $0 = true } afterSleep.fulfill() } @@ -42,7 +41,7 @@ final class TestManualClock: XCTestCase { let failure = ManagedCriticalState(nil) let task = Task { do { - try await clock.sleep(until: start + .steps(3)) + try await clock.sleep(until: start.advanced(by: .steps(3))) } catch { failure.withCriticalRegion { $0 = error } } @@ -65,7 +64,7 @@ final class TestManualClock: XCTestCase { let failure = ManagedCriticalState(nil) let task = Task { do { - try await clock.sleep(until: start + .steps(3)) + try await clock.sleep(until: start.advanced(by: .steps(3))) } catch { failure.withCriticalRegion { $0 = error } } diff --git a/Tests/AsyncAlgorithmsTests/TestMarbleDiagram.swift b/Tests/AsyncAlgorithmsTests/TestMarbleDiagram.swift index e8727f4..8f95e97 100644 --- a/Tests/AsyncAlgorithmsTests/TestMarbleDiagram.swift +++ b/Tests/AsyncAlgorithmsTests/TestMarbleDiagram.swift @@ -54,6 +54,22 @@ final class TestMarbleDiagram: XCTestCase { } } + func test_diagram_grouping_source() { + marbleDiagram { + "[abc]def|" + $0.inputs[0] + "[abc]def|" + } + } + + func test_diagram_groups_of_one() { + marbleDiagram { + " a b c def|" + $0.inputs[0] + "[a][b][c]def|" + } + } + func test_diagram_emoji() { struct EmojiTokens: MarbleDiagramTheme { func token(_ character: Character, inValue: Bool) -> MarbleDiagram.Token { @@ -181,4 +197,31 @@ final class TestMarbleDiagram: XCTestCase { "A--B---|" } } + + func test_diagram_parse_failure_unbalanced_group() { + expectFailures(["marble diagram unbalanced grouping"]) + marbleDiagram { + " ab|" + $0.inputs[0] + "[ab|" + } + } + + func test_diagram_parse_failure_nested_group() { + expectFailures(["marble diagram nested grouping"]) + marbleDiagram { + " ab|" + $0.inputs[0] + "[[ab|" + } + } + + func test_diagram_parse_failure_step_in_group() { + expectFailures(["marble diagram step symbol in group"]) + marbleDiagram { + " ab|" + $0.inputs[0] + "[a-]b|" + } + } } diff --git a/Tests/AsyncAlgorithmsTests/TestValidator.swift b/Tests/AsyncAlgorithmsTests/TestValidator.swift index cf04928..9c5ef9c 100644 --- a/Tests/AsyncAlgorithmsTests/TestValidator.swift +++ b/Tests/AsyncAlgorithmsTests/TestValidator.swift @@ -11,7 +11,6 @@ import XCTest import AsyncAlgorithms -import MarbleDiagram final class TestValidator: XCTestCase { func test_gate() async {