Skip to content

Commit

Permalink
Update for 0.52.4 release
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Sep 17, 2023
1 parent 31e8532 commit 1f8b956
Show file tree
Hide file tree
Showing 14 changed files with 114 additions and 104 deletions.
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Change Log

## [0.52.4](https://github.com/nicklockwood/SwiftFormat/releases/tag/0.52.4) (2023-09-17)

- Fixed `docComments` rule incorrectly replacing comments inside switch cases and if/guard conditions
- Fixed `redundantLet` rule removing required `let` inside `ViewBuilder` modifiers
- Fixed `redundantLet` rule removing required `let` after `@MainActor` or `@Sendable`
- Fixed bug when using `--wrapconditions after-first` if first line of condition is a comment
- Added more context to "failed to terminate" error message to aid tracking down issues
- Updated `sortTypealiases` rule to also remove duplicate protocols in declaration
- Added some fixes to support parameter packs in Swift 5.9

## [0.52.3](https://github.com/nicklockwood/SwiftFormat/releases/tag/0.52.3) (2023-09-02)

- Fixed incorrect hoisting of `try` inside multiline string literal interpolations
Expand Down
Binary file modified CommandLineTool/swiftformat
Binary file not shown.
36 changes: 18 additions & 18 deletions Sources/Arguments.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ extension Options {
}

