Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adopt swift-format #2794

Merged
merged 21 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 0 additions & 1 deletion .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ jobs:
uses: ./.github/workflows/pull_request_soundness.yml
with:
license_header_check_project_name: "SwiftNIO"
format_check_enabled: false

call-pull-request-unit-tests-workflow:
name: Unit tests
Expand Down
11 changes: 9 additions & 2 deletions .github/workflows/pull_request_soundness.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,5 +123,12 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run format check
run: swift format lint --parallel --recursive --strict
- name: Mark the workspace as safe
# https://github.com/actions/checkout/issues/766
run: git config --global --add safe.directory ${GITHUB_WORKSPACE}
- name: Run format lint check
run: swift format lint --strict --recursive --parallel .
- name: Run format and check for modified files
run: |
swift format format --parallel --recursive --in-place .
git diff-index --quiet HEAD
62 changes: 62 additions & 0 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"version" : 1,
"indentation" : {
"spaces" : 4
},
"tabWidth" : 4,
"fileScopedDeclarationPrivacy" : {
"accessLevel" : "private"
},
"spacesAroundRangeFormationOperators" : false,
"indentConditionalCompilationBlocks" : false,
"indentSwitchCaseLabels" : false,
"lineBreakAroundMultilineExpressionChainComponents" : false,
"lineBreakBeforeControlFlowKeywords" : false,
"lineBreakBeforeEachArgument" : true,
"lineBreakBeforeEachGenericRequirement" : true,
"lineLength" : 120,
"maximumBlankLines" : 1,
"respectsExistingLineBreaks" : true,
"prioritizeKeepingFunctionOutputTogether" : true,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLiteralForEmptyCollectionInit" : false,
"AlwaysUseLowerCamelCase" : false,
"AmbiguousTrailingClosureOverload" : true,
"BeginDocumentationCommentWithOneLineSummary" : false,
"DoNotUseSemicolons" : true,
"DontRepeatTypeInStaticProperties" : true,
"FileScopedDeclarationPrivacy" : true,
"FullyIndirectEnum" : true,
"GroupNumericLiterals" : true,
"IdentifiersMustBeASCII" : true,
"NeverForceUnwrap" : false,
"NeverUseForceTry" : false,
"NeverUseImplicitlyUnwrappedOptionals" : false,
"NoAccessLevelOnExtensionDeclaration" : true,
"NoAssignmentInExpressions" : true,
"NoBlockComments" : true,
"NoCasesWithOnlyFallthrough" : true,
"NoEmptyTrailingClosureParentheses" : true,
"NoLabelsInCasePatterns" : true,
"NoLeadingUnderscores" : false,
"NoParensAroundConditions" : true,
"NoVoidReturnOnFunctionSignature" : true,
"OmitExplicitReturns" : true,
"OneCasePerLine" : true,
"OneVariableDeclarationPerLine" : true,
"OnlyOneTrailingClosureArgument" : true,
"OrderedImports" : true,
"ReplaceForEachWithForLoop" : true,
"ReturnVoidInsteadOfEmptyTuple" : true,
"UseEarlyExits" : false,
"UseExplicitNilCheckInConditions" : false,
"UseLetInEveryBoundCaseVariable" : false,
"UseShorthandTypeNames" : true,
"UseSingleLinePropertyGetter" : false,
"UseSynthesizedInitializer" : false,
"UseTripleSlashForDocumentationComments" : true,
"UseWhereClausesInForLoops" : false,
"ValidateDocumentationComments" : false
}
}
4 changes: 2 additions & 2 deletions Benchmarks/Benchmarks/NIOCoreBenchmarks/Benchmarks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import NIOEmbedded

