Skip to content

Commit

Permalink
Add --guardelse option
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Jul 30, 2020
1 parent b031d85 commit 50a7131
Show file tree
Hide file tree
Showing 23 changed files with 283 additions and 57 deletions.
1 change: 1 addition & 0 deletions Rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ next line).
Option | Description
--- | ---
`--elseposition` | Placement of else/catch: "same-line" (default) or "next-line"
`--guardelse` | Guard else: "same-line", "next-line" or "auto" (default)

<details>
<summary>Examples</summary>
Expand Down
4 changes: 2 additions & 2 deletions Snapshots/Euclid/Sources/Polygon.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ public extension Polygon {
/// Vertices are assumed to be in anticlockwise order for the purpose of deriving the plane
init?(_ vertices: [Vertex], material: Material = nil) {
guard vertices.count > 2, !verticesAreDegenerate(vertices),
let plane = Plane(points: vertices.map { $0.position }) else
{
let plane = Plane(points: vertices.map { $0.position })
else {
return nil
}
self.init(unchecked: vertices, plane: plane, material: material)
Expand Down
8 changes: 4 additions & 4 deletions Snapshots/Expression/Examples/Colors/UIColor+Expression.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ private let functions: [AnyExpression.Symbol: AnyExpression.SymbolEvaluator] = [
.function("rgb", arity: 3): { args in
guard let r = args[0] as? Double,
let g = args[1] as? Double,
let b = args[2] as? Double else
{
let b = args[2] as? Double
else {
throw AnyExpression.Error.message("Type mismatch")
}
return UIColor(
Expand All @@ -42,8 +42,8 @@ private let functions: [AnyExpression.Symbol: AnyExpression.SymbolEvaluator] = [
guard let r = args[0] as? Double,
let g = args[1] as? Double,
let b = args[2] as? Double,
let a = args[3] as? Double else
{
let a = args[3] as? Double
else {
throw Expression.Error.message("Type mismatch")
}
return UIColor(
Expand Down
16 changes: 8 additions & 8 deletions Snapshots/Expression/Sources/Expression.swift
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,8 @@ public final class Expression: CustomStringConvertible {
if let array = arrays[name] {
return { args in
guard let index = Int(exactly: floor(args[0])),
array.indices.contains(index) else
{
array.indices.contains(index)
else {
throw Error.arrayBounds(symbol, args[0])
}
return array[index]
Expand Down Expand Up @@ -433,8 +433,8 @@ public final class Expression: CustomStringConvertible {
public static func isValidOperator(_ string: String) -> Bool {
var characters = UnicodeScalarView(string)
guard case let .symbol(symbol, _, _)? = characters.parseOperator(),
case let .infix(name) = symbol, name != "(", name != "[" else
{
case let .infix(name) = symbol, name != "(", name != "["
else {
return false
}
return characters.isEmpty
Expand Down Expand Up @@ -1254,8 +1254,8 @@ private extension UnicodeScalarView {

mutating func parseEscapedIdentifier() -> Subexpression? {
guard let delimiter = first,
var string = scanCharacter({ "`'\"".unicodeScalars.contains($0) }) else
{
var string = scanCharacter({ "`'\"".unicodeScalars.contains($0) })
else {
return nil
}
while let part = scanCharacters({ $0 != delimiter && $0 != "\\" }) {
Expand Down Expand Up @@ -1289,8 +1289,8 @@ private extension UnicodeScalarView {
return .error(.unexpectedToken("}"), string)
}
guard let codepoint = Int(hex, radix: 16),
let c = UnicodeScalar(codepoint) else
{
let c = UnicodeScalar(codepoint)
else {
// TODO: better error for invalid codepoint?
return .error(.unexpectedToken(hex), string)
}
Expand Down
4 changes: 2 additions & 2 deletions Snapshots/Layout/Layout/LayoutError+LayoutNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,8 @@ func bestMatches(for symbol: String, in suggestions: Set<String>) -> [String] {
let lowercaseString = string.lowercased()
// Eliminate keyPaths unless symbol itself is a keyPath or is part of result
guard !lowercaseString.contains(".") || symbol.contains(".") ||
lowercaseString.hasPrefix("\(lowercasedSymbol).") else
{
lowercaseString.hasPrefix("\(lowercasedSymbol).")
else {
return nil
}
return (string, levenshtein(lowercaseString, lowercasedSymbol))
Expand Down
8 changes: 4 additions & 4 deletions Snapshots/Layout/Layout/LayoutExpression.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ private let colorSymbols: [AnyExpression.Symbol: AnyExpression.SymbolEvaluator]
},
.function("rgba", arity: 4): { args in
guard let r = args[0] as? Double, let g = args[1] as? Double,
let b = args[2] as? Double, let a = args[3] as? Double else
{
let b = args[2] as? Double, let a = args[3] as? Double
else {
throw Expression.Error.message("Type mismatch")
}
return UIColor(red: CGFloat(r / 255), green: CGFloat(g / 255), blue: CGFloat(b / 255), alpha: CGFloat(a))
Expand Down Expand Up @@ -1221,8 +1221,8 @@ struct LayoutExpression {
case let .expression(expression):
guard expression.symbols.count == 1,
case let .variable(name) = expression.symbols.first!,
let first = name.first, !"'\"".contains(first) else
{
let first = name.first, !"'\"".contains(first)
else {
continue
}
var parent = node.parent
Expand Down
4 changes: 2 additions & 2 deletions Snapshots/Layout/Layout/LayoutLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,8 @@ class LayoutLoader {
) throws -> Layout {
assert(Thread.isMainThread)
guard let xmlURL = bundle.url(forResource: named, withExtension: nil) ??
bundle.url(forResource: named, withExtension: "xml") else
{
bundle.url(forResource: named, withExtension: "xml")
else {
throw LayoutError.message("No layout XML file found for \(named)")
}
var _layout: Layout?
Expand Down
4 changes: 2 additions & 2 deletions Snapshots/Layout/Layout/LayoutLoading.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public extension LayoutLoading {
assert(Thread.isMainThread)
let name = named ?? "\(type(of: self))".components(separatedBy: ".").last!
guard let xmlURL = bundle.url(forResource: name, withExtension: nil) ??
bundle.url(forResource: name, withExtension: "xml") else
{
bundle.url(forResource: name, withExtension: "xml")
else {
layoutError(.message("No layout XML file found for \(name)"))
return
}
Expand Down
8 changes: 4 additions & 4 deletions Snapshots/Layout/Layout/LayoutNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,8 @@ public class LayoutNode: NSObject {
) {
guard _setupComplete, _updateLock == 0, _evaluating.isEmpty,
root._setupComplete, root._updateLock == 0, root._evaluating.isEmpty,
let view = _view, !view.bounds.size.isNearlyEqual(to: _previousBounds.size) else
{
let view = _view, !view.bounds.size.isNearlyEqual(to: _previousBounds.size)
else {
return
}
root.update()
Expand All @@ -310,8 +310,8 @@ public class LayoutNode: NSObject {
children: [LayoutNode] = []
) throws {
guard let _class = `class` as? LayoutManaged.Type,
_class is UIView.Type || _class is UIViewController.Type else
{
_class is UIView.Type || _class is UIViewController.Type
else {
throw LayoutError.message("\(`class`) is not a subclass of UIView or UIViewController")
}
self._class = _class
Expand Down
8 changes: 4 additions & 4 deletions Snapshots/Layout/Layout/Properties.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ extension NSObject {
if let cattribs = property_getAttributes(cprop) {
var name = String(cString: cname)
guard !name.contains("_"), // We don't want to mess with private stuff
allProperties[name] == nil else
{
allProperties[name] == nil
else {
continue
}
// Get attributes
Expand Down Expand Up @@ -125,8 +125,8 @@ extension NSObject {
let selector: Selector = method_getName(method)
var name = "\(selector)"
guard name.hasPrefix("set"), let colonRange = name.range(of: ":"),
colonRange.upperBound == name.endIndex, !name.hasPrefix("set_") else
{
colonRange.upperBound == name.endIndex, !name.hasPrefix("set_")
else {
continue
}
name = String(name["set".endIndex ..< colonRange.lowerBound])
Expand Down
8 changes: 4 additions & 4 deletions Snapshots/Layout/Layout/RuntimeType.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ public class RuntimeType: NSObject {
}
let instanceName = sanitizedTypeName(typeName)
guard RuntimeType.responds(to: Selector(instanceName)),
let type = RuntimeType.value(forKey: instanceName) as? RuntimeType else
{
let type = RuntimeType.value(forKey: instanceName) as? RuntimeType
else {
return nil // No point updating cache, as it's already nil
}
queue.sync { cache[typeName] = type }
Expand Down Expand Up @@ -539,8 +539,8 @@ public class RuntimeType: NSObject {
// Return the human-readable name, without braces or underscores, etc
private func sanitizedStructName(_ objCType: String) -> String {
guard let equalRange = objCType.range(of: "="),
let braceRange = objCType.range(of: "{") else
{
let braceRange = objCType.range(of: "{")
else {
return objCType
}
let name: String = String(objCType[braceRange.upperBound ..< equalRange.lowerBound])
Expand Down
4 changes: 2 additions & 2 deletions Snapshots/Layout/Layout/UICollectionView+Layout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -349,8 +349,8 @@ extension UICollectionView {
public func dequeueReusableCellNode(withIdentifier identifier: String, for indexPath: IndexPath) -> LayoutNode {
do {
guard let layoutsData = objc_getAssociatedObject(self, &cellDataKey) as? NSMutableDictionary,
let layoutData = layoutsData[identifier] as? LayoutData else
{
let layoutData = layoutsData[identifier] as? LayoutData
else {
throw LayoutError.message("No cell layout has been registered for \(identifier)")
}
let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
Expand Down
4 changes: 2 additions & 2 deletions Snapshots/Layout/Layout/UIFont+Layout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ extension UIFont {
}
// Use the weight attribute as a fallback, but this is not very reliable for 3rd party fonts
guard let traits = fontDescriptor.object(forKey: UIFontDescriptor.AttributeName.traits) as? [UIFontDescriptor.TraitKey: Any],
let weight = traits[UIFontDescriptor.TraitKey.weight] as? UIFont.Weight else
{
let weight = traits[UIFontDescriptor.TraitKey.weight] as? UIFont.Weight
else {
fontWeights[fontName] = .regular
return UIFont.Weight.regular
}
Expand Down
8 changes: 4 additions & 4 deletions Snapshots/Layout/Layout/UITableView+Layout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,8 @@ extension UITableView {
// permanently hidden, which breaks layout. figure out why that is
}
guard let layoutsData = objc_getAssociatedObject(self, &headerDataKey) as? NSMutableDictionary,
let layoutData = layoutsData[identifier] as? LayoutData else
{
let layoutData = layoutsData[identifier] as? LayoutData
else {
return nil
}
var nodes = objc_getAssociatedObject(self, &nodesKey) as? NSMutableArray
Expand Down Expand Up @@ -423,8 +423,8 @@ extension UITableView {
return node
}
guard let layoutsData = objc_getAssociatedObject(self, &cellDataKey) as? NSMutableDictionary,
let layoutData = layoutsData[identifier] as? LayoutData else
{
let layoutData = layoutsData[identifier] as? LayoutData
else {
return nil
}
do {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import XCTest

private func url(forXml name: String) throws -> URL {
guard let url = Bundle(for: LayoutViewControllerTests.self)
.url(forResource: name, withExtension: "xml") else
{
.url(forResource: name, withExtension: "xml")
else {
throw NSError(domain: "Could not locate: \(name).xml", code: 0)
}
return url
Expand Down
8 changes: 4 additions & 4 deletions Snapshots/Layout/UIDesigner/EditViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ class EditViewController: UIViewController, UITextFieldDelegate {
classField?.backgroundColor = .white
guard let classField = classField,
let textRange = classField.textRange(from: classField.beginningOfDocument, to: classField.selectedTextRange?.start ?? classField.endOfDocument),
let text = classField.text(in: textRange) else
{
let text = classField.text(in: textRange)
else {
return
}
var match = ""
Expand Down Expand Up @@ -241,8 +241,8 @@ class EditViewController: UIViewController, UITextFieldDelegate {
}
classField?.attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
guard let cls = NSClassFromString(text) as? NSObject.Type,
cls is UIView.Type || cls is UIViewController.Type else
{
cls is UIView.Type || cls is UIViewController.Type
else {
classField?.backgroundColor = UIColor(red: 1, green: 0.5, blue: 0.5, alpha: 1)
return
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Inference.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ private struct Inference {
}
}
}
options.allmanBraces = (allman > knr)
options.allmanBraces = (allman > 1 && allman > knr)
}

let ifdefIndent = OptionInferrer { formatter, options in
Expand Down
10 changes: 10 additions & 0 deletions Sources/Options.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ public enum AttributeMode: String {
case preserve
}

/// Argument type for else position
public enum ElsePosition: String {
case sameLine = "same-line"
case nextLine = "next-line"
case auto
}

/// Version number wrapper
public struct Version: RawRepresentable, Comparable, ExpressibleByStringLiteral, CustomStringConvertible {
public let rawValue: String
Expand Down Expand Up @@ -277,6 +284,7 @@ public struct FormatOptions: CustomStringConvertible {
public var hoistPatternLet: Bool
public var stripUnusedArguments: ArgumentStrippingMode
public var elseOnNextLine: Bool
public var guardElsePosition: ElsePosition
public var explicitSelf: SelfMode
public var selfRequired: Set<String>
public var experimentalRules: Bool
Expand Down Expand Up @@ -335,6 +343,7 @@ public struct FormatOptions: CustomStringConvertible {
hoistPatternLet: Bool = true,
stripUnusedArguments: ArgumentStrippingMode = .all,
elseOnNextLine: Bool = false,
guardElsePosition: ElsePosition = .auto,
explicitSelf: SelfMode = .remove,
selfRequired: Set<String> = [],
experimentalRules: Bool = false,
Expand Down Expand Up @@ -385,6 +394,7 @@ public struct FormatOptions: CustomStringConvertible {
self.hoistPatternLet = hoistPatternLet
self.stripUnusedArguments = stripUnusedArguments
self.elseOnNextLine = elseOnNextLine
self.guardElsePosition = guardElsePosition
self.explicitSelf = explicitSelf
self.selfRequired = selfRequired
self.experimentalRules = experimentalRules
Expand Down
8 changes: 8 additions & 0 deletions Sources/OptionsDescriptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ extension FormatOptions.Descriptor {
letPatternPlacement,
stripUnusedArguments,
elsePosition,
guardElse,
explicitSelf,
selfRequired,
importGrouping,
Expand Down Expand Up @@ -545,6 +546,13 @@ extension FormatOptions.Descriptor {
trueValues: ["next-line", "nextline"],
falseValues: ["same-line", "sameline"]
)
static let guardElse = FormatOptions.Descriptor(
argumentName: "guardelse",
propertyName: "guardElsePosition",
displayName: "Guard Else Position",
help: "Guard else: \"same-line\", \"next-line\" or \"auto\" (default)",
keyPath: \.guardElsePosition
)
static let explicitSelf = FormatOptions.Descriptor(
argumentName: "self",
propertyName: "explicitSelf",
Expand Down
Loading

0 comments on commit 50a7131

Please sign in to comment.