Skip to content

Instantly share code, notes, and snippets.

@harlanhaskins
Created August 10, 2017 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harlanhaskins/b2ed96b64a551214a7f2c7717c285dce to your computer and use it in GitHub Desktop.
Save harlanhaskins/b2ed96b64a551214a7f2c7717c285dce to your computer and use it in GitHub Desktop.
Swift Format
import Foundation
import SwiftSyntax
/// Ensures all opening braces and brackets appear on the same line
/// as the previous token.
class FixBraces: SyntaxRewriter {
override func visit(_ token: TokenSyntax) -> Syntax {
switch token.tokenKind {
case .leftBrace, .leftSquareBracket:
return token.withLeadingTrivia(.spaces(1))
default:
return token
}
}
}
/// Ensure all colons have 0 spaces before them.
class FixColons: SyntaxRewriter {
override func visit(_ token: TokenSyntax) -> Syntax {
// The child after this one, if there is one.
let sibling = token.parent?.child(at: token.indexInParent + 1)
// If the next token is a colon, remove the trailing trivia from this
// token.
guard let nextToken = sibling as? TokenSyntax,
case .colon = nextToken.tokenKind else { return token }
return token.withoutTrailingTrivia()
}
}
/// Ensures all large integers have _'s in each of the hundreds/
/// thousands/etc place.
class FixIntegers: SyntaxRewriter {
func reSplitInteger(_ literal: String) -> String {
let pieces = literal.split(separator: "_")
let noSplit = pieces.joined(separator: "")
var fixed = ""
for (offset, char) in noSplit.reversed().enumerated() {
if offset != 0 && offset % 3 == 0 {
fixed.insert("_", at: fixed.startIndex)
}
fixed.insert(char, at: fixed.startIndex)
}
return fixed
}
override func visit(_ token: TokenSyntax) -> Syntax {
guard case .integerLiteral(let text) = token.tokenKind else {
return token
}
let fixed = reSplitInteger(text)
return token.withKind(.integerLiteral(fixed))
}
}
guard CommandLine.arguments.count > 1 else {
print("usage: fixintegers [file]")
exit(-1)
}
do {
let url = URL(fileURLWithPath: CommandLine.arguments[1])
let file = try Syntax.parse(url)
let integersFixed = FixIntegers().visit(file)
let bracesFixed = FixBraces().visit(integersFixed)
let colonsFixed = FixColons().visit(bracesFixed)
try "\(colonsFixed)".write(to: url, atomically: true,
encoding: .utf8)
} catch {
print("error: \(error)")
exit(-1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment