Rework marble diagrams to account for task execution (#40)

* Rework marble diagrams to account for task execution

* Add marble diagram tests to validate failure paths

* Test for space no-op in marable diagram DSL

* Factor out parsing into events and generalize
This commit is contained in:
Philippe Hausler authored and GitHub committed 2022-02-14 11:50:05 -08:00
1 parent 47aa4ccba6
commit f20f7fbe85
13 files changed
+1184 -314

No files matched your search

+10 -2
View File
@@ -14,7 +14,9 @@ let package = Package(
.library(
name: "AsyncAlgorithms",
targets: ["AsyncAlgorithms"]),
.library(name: "ClockStub", type: .static, targets: ["ClockStub"])
.library(name: "ClockStub", type: .static, targets: ["ClockStub"]),
.library(name: "MarbleDiagram", targets: ["MarbleDiagram"]),
.library(name: "CMarbleDiagram", type: .static, targets: ["CMarbleDiagram"])
],
dependencies: [],
targets: [
@@ -22,8 +24,14 @@ let package = Package(
name: "AsyncAlgorithms",
dependencies: ["ClockStub"]),
.target(name: "ClockStub"),
.target(name: "MarbleDiagram", dependencies: ["CMarbleDiagram"]),
.target(name: "CMarbleDiagram",
publicHeadersPath: "Headers",
cxxSettings: [
.unsafeFlags(["-std=c++11"])
]),
.testTarget(
name: "AsyncAlgorithmsTests",
dependencies: ["AsyncAlgorithms"]),
dependencies: ["AsyncAlgorithms", "MarbleDiagram"]),
]
)
+13
View File
@@ -0,0 +1,13 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "CMarbleDiagram.h"
@@ -0,0 +1,248 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include <stdint.h>
#if !defined(__has_feature)
#define __has_feature(x) 0
#endif
#if !defined(__has_attribute)
#define __has_attribute(x) 0
#endif
#if !defined(__has_builtin)
#define __has_builtin(builtin) 0
#endif
#if !defined(__has_cpp_attribute)
#define __has_cpp_attribute(attribute) 0
#endif
// TODO: These macro definitions are duplicated in BridgedSwiftObject.h. Move
// them to a single file if we find a location that both Visibility.h and
// BridgedSwiftObject.h can import.
#if __has_feature(nullability)
// Provide macros to temporarily suppress warning about the use of
// _Nullable and _Nonnull.
# define SWIFT_BEGIN_NULLABILITY_ANNOTATIONS \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wnullability-extension\"")
# define SWIFT_END_NULLABILITY_ANNOTATIONS \
_Pragma("clang diagnostic pop")
#else
// #define _Nullable and _Nonnull to nothing if we're not being built
// with a compiler that supports them.
# define _Nullable
# define _Nonnull
# define SWIFT_BEGIN_NULLABILITY_ANNOTATIONS
# define SWIFT_END_NULLABILITY_ANNOTATIONS
#endif
#define SWIFT_MACRO_CONCAT(A, B) A ## B
#define SWIFT_MACRO_IF_0(IF_TRUE, IF_FALSE) IF_FALSE
#define SWIFT_MACRO_IF_1(IF_TRUE, IF_FALSE) IF_TRUE
#define SWIFT_MACRO_IF(COND, IF_TRUE, IF_FALSE) \
SWIFT_MACRO_CONCAT(SWIFT_MACRO_IF_, COND)(IF_TRUE, IF_FALSE)
#if __has_attribute(pure)
#define SWIFT_READONLY __attribute__((__pure__))
#else
#define SWIFT_READONLY
#endif
#if __has_attribute(const)
#define SWIFT_READNONE __attribute__((__const__))
#else
#define SWIFT_READNONE
#endif
#if __has_attribute(always_inline)
#define SWIFT_ALWAYS_INLINE __attribute__((always_inline))
#else
#define SWIFT_ALWAYS_INLINE
#endif
#if __has_attribute(noinline)
#define SWIFT_NOINLINE __attribute__((__noinline__))
#else
#define SWIFT_NOINLINE
#endif
#if __has_attribute(noreturn)
#define SWIFT_NORETURN __attribute__((__noreturn__))
#else
#define SWIFT_NORETURN
#endif
#if __has_attribute(used)
#define SWIFT_USED __attribute__((__used__))
#else
#define SWIFT_USED
#endif
#if __has_attribute(unavailable)
#define SWIFT_ATTRIBUTE_UNAVAILABLE __attribute__((__unavailable__))
#else
#define SWIFT_ATTRIBUTE_UNAVAILABLE
#endif
#if (__has_attribute(weak_import))
#define SWIFT_WEAK_IMPORT __attribute__((weak_import))
#else
#define SWIFT_WEAK_IMPORT
#endif
// Define the appropriate attributes for sharing symbols across
// image (executable / shared-library) boundaries.
//
// SWIFT_ATTRIBUTE_FOR_EXPORTS will be placed on declarations that
// are known to be exported from the current image. Typically, they
// are placed on header declarations and then inherited by the actual
// definitions.
//
// SWIFT_ATTRIBUTE_FOR_IMPORTS will be placed on declarations that
// are known to be exported from a different image. This never
// includes a definition.
//
// Getting the right attribute on a declaratioon can be pretty awkward,
// but it's necessary under the C translation model. All of this
// ceremony is familiar to Windows programmers; C/C++ programmers
// everywhere else usually don't bother, but since we have to get it
// right for Windows, we have everything set up to get it right on
// other targets as well, and doing so lets the compiler use more
// efficient symbol access patterns.
#if defined(__MACH__) || defined(__wasi__)
// On Mach-O and WebAssembly, we use non-hidden visibility. We just use
// default visibility on both imports and exports, both because these
// targets don't support protected visibility but because they don't
// need it: symbols are not interposable outside the current image
// by default.
# define SWIFT_ATTRIBUTE_FOR_EXPORTS __attribute__((__visibility__("default")))
# define SWIFT_ATTRIBUTE_FOR_IMPORTS __attribute__((__visibility__("default")))
#elif defined(__ELF__)
// On ELF, we use non-hidden visibility. For exports, we must use
// protected visibility to tell the compiler and linker that the symbols
// can't be interposed outside the current image. For imports, we must
// use default visibility because protected visibility guarantees that
// the symbol is defined in the current library, which isn't true for
// an import.
//
// The compiler does assume that the runtime and standard library can
// refer to each other's symbols as DSO-local, so it's important that
// we get this right or we can get linker errors.
# define SWIFT_ATTRIBUTE_FOR_EXPORTS __attribute__((__visibility__("protected")))
# define SWIFT_ATTRIBUTE_FOR_IMPORTS __attribute__((__visibility__("default")))
#elif defined(__CYGWIN__)
// For now, we ignore all this on Cygwin.
# define SWIFT_ATTRIBUTE_FOR_EXPORTS
# define SWIFT_ATTRIBUTE_FOR_IMPORTS
// FIXME: this #else should be some sort of #elif Windows
#else // !__MACH__ && !__ELF__
// On PE/COFF, we use dllimport and dllexport.
# define SWIFT_ATTRIBUTE_FOR_EXPORTS __declspec(dllexport)
# define SWIFT_ATTRIBUTE_FOR_IMPORTS __declspec(dllimport)
#endif
// CMake conventionally passes -DlibraryName_EXPORTS when building
// code that goes into libraryName. This isn't the best macro name,
// but it's conventional. We do have to pass it explicitly in a few
// places in the build system for a variety of reasons.
//
// Unfortunately, defined(D) is a special function you can use in
// preprocessor conditions, not a macro you can use anywhere, so we
// need to manually check for all the libraries we know about so that
// we can use them in our condition below.s
#if defined(swiftCore_EXPORTS)
#define SWIFT_IMAGE_EXPORTS_swiftCore 1
#else
#define SWIFT_IMAGE_EXPORTS_swiftCore 0
#endif
#if defined(swift_Concurrency_EXPORTS)
#define SWIFT_IMAGE_EXPORTS_swift_Concurrency 1
#else
#define SWIFT_IMAGE_EXPORTS_swift_Concurrency 0
#endif
#if defined(swift_Distributed_EXPORTS)
#define SWIFT_IMAGE_EXPORTS_swift_Distributed 1
#else
#define SWIFT_IMAGE_EXPORTS_swift_Distributed 0
#endif
#if defined(swift_Differentiation_EXPORTS)
#define SWIFT_IMAGE_EXPORTS_swift_Differentiation 1
#else
#define SWIFT_IMAGE_EXPORTS_swift_Differentiation 0
#endif
#define SWIFT_EXPORT_FROM_ATTRIBUTE(LIBRARY) \
SWIFT_MACRO_IF(SWIFT_IMAGE_EXPORTS_##LIBRARY, \
SWIFT_ATTRIBUTE_FOR_EXPORTS, \
SWIFT_ATTRIBUTE_FOR_IMPORTS)
// SWIFT_EXPORT_FROM(LIBRARY) declares something to be a C-linkage
// entity exported by the given library.
//
// SWIFT_RUNTIME_EXPORT is just SWIFT_EXPORT_FROM(swiftCore).
//
// TODO: use this in shims headers in overlays.
#if defined(__cplusplus)
#define SWIFT_EXPORT_FROM(LIBRARY) extern "C" SWIFT_EXPORT_FROM_ATTRIBUTE(LIBRARY)
#define SWIFT_EXPORT extern "C"
#else
#define SWIFT_EXPORT extern
#define SWIFT_EXPORT_FROM(LIBRARY) SWIFT_EXPORT_FROM_ATTRIBUTE(LIBRARY)
#endif
#define SWIFT_RUNTIME_EXPORT SWIFT_EXPORT_FROM(swiftCore)
// Define mappings for calling conventions.
// Annotation for specifying a calling convention of
// a runtime function. It should be used with declarations
// of runtime functions like this:
// void runtime_function_name() SWIFT_CC(swift)
#define SWIFT_CC(CC) SWIFT_CC_##CC
// SWIFT_CC(c) is the C calling convention.
#define SWIFT_CC_c
// SWIFT_CC(swift) is the Swift calling convention.
// FIXME: the next comment is false.
// Functions outside the stdlib or runtime that include this file may be built
// with a compiler that doesn't support swiftcall; don't define these macros
// in that case so any incorrect usage is caught.
#if __has_attribute(swiftcall)
#define SWIFT_CC_swift __attribute__((swiftcall))
#define SWIFT_CONTEXT __attribute__((swift_context))
#define SWIFT_ERROR_RESULT __attribute__((swift_error_result))
#define SWIFT_INDIRECT_RESULT __attribute__((swift_indirect_result))
#else
#define SWIFT_CC_swift
#define SWIFT_CONTEXT
#define SWIFT_ERROR_RESULT
#define SWIFT_INDIRECT_RESULT
#endif
typedef struct _Job* JobRef;
typedef SWIFT_CC(swift) void (*swift_task_enqueueGlobal_original)(JobRef _Nonnull job);
SWIFT_EXPORT_FROM(swift_Concurrency)
SWIFT_CC(swift) void (* _Nullable swift_task_enqueueGlobal_hook)(
JobRef _Nonnull job, swift_task_enqueueGlobal_original _Nonnull original);
@@ -0,0 +1,4 @@
module CMarableDiagram [system] {
header "CMarbleDiagram.h"
export *
}
+1
View File
@@ -0,0 +1 @@
../../Sources/AsyncAlgorithms/Locking.swift
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
import AsyncAlgorithms
import ClockStub
public struct ManualClock: Clock {
public struct Step: DurationProtocol {
@@ -50,7 +50,7 @@ public struct ManualClock: Clock {
}
}
public struct Instant: InstantProtocol {
public struct Instant: InstantProtocol, CustomStringConvertible {
public typealias Duration = Step
internal let rawValue: Int
@@ -70,6 +70,10 @@ public struct ManualClock: Clock {
public func duration(to other: ManualClock.Instant) -> ManualClock.Step {
.init(other.rawValue - rawValue)
}
public var description: String {
return "tick \(rawValue)"
}
}
fileprivate struct Wakeup {
@@ -78,7 +82,7 @@ public struct ManualClock: Clock {
let deadline: Instant
}
fileprivate enum Scheduled: Hashable, Comparable {
fileprivate enum Scheduled: Hashable, Comparable, CustomStringConvertible {
case cancelled(Int)
case wakeup(Wakeup)
@@ -91,6 +95,13 @@ public struct ManualClock: Clock {
}
}
var description: String {
switch self {
case .cancelled: return "Cancelled wakeup"
case .wakeup(let wakeup): return "Wakeup at \(wakeup.deadline)"
}
}
static func == (_ lhs: Scheduled, _ rhs: Scheduled) -> Bool {
switch (lhs, rhs) {
case (.cancelled(let lhsGen), .cancelled(let rhsGen)):
@@ -138,6 +149,7 @@ public struct ManualClock: Clock {
var generation = 0
var scheduled = Set<Scheduled>()
var now = Instant(0)
var hasSleepers = false
}
fileprivate let state = ManagedCriticalState(State())
@@ -147,6 +159,8 @@ public struct ManualClock: Clock {
}
public var minimumResolution: Step { return .zero }
public init() { }
fileprivate func cancel(_ generation: Int) {
state.withCriticalRegion { state -> UnsafeContinuation<Void, Error>? in
@@ -165,6 +179,10 @@ public struct ManualClock: Clock {
}?.resume(throwing: CancellationError())
}
var hasSleepers: Bool {
state.withCriticalRegion { $0.hasSleepers }
}
public func advance() {
let pending = state.withCriticalRegion { state -> Set<Scheduled> in
state.now += .steps(1)
@@ -176,6 +194,9 @@ public struct ManualClock: Clock {
}
}
state.scheduled.subtract(pending)
if pending.count > 0 {
state.hasSleepers = false
}
return pending
}
for item in pending.sorted() {
@@ -195,7 +216,6 @@ public struct ManualClock: Clock {
if let existing = state.scheduled.remove(.wakeup(wakeup)) {
switch existing {
case .wakeup:
// already a wakeup with this generation?!
fatalError()
case .cancelled:
// dont bother adding it back because it has been cancelled before we got here
@@ -205,6 +225,7 @@ public struct ManualClock: Clock {
// there is no cancelled placeholder so let it run free
if deadline > state.now {
// the deadline is in the future so run it then
state.hasSleepers = true
state.scheduled.insert(.wakeup(wakeup))
return nil
} else {
+677
View File
@@ -0,0 +1,677 @@
import CMarableDiagram
import ClockStub
@_silgen_name("swift_job_run")
@usableFromInline
internal func _swiftJobRun(
_ job: UnownedJob,
_ executor: UnownedSerialExecutor
) -> ()
func start_thread(_ raw: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
Unmanaged<TaskDriver>.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<Operation: AsyncSequence>: 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<String?, Error> {
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<Theme: MarbleDiagramTheme>(_ 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<State>
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<Theme: MarbleDiagramTheme>(_ 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<Operation: AsyncSequence>(
_ input: String,
_ sequence: Operation,
_ output: String
) -> some MarbleDiagramTest where Operation.Element == String {
return Test(inputs: [input], sequence: sequence, output: output)
}
public static func buildBlock<Operation: AsyncSequence>(
_ input1: String,
_ input2: String,
_ sequence: Operation,
_ output: String
) -> some MarbleDiagramTest where Operation.Element == String {
Test(inputs: [input1, input2], sequence: sequence, output: output)
}
public static func buildBlock<Operation: AsyncSequence>(
_ input1: String,
_ input2: String,
_ input3: String,
_ sequence: Operation,
_ output: String
) -> some MarbleDiagramTest where Operation.Element == String {
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]
}
}
}
}
fileprivate let manualClock: ManualClock
public var inputs: InputList
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<Theme: MarbleDiagramTheme>(
output: String,
theme: Theme,
expected: [ManualClock.Instant : Result<String?, Error>],
actual: [(ManualClock.Instant, Result<String?, Error>)]
) -> [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<ManualClock.Instant>()
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<Test: MarbleDiagramTest, Theme: MarbleDiagramTheme>(
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<String?, Error>)]())
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<Test: MarbleDiagramTest>(
@MarbleDiagram _ build: (inout MarbleDiagram) -> Test
) -> [ExpectationFailure] {
self.test(theme: .ascii, build)
}
}
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)
}
}
@@ -150,3 +150,13 @@ fileprivate func ==<A: Equatable, B: Equatable, C: Equatable>(_ lhs: [(A, B, C)]
public func XCTAssertEqual<A: Equatable, B: Equatable, C: Equatable>(_ expression1: @autoclosure () throws -> [(A, B, C)], _ expression2: @autoclosure () throws -> [(A, B, C)], _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line) {
_XCTAssertEqual(expression1, expression2, { $0 == $1 }, message, file: file, line: line)
}
extension XCTestCase {
func expectFailures(_ failures: Set<String>) {
let options = XCTExpectedFailure.Options()
options.issueMatcher = { issue in
return failures.contains(issue.compactDescription)
}
XCTExpectFailure(nil, options: options)
}
}
@@ -11,311 +11,20 @@
import XCTest
import AsyncAlgorithms
public protocol MarbleDiagramTest: Sendable {
var inputs: [String] { get }
var output: String { get }
func test(_ validator: Validator<String>, onFinish: @Sendable @escaping () -> Void)
}
import MarbleDiagram
extension XCTestCase {
@resultBuilder
public struct MarbleDiagram : Sendable {
fileprivate struct Test<Operation: AsyncSequence>: MarbleDiagramTest, @unchecked Sendable where Operation.Element == String {
let inputs: [String]
let sequence: Operation
let output: String
func test(_ validator: Validator<String>, onFinish: @Sendable @escaping () -> Void) {
validator.test(sequence) { _ in
onFinish()
}
}
}
fileprivate enum Event {
case step
case failure
case finish
case value(String)
}
public struct Input: AsyncSequence, Sendable {
public typealias Element = String
enum Emission {
case value(Element)
case failure(Error)
case finish
var result: Result<Element?, Error> {
switch self {
case .value(let value): return .success(value)
case .failure(let failure): return .failure(failure)
case .finish: return .success(nil)
}
}
}
fileprivate struct State {
var emissions = [(ManualClock.Instant, Emission)]()
var continuations = [ManualClock.Instant: (Emission, UnsafeContinuation<Element?, Error>)]()
}
fileprivate let state = ManagedCriticalState(State())
fileprivate let clock: ManualClock
public struct Iterator: AsyncIteratorProtocol {
fileprivate let state: ManagedCriticalState<State>
fileprivate let clock: ManualClock
public mutating func next() async throws -> Element? {
let next = state.withCriticalRegion { state -> (ManualClock.Instant, Emission)? in
guard state.emissions.count > 0 else {
return nil
}
return state.emissions.removeFirst()
}
guard let next = next else {
return nil
}
return try await withUnsafeThrowingContinuation { continuation in
state.withCriticalRegion { state in
state.continuations[next.0] = (next.1, continuation)
}
}
}
}
public func makeAsyncIterator() -> Iterator {
Iterator(state: state, clock: clock)
}
fileprivate static func parse(_ dsl: String) -> [(ManualClock.Instant, Emission)] {
var emissions = [(ManualClock.Instant, Emission)]()
var when = ManualClock.Instant(0)
var group: String?
for ch in dsl {
switch ch {
case "-":
if group == nil {
when += .steps(1)
} else {
group?.append(ch)
}
case "^":
if group == nil {
when += .steps(1)
emissions.append((when, .failure(Failure())))
} else {
group?.append(ch)
}
case "|":
if group == nil {
when += .steps(1)
emissions.append((when, .finish))
} else {
group?.append(ch)
}
case "'":
if let value = group {
group = nil
when += .steps(1)
emissions.append((when, .value(value)))
} else {
group = ""
}
case " ":
group?.append(ch)
continue
default:
if group == nil {
when += .steps(1)
emissions.append((when, .value(String(ch))))
} else {
group?.append(ch)
}
}
}
return emissions
}
func parse(_ dsl: String) {
let emissions = Input.parse(dsl)
state.withCriticalRegion { state in
state.emissions = emissions
}
}
}
public struct Clock {
fileprivate let manualClock: ManualClock
fileprivate init(_ manualClock: ManualClock) {
self.manualClock = manualClock
}
}
public static func buildBlock<Operation: AsyncSequence>(_ input: String, _ sequence: Operation, _ output: String) -> some MarbleDiagramTest where Operation.Element == String {
Test(inputs: [input], sequence: sequence, output: output)
}
public static func buildBlock<Operation: AsyncSequence>(_ input1: String, _ input2: String, _ sequence: Operation, _ output: String) -> some MarbleDiagramTest where Operation.Element == String {
Test(inputs: [input1, input2], sequence: sequence, output: output)
}
public static func buildBlock<Operation: AsyncSequence>(_ input1: String, _ input2: String, _ input3: String, _ sequence: Operation, _ output: String) -> some MarbleDiagramTest where Operation.Element == String {
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) -> XCTestCase.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]
}
}
}
}
fileprivate let manualClock: ManualClock
public var inputs: InputList
public var clock: Clock {
Clock(manualClock)
}
fileprivate init(clock: ManualClock) {
self.manualClock = clock
inputs = InputList(clock: clock)
public func marbleDiagram<Test: MarbleDiagramTest, Theme: MarbleDiagramTheme>(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: [])
record(issue)
print(failure.debugDescription)
}
}
public func marbleDiagram<Test: MarbleDiagramTest>(@MarbleDiagram _ build: (inout MarbleDiagram) -> Test, file: StaticString = #file, line: UInt = #line) {
let finished = expectation(description: "finished")
let clock = ManualClock()
var diagram = MarbleDiagram(clock: clock)
let test = build(&diagram)
for (index, input) in diagram.inputs.enumerated() {
input.parse(test.inputs[index])
}
var expected = Dictionary(uniqueKeysWithValues: MarbleDiagram.Input.parse(test.output).map { ($0, $1.result) })
let actual = ManagedCriticalState([ManualClock.Instant:Result<String?, Error>]())
let gate = Gate()
let expectation = Gate()
let validator = Validator<String> { event in
actual.withCriticalRegion { actual in
actual[clock.now] = event
}
await gate.enter()
expectation.open()
}
test.test(validator) {
finished.fulfill()
}
let task = Task { [expected, diagram] in
while !Task.isCancelled {
clock.advance()
for input in diagram.inputs {
let resumption = input.state.withCriticalRegion { state in
return state.continuations.removeValue(forKey: clock.now)
}
if let resumption = resumption {
resumption.1.resume(with: resumption.0.result)
}
}
gate.open()
if expected[clock.now] != nil {
await expectation.enter()
}
}
}
wait(for: [finished], timeout: executionTimeAllowance)
task.cancel()
let collected = actual.withCriticalRegion { zip($0.keys, $0.values) }
for (instant, result) in collected {
if let expectedResult = expected.removeValue(forKey: instant) {
switch (result, expectedResult) {
case (.success(let actual), .success(let expected)):
switch (actual, expected) {
case (.some(let actual), .some(let expected)):
if actual != expected {
XCTFail("expected \(expected) at time index \(instant.rawValue) but got \(actual)", file: file, line: line)
}
case (.none, .some(let expected)):
XCTFail("expected \(expected) at time index \(instant.rawValue) but got end of iteration", file: file, line: line)
case (.some(let actual), .none):
XCTFail("expected end of iteration at time index \(instant.rawValue) but got \(actual)", file: file, line: line)
case (.none, .none):
break
}
case (.failure(let error), .success(let expected)):
if let expected = expected {
XCTFail("expected \(expected) at time index \(instant.rawValue) but got failure \(error)", file: file, line: line)
} else {
XCTFail("expected end of iteration at time index \(instant.rawValue) but got failure \(error)", file: file, line: line)
}
case (.success(let actual), .failure):
if let actual = actual {
XCTFail("expected failure at time index \(instant.rawValue) but got \(actual)", file: file, line: line)
} else {
XCTFail("expected failure at time index \(instant.rawValue) but got end of iteration", file: file, line: line)
}
case (.failure, .failure):
break
}
} else {
switch result {
case .success(let value):
if let value = value {
XCTFail("unexpected value \"\(value)\" at time index \(instant.rawValue)", file: file, line: line)
} else {
XCTFail("unexpected end of iteration at time index \(instant.rawValue)", file: file, line: line)
}
case .failure:
XCTFail("unexpected failure at time index \(instant.rawValue)", file: file, line: line)
}
}
}
for (instant, result) in expected {
switch result {
case .success(let value):
if let value = value {
XCTFail("missing expected value \"\(value)\" at time index \(instant.rawValue)", file: file, line: line)
} else {
XCTFail("missing end of iteration at time index \(instant.rawValue)", file: file, line: line)
}
case .failure:
XCTFail("missing failure at time index \(instant.rawValue)", file: file, line: line)
}
}
}
}
extension XCTestCase.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)
marbleDiagram(theme: .ascii, build, file: file, line: line)
}
}
@@ -11,6 +11,7 @@
import XCTest
import AsyncAlgorithms
import MarbleDiagram
final class TestCombineLatest2: XCTestCase {
func test_combineLatest() async {
@@ -11,6 +11,7 @@
import XCTest
import AsyncAlgorithms
import MarbleDiagram
final class TestManualClock: XCTestCase {
func test_sleep() async {
@@ -0,0 +1,184 @@
//===----------------------------------------------------------------------===//
//
// 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 XCTest
import AsyncAlgorithms
import MarbleDiagram
final class TestMarbleDiagram: XCTestCase {
func test_diagram() {
marbleDiagram {
"a--b--c---|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--C---|"
}
}
func test_diagram_space_noop() {
marbleDiagram {
" a -- b -- c ---|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
" A- - B - - C - -- | "
}
}
func test_diagram_string_input() {
marbleDiagram {
"'foo''bar''baz'|"
$0.inputs[0].map { $0.first.map { String($0) } ?? "X" }
"fbb|"
}
}
func test_diagram_string_input_expectation() {
marbleDiagram {
"'foo''bar''baz'|"
$0.inputs[0]
"'foo''bar''baz'|"
}
}
func test_diagram_string_dsl_contents() {
marbleDiagram {
"'foo-''bar^''baz|'|"
$0.inputs[0]
"'foo-''bar^''baz|'|"
}
}
func test_diagram_emoji() {
struct EmojiTokens: MarbleDiagramTheme {
func token(_ character: Character, inValue: Bool) -> MarbleDiagram.Token {
switch character {
case "➖": return .step
case "❗️": return .error
case "❌": return .finish
case "➡️": return .beginValue
case "⬅️": return .endValue
case " ": return .skip
default: return .value(String(character))
}
}
}
marbleDiagram(theme: EmojiTokens()) {
"➖🔴➖🟠➖🟡➖🟢➖❌"
$0.inputs[0]
"➖🔴➖🟠➖🟡➖🟢➖❌"
}
}
func test_diagram_failure_mismatch_value() {
expectFailures(["expected \"X\" but got \"C\" at tick 6"])
marbleDiagram {
"a--b--c---|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--X---|"
}
}
func test_diagram_failure_value_for_finish() {
expectFailures(["expected finish but got \"C\" at tick 6",
"unexpected finish at tick 10"])
marbleDiagram {
"a--b--c---|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--|"
}
}
func test_diagram_failure_finish_for_value() {
expectFailures(["expected \"C\" but got finish at tick 6",
"expected finish at tick 7"])
marbleDiagram {
"a--b--|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--C|"
}
}
func test_diagram_failure_finish_for_error() {
expectFailures(["expected failure but got finish at tick 6"])
marbleDiagram {
"a--b--|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--^"
}
}
func test_diagram_failure_error_for_finish() {
expectFailures(["expected finish but got failure at tick 6"])
marbleDiagram {
"a--b--^"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--|"
}
}
func test_diagram_failure_value_for_error() {
expectFailures(["expected failure but got \"C\" at tick 6",
"unexpected finish at tick 7"])
marbleDiagram {
"a--b--c|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--^"
}
}
func test_diagram_failure_error_for_value() {
expectFailures(["expected \"C\" but got failure at tick 6",
"expected finish at tick 7"])
marbleDiagram {
"a--b--^"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--C|"
}
}
func test_diagram_failure_expected_value() {
expectFailures(["expected \"C\" at tick 6",
"unexpected finish at tick 7"])
marbleDiagram {
"a--b---|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--C|"
}
}
func test_diagram_failure_expected_failure() {
expectFailures(["expected failure at tick 6",
"unexpected finish at tick 7"])
marbleDiagram {
"a--b---|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--^"
}
}
func test_diagram_failure_unexpected_value() {
expectFailures(["unexpected \"C\" at tick 6"])
marbleDiagram {
"a--b--c|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B---|"
}
}
func test_diagram_failure_unexpected_failure() {
expectFailures(["unexpected failure at tick 6",
"expected finish at tick 7"])
marbleDiagram {
"a--b--^|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B---|"
}
}
}
@@ -11,6 +11,7 @@
import XCTest
import AsyncAlgorithms
import MarbleDiagram
final class TestValidator: XCTestCase {
func test_gate() async {
@@ -135,12 +136,4 @@ final class TestValidator: XCTestCase {
value = validator.current
XCTAssertEqual(value, [2, 3, 4])
}
func test_diagram() {
marbleDiagram {
"a-b-c|"
$0.inputs[0].map { $0 }
"a-b-c|"
}
}
}