let benchmarks = {
let defaultMetrics: [BenchmarkMetric] = [
.mallocCountTotal,
.mallocCountTotal
]

Benchmark(
Expand All @@ -28,7 +28,7 @@ let benchmarks = {
// Elide the cost of the 'EmbeddedChannel'. It's only used for its pipeline.
var channels: [EmbeddedChannel] = []
channels.reserveCapacity(benchmark.scaledIterations.count)
for _ in 0 ..< benchmark.scaledIterations.count {
for _ in 0..<benchmark.scaledIterations.count {
channels.append(EmbeddedChannel())
}

Expand Down
2 changes: 1 addition & 1 deletion Benchmarks/Benchmarks/NIOPosixBenchmarks/Benchmarks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ private let eventLoop = MultiThreadedEventLoopGroup.singleton.next()

let benchmarks = {
let defaultMetrics: [BenchmarkMetric] = [
.mallocCountTotal,
.mallocCountTotal
]

Benchmark(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func runTCPEchoAsyncChannel(numberOfWrites: Int, eventLoop: EventLoop) async thr
port: 0
) { channel in
channel.eventLoop.makeCompletedFuture {
return try NIOAsyncChannel(
try NIOAsyncChannel(
wrappingChannelSynchronously: channel,
configuration: .init(
inboundType: ByteBuffer.self,
Expand All @@ -38,7 +38,7 @@ func runTCPEchoAsyncChannel(numberOfWrites: Int, eventLoop: EventLoop) async thr
port: serverChannel.channel.localAddress!.port!
) { channel in
channel.eventLoop.makeCompletedFuture {
return try NIOAsyncChannel(
try NIOAsyncChannel(
wrappingChannelSynchronously: channel,
configuration: .init(
inboundType: ByteBuffer.self,
Expand All @@ -55,7 +55,9 @@ func runTCPEchoAsyncChannel(numberOfWrites: Int, eventLoop: EventLoop) async thr
group.addTask {
try await serverChannel.executeThenClose { serverChannelInbound in
for try await connectionChannel in serverChannelInbound {
try await connectionChannel.executeThenClose { connectionChannelInbound, connectionChannelOutbound in
try await connectionChannel.executeThenClose {
connectionChannelInbound,
connectionChannelOutbound in
for try await inboundData in connectionChannelInbound {
try await connectionChannelOutbound.write(inboundData)
}
Expand All @@ -68,7 +70,7 @@ func runTCPEchoAsyncChannel(numberOfWrites: Int, eventLoop: EventLoop) async thr
// This child task is collecting the echoed back responses.
group.addTask {
var receivedData = 0
for try await inboundData in inbound {
for try await inboundData in inbound {
receivedData += inboundData.readableBytes

if receivedData == numberOfWrites * messageSize {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ import Glibc
typealias EnqueueGlobalHook = @convention(thin) (UnownedJob, @convention(thin) (UnownedJob) -> Void) -> Void

var swiftTaskEnqueueGlobalHook: EnqueueGlobalHook? {
get { _swiftTaskEnqueueGlobalHook.pointee }
set { _swiftTaskEnqueueGlobalHook.pointee = newValue }
get { _swiftTaskEnqueueGlobalHook.pointee }
set { _swiftTaskEnqueueGlobalHook.pointee = newValue }
}

private let _swiftTaskEnqueueGlobalHook: UnsafeMutablePointer<EnqueueGlobalHook?> =
dlsym(dlopen(nil, RTLD_LAZY), "swift_task_enqueueGlobal_hook").assumingMemoryBound(to: EnqueueGlobalHook?.self)
dlsym(dlopen(nil, RTLD_LAZY), "swift_task_enqueueGlobal_hook").assumingMemoryBound(to: EnqueueGlobalHook?.self)
2 changes: 1 addition & 1 deletion Benchmarks/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import PackageDescription
let package = Package(
name: "benchmarks",
platforms: [
.macOS("14"),
.macOS("14")
],
dependencies: [
.package(path: "../"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ import PackageDescription
let package = Package(
name: "AtomicCounter",
products: [
.library(name: "AtomicCounter", type: .dynamic, targets: ["AtomicCounter"]),
.library(name: "AtomicCounter", type: .dynamic, targets: ["AtomicCounter"])
],
dependencies: [ ],
dependencies: [],
targets: [
.target(
name: "AtomicCounter",
dependencies: []),
dependencies: []
)
]
)
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ import PackageDescription
let package = Package(
name: "HookedFunctions",
products: [
.library(name: "HookedFunctions", type: .dynamic, targets: ["HookedFunctions"]),
.library(name: "HookedFunctions", type: .dynamic, targets: ["HookedFunctions"])
],
dependencies: [
.package(url: "../AtomicCounter/", branch: "main"),
.package(url: "../AtomicCounter/", branch: "main")
],
targets: [
.target(name: "HookedFunctions", dependencies: ["AtomicCounter"]),
.target(name: "HookedFunctions", dependencies: ["AtomicCounter"])
]
)
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ import PackageDescription
let package = Package(
name: "HookedFunctions",
products: [
.library(name: "HookedFunctions", type: .dynamic, targets: ["HookedFunctions"]),
.library(name: "HookedFunctions", type: .dynamic, targets: ["HookedFunctions"])
],
dependencies: [
.package(url: "../AtomicCounter/", branch: "main"),
.package(url: "../AtomicCounter/", branch: "main")
],
targets: [
.target(name: "HookedFunctions", dependencies: ["AtomicCounter"]),
.target(name: "HookedFunctions", dependencies: ["AtomicCounter"])
]
)
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@
//
//===----------------------------------------------------------------------===//

import Foundation
import AtomicCounter
import Foundation

#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
Expand All @@ -24,7 +25,7 @@ import Glibc

func waitForThreadsToQuiesce(shouldReachZero: Bool) {
func getUnfreed() -> Int {
return AtomicCounter.read_malloc_counter() - AtomicCounter.read_free_counter()
AtomicCounter.read_malloc_counter() - AtomicCounter.read_free_counter()
}

var oldNumberOfUnfreed = getUnfreed()
Expand All @@ -35,7 +36,8 @@ func waitForThreadsToQuiesce(shouldReachZero: Bool) {
return
}
count += 1
usleep(shouldReachZero ? 50_000 : 200_000) // allocs/frees happen on multiple threads, allow some cool down time
// allocs/frees happen on multiple threads, allow some cool down time
usleep(shouldReachZero ? 50_000 : 200_000)
let newNumberOfUnfreed = getUnfreed()
if oldNumberOfUnfreed == newNumberOfUnfreed && (!shouldReachZero || newNumberOfUnfreed <= 0) {
// nothing happened in the last 100ms, let's assume everything's
Expand All @@ -57,7 +59,11 @@ struct Measurement {
}

extension Array where Element == Measurement {
private func printIntegerMetric(_ keyPath: KeyPath<Measurement, Int>, description desc: String, metricName k: String) {
private func printIntegerMetric(
_ keyPath: KeyPath<Measurement, Int>,
description desc: String,
metricName k: String
) {
let vs = self.map { $0[keyPath: keyPath] }
print("\(desc).\(k): \(vs.min() ?? -1)")
}
Expand Down Expand Up @@ -90,13 +96,13 @@ func measureAll(trackFDs: Bool, _ fn: () -> Int) -> [Measurement] {
AtomicCounter.begin_tracking_fds()
}

#if canImport(Darwin)
#if canImport(Darwin)
autoreleasepool {
_ = fn()
}
#else
#else
_ = fn()
#endif
#endif
waitForThreadsToQuiesce(shouldReachZero: !throwAway)
let frees = AtomicCounter.read_free_counter()
let mallocs = AtomicCounter.read_malloc_counter()
Expand All @@ -121,7 +127,7 @@ func measureAll(trackFDs: Bool, _ fn: () -> Int) -> [Measurement] {
)
}

_ = measureOne(throwAway: true, trackFDs: trackFDs, fn) /* pre-heat and throw away */
_ = measureOne(throwAway: true, trackFDs: trackFDs, fn) // pre-heat and throw away

var measurements: [Measurement] = []
for _ in 0..<10 {
Expand All @@ -132,19 +138,19 @@ func measureAll(trackFDs: Bool, _ fn: () -> Int) -> [Measurement] {
return measurements
}

func measureAndPrint(desc: String, trackFDs: Bool, fn: () -> Int) -> Void {
func measureAndPrint(desc: String, trackFDs: Bool, fn: () -> Int) {
let measurements = measureAll(trackFDs: trackFDs, fn)
measurements.printTotalAllocations(description: desc)
measurements.printRemainingAllocations(description: desc)
measurements.printTotalAllocatedBytes(description: desc)
measurements.printLeakedFDs(description: desc)

print("DEBUG: \(measurements)")
}

public func measure(identifier: String, trackFDs: Bool = false, _ body: () -> Int) {
measureAndPrint(desc: identifier, trackFDs: trackFDs) {
return body()
body()
}
}

Expand All @@ -160,7 +166,7 @@ func measureAll(trackFDs: Bool, _ fn: @escaping () async -> Int) -> [Measurement
}
group.wait()
}

if trackFDs {
AtomicCounter.begin_tracking_fds()
}
Expand All @@ -169,13 +175,13 @@ func measureAll(trackFDs: Bool, _ fn: @escaping () async -> Int) -> [Measurement
AtomicCounter.reset_malloc_counter()
AtomicCounter.reset_malloc_bytes_counter()

#if canImport(Darwin)
#if canImport(Darwin)
autoreleasepool {
run(fn)
}
#else
#else
run(fn)
#endif
#endif
waitForThreadsToQuiesce(shouldReachZero: !throwAway)
let frees = AtomicCounter.read_free_counter()
let mallocs = AtomicCounter.read_malloc_counter()
Expand All @@ -200,7 +206,7 @@ func measureAll(trackFDs: Bool, _ fn: @escaping () async -> Int) -> [Measurement
)
}

_ = measureOne(throwAway: true, trackFDs: trackFDs, fn) /* pre-heat and throw away */
_ = measureOne(throwAway: true, trackFDs: trackFDs, fn) // pre-heat and throw away

var measurements: [Measurement] = []
for _ in 0..<10 {
Expand All @@ -212,7 +218,7 @@ func measureAll(trackFDs: Bool, _ fn: @escaping () async -> Int) -> [Measurement
}

@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
func measureAndPrint(desc: String, trackFDs: Bool, fn: @escaping () async -> Int) -> Void {
func measureAndPrint(desc: String, trackFDs: Bool, fn: @escaping () async -> Int) {
let measurements = measureAll(trackFDs: trackFDs, fn)
measurements.printTotalAllocations(description: desc)
measurements.printRemainingAllocations(description: desc)
Expand Down
Loading