mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-29 04:54:21 +00:00
Apply formatting
This commit is contained in:
1 parent
ba33a225e9
commit
d5b49aab17
97 files changed
+5078
-4440
No files matched your search
@@ -12,71 +12,114 @@
|
||||
import _CAsyncSequenceValidationSupport
|
||||
|
||||
@resultBuilder
|
||||
public struct AsyncSequenceValidationDiagram : Sendable {
|
||||
public struct AsyncSequenceValidationDiagram: Sendable {
|
||||
public struct Component<T> {
|
||||
var component: T
|
||||
var location: SourceLocation
|
||||
}
|
||||
|
||||
|
||||
public struct AccumulatedInputs {
|
||||
var inputs: [Specification] = []
|
||||
}
|
||||
|
||||
|
||||
public struct AccumulatedInputsWithOperation<Operation: AsyncSequence> where Operation.Element == String {
|
||||
var inputs: [Specification]
|
||||
var operation: Operation
|
||||
}
|
||||
|
||||
public static func buildExpression(_ expr: String, file: StaticString = #file, line: UInt = #line) -> Component<String> {
|
||||
|
||||
public static func buildExpression(
|
||||
_ expr: String,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) -> Component<String> {
|
||||
Component(component: expr, location: SourceLocation(file: file, line: line))
|
||||
}
|
||||
|
||||
public static func buildExpression<S: AsyncSequence>(_ expr: S, file: StaticString = #file, line: UInt = #line) -> Component<S> {
|
||||
|
||||
public static func buildExpression<S: AsyncSequence>(
|
||||
_ expr: S,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) -> Component<S> {
|
||||
Component(component: expr, location: SourceLocation(file: file, line: line))
|
||||
}
|
||||
|
||||
|
||||
public static func buildPartialBlock(first input: Component<String>) -> AccumulatedInputs {
|
||||
return AccumulatedInputs(inputs: [Specification(specification: input.component, location: input.location)])
|
||||
}
|
||||
|
||||
public static func buildPartialBlock<Operation: AsyncSequence>(first operation: Component<Operation>) -> AccumulatedInputsWithOperation<Operation> where Operation.Element == String {
|
||||
|
||||
public static func buildPartialBlock<Operation: AsyncSequence>(
|
||||
first operation: Component<Operation>
|
||||
) -> AccumulatedInputsWithOperation<Operation> where Operation.Element == String {
|
||||
return AccumulatedInputsWithOperation(inputs: [], operation: operation.component)
|
||||
}
|
||||
|
||||
public static func buildPartialBlock(accumulated: AccumulatedInputs, next input: Component<String>) -> AccumulatedInputs {
|
||||
return AccumulatedInputs(inputs: accumulated.inputs + [Specification(specification: input.component, location: input.location)])
|
||||
|
||||
public static func buildPartialBlock(
|
||||
accumulated: AccumulatedInputs,
|
||||
next input: Component<String>
|
||||
) -> AccumulatedInputs {
|
||||
return AccumulatedInputs(
|
||||
inputs: accumulated.inputs + [Specification(specification: input.component, location: input.location)]
|
||||
)
|
||||
}
|
||||
|
||||
public static func buildPartialBlock<Operation: AsyncSequence>(accumulated: AccumulatedInputs, next operation: Component<Operation>) -> AccumulatedInputsWithOperation<Operation> {
|
||||
|
||||
public static func buildPartialBlock<Operation: AsyncSequence>(
|
||||
accumulated: AccumulatedInputs,
|
||||
next operation: Component<Operation>
|
||||
) -> AccumulatedInputsWithOperation<Operation> {
|
||||
return AccumulatedInputsWithOperation(inputs: accumulated.inputs, operation: operation.component)
|
||||
}
|
||||
|
||||
public static func buildPartialBlock<Operation: AsyncSequence>(accumulated: AccumulatedInputsWithOperation<Operation>, next output: Component<String>) -> some AsyncSequenceValidationTest {
|
||||
return Test(inputs: accumulated.inputs, sequence: accumulated.operation, output: Specification(specification: output.component, location: output.location))
|
||||
|
||||
public static func buildPartialBlock<Operation: AsyncSequence>(
|
||||
accumulated: AccumulatedInputsWithOperation<Operation>,
|
||||
next output: Component<String>
|
||||
) -> some AsyncSequenceValidationTest {
|
||||
return Test(
|
||||
inputs: accumulated.inputs,
|
||||
sequence: accumulated.operation,
|
||||
output: Specification(specification: output.component, location: output.location)
|
||||
)
|
||||
}
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(_ sequence: Component<Operation>, _ output: Component<String>) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(
|
||||
_ sequence: Component<Operation>,
|
||||
_ output: Component<String>
|
||||
) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
let part1 = buildPartialBlock(first: sequence)
|
||||
let part2 = buildPartialBlock(accumulated: part1, next: output)
|
||||
return part2
|
||||
}
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(_ input1: Component<String>, _ sequence: Component<Operation>, _ output: Component<String>) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(
|
||||
_ input1: Component<String>,
|
||||
_ sequence: Component<Operation>,
|
||||
_ output: Component<String>
|
||||
) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
let part1 = buildPartialBlock(first: input1)
|
||||
let part2 = buildPartialBlock(accumulated: part1, next: sequence)
|
||||
let part3 = buildPartialBlock(accumulated: part2, next: output)
|
||||
return part3
|
||||
}
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(_ input1: Component<String>, _ input2: Component<String>, _ sequence: Component<Operation>, _ output: Component<String>) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(
|
||||
_ input1: Component<String>,
|
||||
_ input2: Component<String>,
|
||||
_ sequence: Component<Operation>,
|
||||
_ output: Component<String>
|
||||
) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
let part1 = buildPartialBlock(first: input1)
|
||||
let part2 = buildPartialBlock(accumulated: part1, next: input2)
|
||||
let part3 = buildPartialBlock(accumulated: part2, next: sequence)
|
||||
let part4 = buildPartialBlock(accumulated: part3, next: output)
|
||||
return part4
|
||||
}
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(_ input1: Component<String>, _ input2: Component<String>, _ input3: Component<String>, _ sequence: Component<Operation>, _ output: Component<String>) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(
|
||||
_ input1: Component<String>,
|
||||
_ input2: Component<String>,
|
||||
_ input3: Component<String>,
|
||||
_ sequence: Component<Operation>,
|
||||
_ output: Component<String>
|
||||
) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
let part1 = buildPartialBlock(first: input1)
|
||||
let part2 = buildPartialBlock(accumulated: part1, next: input2)
|
||||
let part3 = buildPartialBlock(accumulated: part2, next: input3)
|
||||
@@ -84,8 +127,15 @@ public struct AsyncSequenceValidationDiagram : Sendable {
|
||||
let part5 = buildPartialBlock(accumulated: part4, next: output)
|
||||
return part5
|
||||
}
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(_ input1: Component<String>, _ input2: Component<String>, _ input3: Component<String>, _ input4: Component<String>, _ sequence: Component<Operation>, _ output: Component<String>) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
|
||||
public static func buildBlock<Operation: AsyncSequence>(
|
||||
_ input1: Component<String>,
|
||||
_ input2: Component<String>,
|
||||
_ input3: Component<String>,
|
||||
_ input4: Component<String>,
|
||||
_ sequence: Component<Operation>,
|
||||
_ output: Component<String>
|
||||
) -> some AsyncSequenceValidationTest where Operation.Element == String {
|
||||
let part1 = buildPartialBlock(first: input1)
|
||||
let part2 = buildPartialBlock(accumulated: part1, next: input2)
|
||||
let part3 = buildPartialBlock(accumulated: part2, next: input3)
|
||||
@@ -94,17 +144,17 @@ public struct AsyncSequenceValidationDiagram : Sendable {
|
||||
let part6 = buildPartialBlock(accumulated: part5, next: output)
|
||||
return part6
|
||||
}
|
||||
|
||||
|
||||
let queue: WorkQueue
|
||||
let _clock: Clock
|
||||
|
||||
|
||||
public var inputs: InputList
|
||||
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public var clock: Clock {
|
||||
_clock
|
||||
}
|
||||
|
||||
|
||||
internal init() {
|
||||
let queue = WorkQueue()
|
||||
self.queue = queue
|
||||
@@ -112,4 +162,3 @@ public struct AsyncSequenceValidationDiagram : Sendable {
|
||||
self._clock = Clock(queue: queue)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,19 +14,18 @@ import AsyncAlgorithms
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public struct Clock {
|
||||
let queue: WorkQueue
|
||||
|
||||
|
||||
init(queue: WorkQueue) {
|
||||
self.queue = queue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public protocol TestClock: Sendable {
|
||||
associatedtype Instant: TestInstant
|
||||
|
||||
|
||||
var now: Instant { get }
|
||||
|
||||
|
||||
func sleep(until deadline: Self.Instant, tolerance: Self.Instant.Duration?) async throws
|
||||
}
|
||||
|
||||
@@ -37,77 +36,77 @@ public protocol TestInstant: Equatable {
|
||||
extension AsyncSequenceValidationDiagram.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: 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
|
||||
@@ -115,7 +114,12 @@ extension AsyncSequenceValidationDiagram.Clock {
|
||||
let token = queue.prepare()
|
||||
try await withTaskCancellationHandler {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
queue.enqueue(AsyncSequenceValidationDiagram.Context.currentJob, deadline: deadline, continuation: continuation, token: token)
|
||||
queue.enqueue(
|
||||
AsyncSequenceValidationDiagram.Context.currentJob,
|
||||
deadline: deadline,
|
||||
continuation: continuation,
|
||||
token: token
|
||||
)
|
||||
}
|
||||
} onCancel: {
|
||||
queue.cancel(token)
|
||||
@@ -123,16 +127,16 @@ extension AsyncSequenceValidationDiagram.Clock {
|
||||
}
|
||||
}
|
||||
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: TestInstant { }
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: TestInstant {}
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: InstantProtocol { }
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: InstantProtocol {}
|
||||
|
||||
extension AsyncSequenceValidationDiagram.Clock: TestClock { }
|
||||
extension AsyncSequenceValidationDiagram.Clock: TestClock {}
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncSequenceValidationDiagram.Clock: Clock { }
|
||||
extension AsyncSequenceValidationDiagram.Clock: Clock {}
|
||||
|
||||
// placeholders to avoid warnings
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: Hashable { }
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: Comparable { }
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: Hashable {}
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: Comparable {}
|
||||
@@ -10,13 +10,13 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
struct Failure: Error, Equatable { }
|
||||
|
||||
struct Failure: Error, Equatable {}
|
||||
|
||||
enum ParseFailure: Error, CustomStringConvertible, SourceFailure {
|
||||
case stepInGroup(String, String.Index, SourceLocation)
|
||||
case nestedGroup(String, String.Index, SourceLocation)
|
||||
case unbalancedNesting(String, String.Index, SourceLocation)
|
||||
|
||||
|
||||
var location: SourceLocation {
|
||||
switch self {
|
||||
case .stepInGroup(_, _, let location): return location
|
||||
@@ -24,7 +24,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
case .unbalancedNesting(_, _, let location): return location
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case .stepInGroup:
|
||||
@@ -36,14 +36,14 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
enum Event {
|
||||
case value(String, String.Index)
|
||||
case failure(Error, String.Index)
|
||||
case finish(String.Index)
|
||||
case delayNext(String.Index)
|
||||
case cancel(String.Index)
|
||||
|
||||
|
||||
var results: [Result<String?, Error>] {
|
||||
switch self {
|
||||
case .value(let value, _): return [.success(value)]
|
||||
@@ -53,7 +53,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
case .cancel: return []
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var index: String.Index {
|
||||
switch self {
|
||||
case .value(_, let index): return index
|
||||
@@ -63,23 +63,26 @@ extension AsyncSequenceValidationDiagram {
|
||||
case .cancel(let index): return index
|
||||
}
|
||||
}
|
||||
|
||||
static func parse<Theme: AsyncSequenceValidationTheme>(_ dsl: String, theme: Theme, location: SourceLocation) throws -> [(Clock.Instant, Event)] {
|
||||
|
||||
static func parse<Theme: AsyncSequenceValidationTheme>(
|
||||
_ dsl: String,
|
||||
theme: Theme,
|
||||
location: SourceLocation
|
||||
) 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 {
|
||||
guard grouping == 0 else {
|
||||
throw ParseFailure.stepInGroup(dsl, index, location)
|
||||
}
|
||||
when = when.advanced(by: .steps(1))
|
||||
} else {
|
||||
string?.append(ch)
|
||||
}
|
||||
@@ -130,11 +133,10 @@ extension AsyncSequenceValidationDiagram {
|
||||
emissions.append((when, .value(value, index)))
|
||||
}
|
||||
case .beginGroup:
|
||||
if grouping == 0 {
|
||||
when = when.advanced(by: .steps(1))
|
||||
} else {
|
||||
guard grouping == 0 else {
|
||||
throw ParseFailure.nestedGroup(dsl, index, location)
|
||||
}
|
||||
when = when.advanced(by: .steps(1))
|
||||
grouping += 1
|
||||
case .endGroup:
|
||||
grouping -= 1
|
||||
|
||||
@@ -18,7 +18,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
public var expected: [Event]
|
||||
public var actual: [(Clock.Instant, Result<String?, Error>)]
|
||||
|
||||
|
||||
func reconstitute<Theme: AsyncSequenceValidationTheme>(_ result: Result<String?, Error>, theme: Theme) -> String {
|
||||
var reconstituted = ""
|
||||
switch result {
|
||||
@@ -39,9 +39,13 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
return reconstituted
|
||||
}
|
||||
|
||||
func reconstitute<Theme: AsyncSequenceValidationTheme>(_ events: [Clock.Instant : [Result<String?, Error>]], theme: Theme, end: Clock.Instant) -> String {
|
||||
var now = Clock.Instant(when: .steps(1)) // adjust for the offset index
|
||||
|
||||
func reconstitute<Theme: AsyncSequenceValidationTheme>(
|
||||
_ events: [Clock.Instant: [Result<String?, Error>]],
|
||||
theme: Theme,
|
||||
end: Clock.Instant
|
||||
) -> String {
|
||||
var now = Clock.Instant(when: .steps(1)) // adjust for the offset index
|
||||
var reconstituted = ""
|
||||
while now <= end {
|
||||
if let results = events[now] {
|
||||
@@ -61,11 +65,11 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
return reconstituted
|
||||
}
|
||||
|
||||
|
||||
public func reconstituteExpected<Theme: AsyncSequenceValidationTheme>(theme: Theme) -> String {
|
||||
var events = [Clock.Instant : [Result<String?, Error>]]()
|
||||
var events = [Clock.Instant: [Result<String?, Error>]]()
|
||||
var end: Clock.Instant = Clock.Instant(when: .zero)
|
||||
|
||||
|
||||
for expectation in expected {
|
||||
let when = expectation.when
|
||||
let result = expectation.result
|
||||
@@ -74,25 +78,25 @@ extension AsyncSequenceValidationDiagram {
|
||||
end = when
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return reconstitute(events, theme: theme, end: end)
|
||||
}
|
||||
|
||||
|
||||
public func reconstituteActual<Theme: AsyncSequenceValidationTheme>(theme: Theme) -> String {
|
||||
var events = [Clock.Instant : [Result<String?, Error>]]()
|
||||
var events = [Clock.Instant: [Result<String?, Error>]]()
|
||||
var end: Clock.Instant = Clock.Instant(when: .zero)
|
||||
|
||||
|
||||
for (when, result) in actual {
|
||||
events[when, default: []].append(result)
|
||||
if when > end {
|
||||
end = when
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return reconstitute(events, theme: theme, end: end)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public struct ExpectationFailure: Sendable, CustomStringConvertible {
|
||||
public enum Kind: Sendable {
|
||||
case expectedFinishButGotValue(String)
|
||||
@@ -108,23 +112,23 @@ extension AsyncSequenceValidationDiagram {
|
||||
case unexpectedValue(String)
|
||||
case unexpectedFinish
|
||||
case unexpectedFailure(Error)
|
||||
|
||||
|
||||
case specificationViolationGotValueAfterIteration(String)
|
||||
case specificationViolationGotFailureAfterIteration(Error)
|
||||
}
|
||||
public var when: Clock.Instant
|
||||
public var kind: Kind
|
||||
|
||||
|
||||
public var specification: Specification?
|
||||
public var index: String.Index?
|
||||
|
||||
|
||||
init(when: Clock.Instant, kind: Kind, specification: Specification? = nil, index: String.Index? = nil) {
|
||||
self.when = when
|
||||
self.kind = kind
|
||||
self.specification = specification
|
||||
self.index = index
|
||||
}
|
||||
|
||||
|
||||
var reason: String {
|
||||
switch kind {
|
||||
case .expectedFinishButGotValue(let actual):
|
||||
@@ -159,7 +163,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
return "specification violation got failure after iteration terminated"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public var description: String {
|
||||
return reason + " at tick \(when.when.rawValue - 1)"
|
||||
}
|
||||
|
||||
@@ -13,31 +13,31 @@ extension AsyncSequenceValidationDiagram {
|
||||
public struct Specification: Sendable {
|
||||
public let specification: String
|
||||
public let location: SourceLocation
|
||||
|
||||
|
||||
init(specification: String, location: SourceLocation) {
|
||||
self.specification = specification
|
||||
self.location = location
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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, Sendable {
|
||||
let state: ManagedCriticalState<State>
|
||||
let queue: WorkQueue
|
||||
let index: Int
|
||||
var active: (Clock.Instant, [Result<String?, Error>])?
|
||||
var eventIndex = 0
|
||||
|
||||
|
||||
mutating func apply(when: Clock.Instant, results: [Result<String?, Error>]) async throws -> Element? {
|
||||
let token = queue.prepare()
|
||||
if eventIndex + 1 >= results.count {
|
||||
@@ -52,17 +52,22 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
return try await withTaskCancellationHandler {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
queue.enqueue(Context.currentJob, deadline: when, continuation: continuation, results[eventIndex], index: index, token: token)
|
||||
queue.enqueue(
|
||||
Context.currentJob,
|
||||
deadline: when,
|
||||
continuation: continuation,
|
||||
results[eventIndex],
|
||||
index: index,
|
||||
token: token
|
||||
)
|
||||
}
|
||||
} onCancel: { [queue] in
|
||||
queue.cancel(token)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public mutating func next() async throws -> Element? {
|
||||
if let (when, results) = active {
|
||||
return try await apply(when: when, results: results)
|
||||
} else {
|
||||
guard let (when, results) = active else {
|
||||
let next = state.withCriticalRegion { state -> (Clock.Instant, Event)? in
|
||||
guard state.emissions.count > 0 else {
|
||||
return nil
|
||||
@@ -77,36 +82,37 @@ extension AsyncSequenceValidationDiagram {
|
||||
active = (when, results)
|
||||
return try await apply(when: when, results: results)
|
||||
}
|
||||
return try await apply(when: when, results: results)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func makeAsyncIterator() -> Iterator {
|
||||
Iterator(state: state, queue: queue, index: index)
|
||||
}
|
||||
|
||||
|
||||
func parse<Theme: AsyncSequenceValidationTheme>(_ dsl: String, theme: Theme, location: SourceLocation) throws {
|
||||
let emissions = try Event.parse(dsl, theme: theme, location: location)
|
||||
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) -> AsyncSequenceValidationDiagram.Input {
|
||||
get {
|
||||
return state.withCriticalRegion { state in
|
||||
|
||||
@@ -13,11 +13,11 @@ import _CAsyncSequenceValidationSupport
|
||||
|
||||
struct Job: Hashable, @unchecked Sendable {
|
||||
let job: JobRef
|
||||
|
||||
|
||||
init(_ job: JobRef) {
|
||||
self.job = job
|
||||
}
|
||||
|
||||
|
||||
func execute() {
|
||||
_swiftJobRun(unsafeBitCast(job, to: UnownedJob.self), AsyncSequenceValidationDiagram.Context.unownedExecutor)
|
||||
}
|
||||
|
||||
@@ -12,12 +12,12 @@
|
||||
public struct SourceLocation: Sendable, CustomStringConvertible {
|
||||
public var file: StaticString
|
||||
public var line: UInt
|
||||
|
||||
|
||||
public init(file: StaticString, line: UInt) {
|
||||
self.file = file
|
||||
self.line = line
|
||||
}
|
||||
|
||||
|
||||
public var description: String {
|
||||
return "\(file):\(line)"
|
||||
}
|
||||
|
||||
@@ -47,45 +47,49 @@ func start_thread(_ raw: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer {
|
||||
final class TaskDriver {
|
||||
let work: (TaskDriver) -> Void
|
||||
let queue: WorkQueue
|
||||
#if canImport(Darwin)
|
||||
#if canImport(Darwin)
|
||||
var thread: pthread_t?
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
var thread = pthread_t()
|
||||
#elseif canImport(WinSDK)
|
||||
#error("TODO: Port TaskDriver threading to windows")
|
||||
#endif
|
||||
|
||||
#elseif canImport(WinSDK)
|
||||
#error("TODO: Port TaskDriver threading to windows")
|
||||
#endif
|
||||
|
||||
init(queue: WorkQueue, _ work: @escaping (TaskDriver) -> Void) {
|
||||
self.queue = queue
|
||||
self.work = work
|
||||
}
|
||||
|
||||
|
||||
func start() {
|
||||
#if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
pthread_create(&thread, nil, start_thread,
|
||||
Unmanaged.passRetained(self).toOpaque())
|
||||
#elseif canImport(WinSDK)
|
||||
#error("TODO: Port TaskDriver threading to windows")
|
||||
#endif
|
||||
#if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
pthread_create(
|
||||
&thread,
|
||||
nil,
|
||||
start_thread,
|
||||
Unmanaged.passRetained(self).toOpaque()
|
||||
)
|
||||
#elseif canImport(WinSDK)
|
||||
#error("TODO: Port TaskDriver threading to windows")
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
func run() {
|
||||
#if canImport(Darwin)
|
||||
#if canImport(Darwin)
|
||||
pthread_setname_np("Validation Diagram Clock Driver")
|
||||
#endif
|
||||
#endif
|
||||
work(self)
|
||||
}
|
||||
|
||||
|
||||
func join() {
|
||||
#if canImport(Darwin)
|
||||
#if canImport(Darwin)
|
||||
pthread_join(thread!, nil)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
pthread_join(thread, nil)
|
||||
#elseif canImport(WinSDK)
|
||||
#error("TODO: Port TaskDriver threading to windows")
|
||||
#endif
|
||||
#elseif canImport(WinSDK)
|
||||
#error("TODO: Port TaskDriver threading to windows")
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
func enqueue(_ job: JobRef) {
|
||||
let job = Job(job)
|
||||
queue.enqueue(AsyncSequenceValidationDiagram.Context.currentJob) {
|
||||
@@ -96,4 +100,3 @@ final class TaskDriver {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,47 +17,59 @@ import AsyncAlgorithms
|
||||
internal func _swiftJobRun(
|
||||
_ job: UnownedJob,
|
||||
_ executor: UnownedSerialExecutor
|
||||
) -> ()
|
||||
)
|
||||
|
||||
public protocol AsyncSequenceValidationTest: Sendable {
|
||||
var inputs: [AsyncSequenceValidationDiagram.Specification] { get }
|
||||
var output: AsyncSequenceValidationDiagram.Specification { get }
|
||||
|
||||
func test<C: TestClock>(with clock: C, activeTicks: [C.Instant], output: AsyncSequenceValidationDiagram.Specification, _ event: (String) -> Void) async throws
|
||||
|
||||
func test<C: TestClock>(
|
||||
with clock: C,
|
||||
activeTicks: [C.Instant],
|
||||
output: AsyncSequenceValidationDiagram.Specification,
|
||||
_ event: (String) -> Void
|
||||
) async throws
|
||||
}
|
||||
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
struct Test<Operation: AsyncSequence>: AsyncSequenceValidationTest, @unchecked Sendable where Operation.Element == String {
|
||||
struct Test<Operation: AsyncSequence>: AsyncSequenceValidationTest, @unchecked Sendable
|
||||
where Operation.Element == String {
|
||||
let inputs: [Specification]
|
||||
let sequence: Operation
|
||||
let output: Specification
|
||||
|
||||
func test<C: TestClock>(with clock: C, activeTicks: [C.Instant], output: Specification, _ event: (String) -> Void) async throws {
|
||||
|
||||
func test<C: TestClock>(
|
||||
with clock: C,
|
||||
activeTicks: [C.Instant],
|
||||
output: Specification,
|
||||
_ event: (String) -> Void
|
||||
) async throws {
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
do {
|
||||
for tick in activeTicks {
|
||||
if tick != clock.now {
|
||||
try await clock.sleep(until: tick, tolerance: nil)
|
||||
}
|
||||
if let item = try await iterator.next() {
|
||||
event(item)
|
||||
} else {
|
||||
guard let item = try await iterator.next() else {
|
||||
break
|
||||
}
|
||||
event(item)
|
||||
}
|
||||
do {
|
||||
if let pastEnd = try await iterator.next(){
|
||||
if let pastEnd = try await iterator.next() {
|
||||
let failure = ExpectationFailure(
|
||||
when: Context.clock!.now,
|
||||
kind: .specificationViolationGotValueAfterIteration(pastEnd),
|
||||
specification: output)
|
||||
specification: output
|
||||
)
|
||||
Context.specificationFailures.append(failure)
|
||||
}
|
||||
} catch {
|
||||
let failure = ExpectationFailure(
|
||||
when: Context.clock!.now,
|
||||
kind: .specificationViolationGotFailureAfterIteration(error),
|
||||
specification: output)
|
||||
specification: output
|
||||
)
|
||||
Context.specificationFailures.append(failure)
|
||||
}
|
||||
} catch {
|
||||
@@ -65,9 +77,9 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct Context {
|
||||
#if swift(<5.9)
|
||||
#if swift(<5.9)
|
||||
final class ClockExecutor: SerialExecutor {
|
||||
func enqueue(_ job: UnownedJob) {
|
||||
job._runSynchronously(on: self.asUnownedSerialExecutor())
|
||||
@@ -77,24 +89,24 @@ extension AsyncSequenceValidationDiagram {
|
||||
UnownedSerialExecutor(ordinary: self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static let _executor = ClockExecutor()
|
||||
|
||||
|
||||
static var unownedExecutor: UnownedSerialExecutor {
|
||||
_executor.asUnownedSerialExecutor()
|
||||
}
|
||||
#else
|
||||
#else
|
||||
@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
|
||||
final class ClockExecutor_5_9: SerialExecutor {
|
||||
final class ClockExecutor_5_9: SerialExecutor {
|
||||
func enqueue(_ job: __owned ExecutorJob) {
|
||||
job.runSynchronously(on: asUnownedSerialExecutor())
|
||||
}
|
||||
|
||||
|
||||
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
|
||||
UnownedSerialExecutor(ordinary: self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
final class ClockExecutor_Pre5_9: SerialExecutor {
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
@available(*, deprecated, message: "Implement 'enqueue(_: __owned ExecutorJob)' instead")
|
||||
@@ -106,36 +118,33 @@ extension AsyncSequenceValidationDiagram {
|
||||
UnownedSerialExecutor(ordinary: self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static let _executor: AnyObject = {
|
||||
if #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) {
|
||||
return ClockExecutor_5_9()
|
||||
} else {
|
||||
guard #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) else {
|
||||
return ClockExecutor_Pre5_9()
|
||||
}
|
||||
return ClockExecutor_5_9()
|
||||
}()
|
||||
|
||||
|
||||
static var unownedExecutor: UnownedSerialExecutor {
|
||||
(_executor as! any SerialExecutor).asUnownedSerialExecutor()
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
static var clock: Clock?
|
||||
|
||||
|
||||
|
||||
|
||||
static var driver: TaskDriver?
|
||||
|
||||
|
||||
static var currentJob: Job?
|
||||
|
||||
|
||||
static var specificationFailures = [ExpectationFailure]()
|
||||
}
|
||||
|
||||
|
||||
enum ActualResult {
|
||||
case success(String?)
|
||||
case failure(Error)
|
||||
case none
|
||||
|
||||
|
||||
init(_ result: Result<String?, Error>?) {
|
||||
if let result = result {
|
||||
switch result {
|
||||
@@ -149,7 +158,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static func validate<Theme: AsyncSequenceValidationTheme>(
|
||||
inputs: [Specification],
|
||||
output: Specification,
|
||||
@@ -160,21 +169,21 @@ extension AsyncSequenceValidationDiagram {
|
||||
let result = ExpectationResult(expected: expected, actual: actual)
|
||||
var failures = Context.specificationFailures
|
||||
Context.specificationFailures.removeAll()
|
||||
|
||||
|
||||
let actualTimes = actual.map { when, _ in when }
|
||||
let expectedTimes = expected.map { $0.when }
|
||||
|
||||
|
||||
var expectedMap = [Clock.Instant: [ExpectationResult.Event]]()
|
||||
var actualMap = [Clock.Instant: [Result<String?, Error>]]()
|
||||
|
||||
|
||||
for event in expected {
|
||||
expectedMap[event.when, default: []].append(event)
|
||||
}
|
||||
|
||||
|
||||
for (when, result) in actual {
|
||||
actualMap[when, default: []].append(result)
|
||||
}
|
||||
|
||||
|
||||
let allTimes = Set(actualTimes + expectedTimes).sorted()
|
||||
for when in allTimes {
|
||||
let expectedResults = expectedMap[when] ?? []
|
||||
@@ -192,21 +201,24 @@ extension AsyncSequenceValidationDiagram {
|
||||
when: when,
|
||||
kind: .expectedMismatch(expected, actual),
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
}
|
||||
case (.none, .some(let actual)):
|
||||
let failure = ExpectationFailure(
|
||||
when: when,
|
||||
kind: .expectedFinishButGotValue(actual),
|
||||
specification: output)
|
||||
specification: output
|
||||
)
|
||||
failures.append(failure)
|
||||
case (.some(let expected), .none):
|
||||
let failure = ExpectationFailure(
|
||||
when: when,
|
||||
kind: .expectedValueButGotFinished(expected),
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
case (.none, .none):
|
||||
break
|
||||
@@ -217,14 +229,16 @@ extension AsyncSequenceValidationDiagram {
|
||||
when: when,
|
||||
kind: .expectedValueButGotFailure(expected, actual),
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
} else {
|
||||
let failure = ExpectationFailure(
|
||||
when: when,
|
||||
kind: .expectedFinishButGotFailure(actual),
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
}
|
||||
case (.success(let expected), .none):
|
||||
@@ -234,14 +248,16 @@ extension AsyncSequenceValidationDiagram {
|
||||
when: when,
|
||||
kind: .expectedValue(expected),
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
case .none:
|
||||
let failure = ExpectationFailure(
|
||||
when: when,
|
||||
kind: .expectedFinish,
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
}
|
||||
case (.failure(let expected), .success(let actual)):
|
||||
@@ -250,14 +266,16 @@ extension AsyncSequenceValidationDiagram {
|
||||
when: when,
|
||||
kind: .expectedFailureButGotValue(expected, actual),
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
} else {
|
||||
let failure = ExpectationFailure(
|
||||
when: when,
|
||||
kind: .expectedFailureButGotFinish(expected),
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
}
|
||||
case (.failure, .failure):
|
||||
@@ -267,7 +285,8 @@ extension AsyncSequenceValidationDiagram {
|
||||
when: when,
|
||||
kind: .expectedFailure(expected),
|
||||
specification: output,
|
||||
index: expectedEvent.offset)
|
||||
index: expectedEvent.offset
|
||||
)
|
||||
failures.append(failure)
|
||||
}
|
||||
}
|
||||
@@ -279,28 +298,31 @@ extension AsyncSequenceValidationDiagram {
|
||||
let failure = ExpectationFailure(
|
||||
when: when,
|
||||
kind: .unexpectedValue(actual),
|
||||
specification: output)
|
||||
specification: output
|
||||
)
|
||||
failures.append(failure)
|
||||
case .none:
|
||||
let failure = ExpectationFailure(
|
||||
when: when,
|
||||
kind: .unexpectedFinish,
|
||||
specification: output)
|
||||
specification: output
|
||||
)
|
||||
failures.append(failure)
|
||||
}
|
||||
case .failure(let actual):
|
||||
let failure = ExpectationFailure(
|
||||
when: when,
|
||||
kind: .unexpectedFailure(actual),
|
||||
specification: output)
|
||||
specification: output
|
||||
)
|
||||
failures.append(failure)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (result, failures)
|
||||
}
|
||||
|
||||
|
||||
public static func test<Test: AsyncSequenceValidationTest, Theme: AsyncSequenceValidationTheme>(
|
||||
theme: Theme,
|
||||
@AsyncSequenceValidationDiagram _ build: (AsyncSequenceValidationDiagram) -> Test
|
||||
@@ -312,30 +334,32 @@ extension AsyncSequenceValidationDiagram {
|
||||
// fault in all inputs
|
||||
_ = diagram.inputs[index]
|
||||
}
|
||||
|
||||
|
||||
for (index, input) in diagram.inputs.enumerated() {
|
||||
let inputSpecification = test.inputs[index]
|
||||
try input.parse(inputSpecification.specification, theme: theme, location: inputSpecification.location)
|
||||
}
|
||||
|
||||
|
||||
let parsedOutput = try Event.parse(test.output.specification, theme: theme, location: test.output.location)
|
||||
let cancelEvents = Set(parsedOutput.filter { when, event in
|
||||
switch event {
|
||||
case .cancel: return true
|
||||
default: return false
|
||||
}
|
||||
}.map { when, _ in return when })
|
||||
let cancelEvents = Set(
|
||||
parsedOutput.filter { when, event in
|
||||
switch event {
|
||||
case .cancel: return true
|
||||
default: return false
|
||||
}
|
||||
}.map { when, _ in return when }
|
||||
)
|
||||
|
||||
let activeTicks = parsedOutput.reduce(into: [Clock.Instant.init(when: .zero)]) { events, thisEvent in
|
||||
switch thisEvent {
|
||||
case (let when, .delayNext(_)):
|
||||
events.removeLast()
|
||||
events.append(when.advanced(by: .steps(1)))
|
||||
case (let when, _):
|
||||
events.append(when)
|
||||
case (let when, .delayNext(_)):
|
||||
events.removeLast()
|
||||
events.append(when.advanced(by: .steps(1)))
|
||||
case (let when, _):
|
||||
events.append(when)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var expected = [ExpectationResult.Event]()
|
||||
for (when, event) in parsedOutput {
|
||||
for result in event.results {
|
||||
@@ -343,7 +367,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
}
|
||||
let times = parsedOutput.map { when, _ in when }
|
||||
|
||||
|
||||
guard let end = (times + diagram.inputs.compactMap { $0.end }).max() else {
|
||||
return (ExpectationResult(expected: [], actual: []), [])
|
||||
}
|
||||
@@ -356,7 +380,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
swift_task_enqueueGlobal_hook = { job, original in
|
||||
Context.driver?.enqueue(job)
|
||||
}
|
||||
|
||||
|
||||
let runner = Task {
|
||||
do {
|
||||
try await test.test(with: clock, activeTicks: activeTicks, output: test.output) { event in
|
||||
@@ -373,7 +397,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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
|
||||
@@ -387,7 +411,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
diagram.queue.advance()
|
||||
}
|
||||
|
||||
|
||||
runner.cancel()
|
||||
Context.clock = nil
|
||||
swift_task_enqueueGlobal_hook = nil
|
||||
@@ -397,15 +421,16 @@ extension AsyncSequenceValidationDiagram {
|
||||
// else wise this would cause QoS inversions
|
||||
Context.driver?.join()
|
||||
Context.driver = nil
|
||||
|
||||
|
||||
return validate(
|
||||
inputs: test.inputs,
|
||||
output: test.output,
|
||||
theme: theme,
|
||||
expected: expected,
|
||||
actual: actual.withCriticalRegion { $0 })
|
||||
actual: actual.withCriticalRegion { $0 }
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
public static func test<Test: AsyncSequenceValidationTest>(
|
||||
@AsyncSequenceValidationDiagram _ build: (AsyncSequenceValidationDiagram) -> Test
|
||||
) throws -> (ExpectationResult, [ExpectationFailure]) {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
public protocol AsyncSequenceValidationTheme {
|
||||
func token(_ character: Character, inValue: Bool) -> AsyncSequenceValidationDiagram.Token
|
||||
|
||||
|
||||
func description(for token: AsyncSequenceValidationDiagram.Token) -> String
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
case skip
|
||||
case value(String)
|
||||
}
|
||||
|
||||
|
||||
public struct ASCIITheme: AsyncSequenceValidationTheme, Sendable {
|
||||
public func token(_ character: Character, inValue: Bool) -> AsyncSequenceValidationDiagram.Token {
|
||||
switch character {
|
||||
@@ -51,7 +51,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
default: return .value(String(character))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func description(for token: AsyncSequenceValidationDiagram.Token) -> String {
|
||||
switch token {
|
||||
case .step: return "-"
|
||||
|
||||
@@ -12,10 +12,16 @@
|
||||
struct WorkQueue: Sendable {
|
||||
enum Item: CustomStringConvertible, Comparable {
|
||||
case blocked(Token, AsyncSequenceValidationDiagram.Clock.Instant, UnsafeContinuation<Void, Error>)
|
||||
case emit(Token, AsyncSequenceValidationDiagram.Clock.Instant, UnsafeContinuation<String?, Error>, Result<String?, Error>, Int)
|
||||
case emit(
|
||||
Token,
|
||||
AsyncSequenceValidationDiagram.Clock.Instant,
|
||||
UnsafeContinuation<String?, Error>,
|
||||
Result<String?, Error>,
|
||||
Int
|
||||
)
|
||||
case work(Token, @Sendable () -> Void)
|
||||
case cancelled(Token)
|
||||
|
||||
|
||||
func run() {
|
||||
switch self {
|
||||
case .blocked(_, _, let continuation):
|
||||
@@ -28,7 +34,7 @@ struct WorkQueue: Sendable {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case .blocked(let token, let when, _):
|
||||
@@ -41,7 +47,7 @@ struct WorkQueue: Sendable {
|
||||
return "cancelled #\(token)"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var token: Token {
|
||||
switch self {
|
||||
case .blocked(let token, _, _): return token
|
||||
@@ -50,14 +56,14 @@ struct WorkQueue: Sendable {
|
||||
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):
|
||||
@@ -71,7 +77,7 @@ struct WorkQueue: Sendable {
|
||||
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 {
|
||||
@@ -82,28 +88,28 @@ struct WorkQueue: Sendable {
|
||||
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 queues = [Job?: [Item]]()
|
||||
var jobs: [Job?] = [nil]
|
||||
var items = [Token : Item]()
|
||||
|
||||
var items = [Token: Item]()
|
||||
|
||||
var now = AsyncSequenceValidationDiagram.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<Int>()
|
||||
@@ -160,32 +166,32 @@ struct WorkQueue: Sendable {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return items
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let state = ManagedCriticalState(State())
|
||||
|
||||
|
||||
var now: AsyncSequenceValidationDiagram.Clock.Instant {
|
||||
state.withCriticalRegion { $0.now }
|
||||
}
|
||||
|
||||
|
||||
struct Token: Hashable, CustomStringConvertible {
|
||||
var generation: Int
|
||||
|
||||
|
||||
var description: String {
|
||||
return generation.description
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func prepare() -> 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] {
|
||||
@@ -212,16 +218,24 @@ struct WorkQueue: Sendable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func enqueue(_ job: Job?, deadline: AsyncSequenceValidationDiagram.Clock.Instant, continuation: UnsafeContinuation<Void, Error>, token: Token) {
|
||||
|
||||
func enqueue(
|
||||
_ job: Job?,
|
||||
deadline: AsyncSequenceValidationDiagram.Clock.Instant,
|
||||
continuation: UnsafeContinuation<Void, Error>,
|
||||
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())
|
||||
})
|
||||
let item: Item = .work(
|
||||
token,
|
||||
{
|
||||
continuation.resume(throwing: CancellationError())
|
||||
}
|
||||
)
|
||||
state.queues[job, default: []].append(item)
|
||||
state.items[token] = item
|
||||
} else {
|
||||
@@ -231,16 +245,27 @@ struct WorkQueue: Sendable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func enqueue(_ job: Job?, deadline: AsyncSequenceValidationDiagram.Clock.Instant, continuation: UnsafeContinuation<String?, Error>, _ result: Result<String?, Error>, index: Int, token: Token) {
|
||||
|
||||
func enqueue(
|
||||
_ job: Job?,
|
||||
deadline: AsyncSequenceValidationDiagram.Clock.Instant,
|
||||
continuation: UnsafeContinuation<String?, Error>,
|
||||
_ result: Result<String?, Error>,
|
||||
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(returning: nil) // the input sequences should not throw cancellation errors
|
||||
})
|
||||
let item: Item = .work(
|
||||
token,
|
||||
{
|
||||
// the input sequences should not throw cancellation errors
|
||||
continuation.resume(returning: nil)
|
||||
}
|
||||
)
|
||||
state.queues[job, default: []].append(item)
|
||||
state.items[token] = item
|
||||
} else {
|
||||
@@ -250,7 +275,7 @@ struct WorkQueue: Sendable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func enqueue(_ job: Job?, work: @Sendable @escaping () -> Void) {
|
||||
state.withCriticalRegion { state in
|
||||
if state.queues[job] == nil, let job = job {
|
||||
@@ -263,7 +288,7 @@ struct WorkQueue: Sendable {
|
||||
state.items[token] = item
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func drain() {
|
||||
// keep draining until there is no recursive work to do
|
||||
while true {
|
||||
@@ -279,7 +304,7 @@ struct WorkQueue: Sendable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func advance() {
|
||||
// drain off the advancement
|
||||
var items: [Item] = state.withCriticalRegion { state in
|
||||
@@ -292,7 +317,7 @@ struct WorkQueue: Sendable {
|
||||
for item in items {
|
||||
item.run()
|
||||
}
|
||||
|
||||
|
||||
// and cleanup any additional recursive items
|
||||
drain()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user