extension String {
// Find best match for the string in a list of options
/// Find best match for the string in a list of options
func bestMatches(in options: [String]) -> [String] {
let lowercaseQuery = lowercased()
// Sort matches by Levenshtein edit distance
Expand Down Expand Up @@ -108,8 +108,8 @@ extension String {
}
}

// Parse a space-delimited string into an array of command-line arguments
// Replicates the behavior implemented by the console when parsing input
/// Parse a space-delimited string into an array of command-line arguments
/// Replicates the behavior implemented by the console when parsing input
func parseArguments(_ argumentString: String, ignoreComments: Bool = true) -> [String] {
var arguments = [""] // Arguments always begin with script path
var characters = String.UnicodeScalarView.SubSequence(argumentString.unicodeScalars)
Expand Down Expand Up @@ -149,7 +149,7 @@ func parseArguments(_ argumentString: String, ignoreComments: Bool = true) -> [S
return arguments
}

// Parse a flat array of command-line arguments into a dictionary of flags and values
/// Parse a flat array of command-line arguments into a dictionary of flags and values
func preprocessArguments(_ args: [String], _ names: [String]) throws -> [String: String] {
var anonymousArgs = 0
var namedArgs: [String: String] = [:]
Expand Down Expand Up @@ -205,15 +205,15 @@ func preprocessArguments(_ args: [String], _ names: [String]) throws -> [String:
return namedArgs
}

// Parse a comma-delimited list of items
/// Parse a comma-delimited list of items
func parseCommaDelimitedList(_ string: String) -> [String] {
string.components(separatedBy: ",").compactMap {
let item = $0.trimmingCharacters(in: .whitespacesAndNewlines)
return item.isEmpty ? nil : item
}
}

// Parse a comma-delimited string into an array of rules
/// Parse a comma-delimited string into an array of rules
let allRules = Set(FormatRules.byName.keys)
func parseRules(_ rules: String) throws -> [String] {
try parseCommaDelimitedList(rules).flatMap { proposedName -> [String] in
Expand All @@ -238,7 +238,7 @@ func parseRules(_ rules: String) throws -> [String] {
}
}

// Parse single file path, disallowing globs or commas
/// Parse single file path, disallowing globs or commas
func parsePath(_ path: String, for argument: String, in directory: String) throws -> URL {
let expandedPath = expandPath(path, in: directory)
if !FileManager.default.fileExists(atPath: expandedPath.path) {
Expand All @@ -252,12 +252,12 @@ func parsePath(_ path: String, for argument: String, in directory: String) throw
return expandedPath
}

// Parse one or more comma-delimited file paths, expanding globs as required
/// Parse one or more comma-delimited file paths, expanding globs as required
func parsePaths(_ paths: String, in directory: String) throws -> [URL] {
try matchGlobs(expandGlobs(paths, in: directory), in: directory)
}

// Merge two dictionaries of arguments
/// Merge two dictionaries of arguments
func mergeArguments(_ args: [String: String], into config: [String: String]) throws -> [String: String] {
var input = config
var output = args
Expand Down Expand Up @@ -327,7 +327,7 @@ func mergeArguments(_ args: [String: String], into config: [String: String]) thr
return output
}

// Parse a configuration file into a dictionary of arguments
/// Parse a configuration file into a dictionary of arguments
public func parseConfigFile(_ data: Data) throws -> [String: String] {
guard let input = String(data: data, encoding: .utf8) else {
throw FormatError.reading("Unable to read data for configuration file")
Expand Down Expand Up @@ -378,7 +378,7 @@ private func effectiveContent(of line: String) -> String {
.trimmingCharacters(in: .whitespaces)
}

// Serialize a set of options into either an arguments string or a file
/// Serialize a set of options into either an arguments string or a file
func serialize(options: Options,
swiftVersion: Version = .undefined,
excludingDefaults: Bool = false,
Expand Down Expand Up @@ -412,7 +412,7 @@ func serialize(options: Options,
.joined(separator: separator)
}

// Serialize arguments
/// Serialize arguments
func serialize(arguments: [String: String],
separator: String = "\n") -> String
{
Expand All @@ -425,7 +425,7 @@ func serialize(arguments: [String: String],
}.sorted().joined(separator: separator)
}

// Get command line arguments from options
/// Get command line arguments from options
func argumentsFor(_ options: Options, excludingDefaults: Bool = false) -> [String: String] {
var args = [String: String]()
if let fileOptions = options.fileOptions {
Expand Down Expand Up @@ -523,7 +523,7 @@ private func processOption(_ key: String,
}
}

// Parse rule names from arguments
/// Parse rule names from arguments
public func rulesFor(_ args: [String: String], lint: Bool) throws -> Set<String> {
var rules = allRules
rules = try args["rules"].map {
Expand All @@ -545,7 +545,7 @@ public func rulesFor(_ args: [String: String], lint: Bool) throws -> Set<String>
return rules
}

// Parse FileOptions from arguments
/// Parse FileOptions from arguments
func fileOptionsFor(_ args: [String: String], in directory: String) throws -> FileOptions? {
var options = FileOptions()
var arguments = Set(fileArguments)
Expand Down Expand Up @@ -584,8 +584,8 @@ func fileOptionsFor(_ args: [String: String], in directory: String) throws -> Fi
return containsFileOption ? options : nil
}

// Parse FormatOptions from arguments
// Returns nil if the arguments dictionary does not contain any formatting arguments
/// Parse FormatOptions from arguments
/// Returns nil if the arguments dictionary does not contain any formatting arguments
public func formatOptionsFor(_ args: [String: String]) throws -> FormatOptions? {
var options = FormatOptions.default
var arguments = Set(formattingArguments)
Expand All @@ -601,7 +601,7 @@ public func formatOptionsFor(_ args: [String: String]) throws -> FormatOptions?
return containsFormatOption ? options : nil
}

// Get deprecation warnings from a set of arguments
/// Get deprecation warnings from a set of arguments
func warningsForArguments(_ args: [String: String], ignoreUnusedOptions: Bool = false) -> [String] {
var warnings = [String]()
for option in Descriptors.all {
Expand Down
4 changes: 2 additions & 2 deletions Sources/CommandLine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ private func print(_ message: String, as type: CLI.OutputType = .info) {
}
}

// Print warnings and return true if any was an actual error
/// Print warnings and return true if any was an actual error
private func printWarnings(_ errors: [Error]) -> Bool {
var containsError = false
for error in errors {
Expand Down Expand Up @@ -102,7 +102,7 @@ private func printWarnings(_ errors: [Error]) -> Bool {
return containsError
}

// Represents the exit codes to the command line. See `man sysexits` for more information.
/// Represents the exit codes to the command line. See `man sysexits` for more information.
public enum ExitCode: Int32 {
case ok = 0 // EX_OK
case lintFailure = 1
Expand Down
12 changes: 6 additions & 6 deletions Sources/Formatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Formatter.swift
// SwiftFormat
//
// Version 0.52.3
// Version 0.52.4
//
// Created by Nick Lockwood on 12/08/2016.
// Copyright 2016 Nick Lockwood
Expand Down Expand Up @@ -47,10 +47,10 @@ public class Formatter: NSObject {
private var tempOptions: FormatOptions?
private var wasNextDirective = false

// Formatting range
/// Formatting range
public var range: Range<Int>?

// Current rule, used for handling comment directives
/// Current rule, used for handling comment directives
var currentRule: FormatRule? {
didSet {
disabledCount = 0
Expand All @@ -64,7 +64,7 @@ public class Formatter: NSObject {
}
}

// Is current rule enabled
/// Is current rule enabled
var isEnabled: Bool {
if ruleDisabled || disabledCount + disabledNext > 0 ||
range?.contains(enumerationIndex) == false
Expand All @@ -77,7 +77,7 @@ public class Formatter: NSObject {
/// Directives that can be used in comments, e.g. `// swiftformat:disable rule`
let directives = ["disable", "enable", "options", "sort"]

// Process a comment token (which may contain directives)
/// Process a comment token (which may contain directives)
func processCommentBody(_ comment: String, at index: Int) {
var prefix = "swiftformat:"
guard let range = comment.range(of: prefix) else {
Expand Down Expand Up @@ -590,7 +590,7 @@ public extension Formatter {
return 0 // Inserted 0 tokens
}

// As above, but only if formatting is enabled
/// As above, but only if formatting is enabled
@discardableResult
internal func insertSpaceIfEnabled(_ space: String, at index: Int) -> Int {
isEnabled ? insertSpace(space, at: index) : 0
Expand Down
52 changes: 26 additions & 26 deletions Sources/FormattingHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import Foundation
// MARK: shared helper methods

extension Formatter {
// should brace be wrapped according to `wrapMultilineStatementBraces` rule?
/// should brace be wrapped according to `wrapMultilineStatementBraces` rule?
func shouldWrapMultilineStatementBrace(at index: Int) -> Bool {
assert(tokens[index] == .startOfScope("{"))
guard let endIndex = endOfScope(at: index),
Expand All @@ -36,7 +36,7 @@ extension Formatter {
return false
}

// remove self if possible
/// remove self if possible
func removeSelf(at i: Int, exclude: Set<String>, include: Set<String>? = nil) -> Bool {
guard case let .identifier(selfKeyword) = tokens[i], ["self", "Self"].contains(selfKeyword) else {
assertionFailure()
Expand Down Expand Up @@ -82,7 +82,7 @@ extension Formatter {
return true
}

// gather declared variable names, starting at index after let/var keyword
/// gather declared variable names, starting at index after let/var keyword
func processDeclaredVariables(at index: inout Int, names: inout Set<String>,
removeSelfKeyword: String?, onlyLocal: Bool,
scopeAllowsImplicitSelfRebinding: Bool)
Expand Down Expand Up @@ -270,7 +270,7 @@ extension Formatter {
}
}

// Shared wrap implementation
/// Shared wrap implementation
func wrapCollectionsAndArguments(completePartialWrapping: Bool, wrapSingleArguments: Bool) {
let maxWidth = options.maxWidth
func removeLinebreakBeforeEndOfScope(at endOfScope: inout Int) {
Expand Down Expand Up @@ -540,7 +540,7 @@ extension Formatter {
var isParameters = false
switch string {
case "(":
/// Don't wrap color/image literals due to Xcode bug
// Don't wrap color/image literals due to Xcode bug
guard let prevToken = self.token(at: i - 1),
prevToken != .keyword("#colorLiteral"),
prevToken != .keyword("#imageLiteral")
Expand Down Expand Up @@ -739,10 +739,10 @@ extension Formatter {
}
}

/// Wraps / re-wraps a multi-line statement where each delimiter index
/// should be the first token on its line, if the statement
/// is longer than the max width or there is already a linebreak
/// adjacent to one of the delimiters
// Wraps / re-wraps a multi-line statement where each delimiter index
// should be the first token on its line, if the statement
// is longer than the max width or there is already a linebreak
// adjacent to one of the delimiters
@discardableResult
func wrapMultilineStatement(
startIndex: Int,
Expand Down Expand Up @@ -999,8 +999,8 @@ extension Formatter {
}
}

// Common implementation for the `hoistTry` and `hoistAwait` rules
// Hoists the first keyword of the specified type out of the specified scope
/// Common implementation for the `hoistTry` and `hoistAwait` rules
/// Hoists the first keyword of the specified type out of the specified scope
func hoistEffectKeyword(
_ keyword: String,
inScopeAt scopeStart: Int,
Expand Down Expand Up @@ -1469,7 +1469,7 @@ extension Formatter {
}
}

// Utility functions used by organizeDeclarations rule
/// Utility functions used by organizeDeclarations rule
// TODO: find a better place to put this
extension Formatter {
/// Categories of declarations within an individual type
Expand Down Expand Up @@ -1883,7 +1883,7 @@ extension Formatter {
$0.isComment && $0.string.contains("swiftformat:sort") && !$0.string.contains(":sort:")
})

/// Sorts the given categoried declarations based on their derived metadata
// Sorts the given categoried declarations based on their derived metadata
func sortDeclarations(
_ declarations: CategorizedDeclarations,
byCategory sortByCategory: Bool,
Expand Down Expand Up @@ -1941,8 +1941,8 @@ extension Formatter {
if typeDeclaration.kind == "struct",
!typeDeclaration.body.contains(where: { $0.keyword == "init" })
{
/// Whether or not this declaration is an instance property that can affect
/// the parameters struct's synthesized memberwise initializer
// Whether or not this declaration is an instance property that can affect
// the parameters struct's synthesized memberwise initializer
func affectsSynthesizedMemberwiseInitializer(
_ declaration: Declaration,
_ type: DeclarationType?
Expand Down Expand Up @@ -2114,7 +2114,7 @@ extension Formatter {
}

extension Formatter {
/// A generic type parameter for a method
// A generic type parameter for a method
class GenericType {
/// The name of the generic parameter. For example with `<T: Fooable>` the generic parameter `name` is `T`.
let name: String
Expand Down Expand Up @@ -2153,8 +2153,8 @@ extension Formatter {
self.conformances = conformances
}

// The opaque parameter syntax that represents this generic type,
// if the constraints can be expressed using this syntax
/// The opaque parameter syntax that represents this generic type,
/// if the constraints can be expressed using this syntax
func asOpaqueParameter(useSomeAny: Bool) -> [Token]? {
// Protocols with primary associated types that can be used with
// opaque parameter syntax. In the future we could make this extensible
Expand Down Expand Up @@ -2850,14 +2850,14 @@ extension Formatter {
closureLocalNames.insert("self")
}

/// Whether or not the closure at the current index permits implicit self.
///
/// SE-0269 (in Swift 5.3) allows implicit self when:
/// - the closure captures self explicitly using [self] or [unowned self]
/// - self is not a reference type
///
/// SE-0365 (in Swift 5.8) additionally allows implicit self using
/// [weak self] captures after self has been unwrapped.
// Whether or not the closure at the current index permits implicit self.
//
// SE-0269 (in Swift 5.3) allows implicit self when:
// - the closure captures self explicitly using [self] or [unowned self]
// - self is not a reference type
//
// SE-0365 (in Swift 5.8) additionally allows implicit self using
// [weak self] captures after self has been unwrapped.
func closureAllowsImplicitSelf() -> Bool {
guard options.swiftVersion >= "5.3" else {
return false
Expand Down
2 changes: 1 addition & 1 deletion Sources/OptionDescriptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import Foundation

class OptionDescriptor {
enum ArgumentType: EnumAssociable {
// index 0 is official value, others are acceptable
/// index 0 is official value, others are acceptable
case binary(true: [String], false: [String])
case `enum`([String])
case text
Expand Down
Loading

0 comments on commit 1f8b956

Please sign in to comment.