Slide 1

Slide 1 text

Swiftly Swift manipulation... with Swift FrenchKit 2019 Marcin Krzyzanowski

Slide 2

Slide 2 text

Agenda • Problem • Introduce SwiftSyntax • github.com/krzyzanowskim/reorder • IndexSourceDB

Slide 3

Slide 3 text

PROBLEM https://twitter.com/krzyzanowskim/status/1162306459075588096

Slide 4

Slide 4 text

import Foundation public class Conference { public var name: String public let venue: String INPUT

Slide 5

Slide 5 text

public class Conference { public var name: String public let venue: String internal typealias Line = String private var attendees: Set private var sponsors: Set private var costs: Array internal func add(attendee: String) internal func add(sponsor: String) deinit internal func add(cost: Decimal) private init() public func totalCosts() -> Decimal private func statement() -> Array internal func printStatement() public init(name: String, venue: String) } API

Slide 6

Slide 6 text

public class Conference { public var name: String public let venue: String internal typealias Line = String private var attendees: Set private var sponsors: Set private var costs: Array public init(name: String, venue: String) private init() deinit public func totalCosts() -> Decimal internal func add(attendee: String) internal func add(sponsor: String) internal func add(cost: Decimal) internal func printStatement() private func statement() -> Array } API Initializer Public Internal Private

Slide 7

Slide 7 text

public class Conference { public var name: String public let venue: String internal typealias Line = String private var attendees: Set private var sponsors: Set private var costs: Array internal func add(attendee: String) internal func add(sponsor: String) deinit internal func add(cost: Decimal) private init() public func totalCosts() -> Decimal private func statement() -> Array internal func printStatement() public init(name: String, venue: String) } public class Conference { public var name: String public let venue: String internal typealias Line = String private var attendees: Set private var sponsors: Set private var costs: Array public init(name: String, venue: String) private init() deinit public func totalCosts() -> Decimal internal func add(attendee: String) internal func add(sponsor: String) internal func add(cost: Decimal) internal func printStatement() private func statement() -> Array } →

Slide 8

Slide 8 text

HOW? move lines by hand use editor plugin use existing command line tool write a tool by my own

Slide 9

Slide 9 text

HOW? move lines by hand use editor plugin use existing command line tool write a tool by my own

Slide 10

Slide 10 text

HOW? move lines by hand use editor plugin use existing command line tool write a tool by my own

Slide 11

Slide 11 text

HOW? move lines by hand use editor plugin use existing command line tool write a tool by my own nicklockwood/SwiftFormat google/swift (format) inamiy/SwiftRewriter

Slide 12

Slide 12 text

HOW? move lines by hand use editor plugin use existing command line tool write a tool by my own

Slide 13

Slide 13 text

HOW? HOW? write a tool by my own Brain + Time + Computer + Programming Language + Library + ⏲ + + C +

Slide 14

Slide 14 text

you have brain

Slide 15

Slide 15 text

The Internet

Slide 16

Slide 16 text

SwiftSyntax github.com/apple/swift-syntax Source Code text/plain Abstract Syntax Tree

Slide 17

Slide 17 text

SwiftSyntax github.com/apple/swift-syntax Abstract Syntax Tree Syntax Syntax Syntax Syntax Syntax Syntax

Slide 18

Slide 18 text

SwiftSyntax Syntax Syntax Syntax Syntax Syntax Syntax Visitor Design Pattern The visitor design pattern is a way of separating an algorithm from an object structure on which it operates

Slide 19

Slide 19 text

SwiftSyntax import SwiftSyntax struct Visitor: SyntaxVisitor { mutating func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { self.process(node) return .skipChildren } }

Slide 20

Slide 20 text

SwiftSyntax class Rewriter: SyntaxRewriter { init() { } override func visit(_ node: DeinitializerDeclSyntax) -> DeclSyntax { return SyntaxFactory.makeBlankClassDecl() } }

Slide 21

Slide 21 text

PLAN 1. Search for all declarations (func, init, deinit) 2. Sort functions by access level and kind 3. Rewrite source with new order 4. Output source code

Slide 22

Slide 22 text

class Indexer: SyntaxVisitor { private var functions: Array = [] func visit(_ node: DeinitializerDeclSyntax) -> SyntaxVisitorContinueKind{ self.functions.append(node) return .skipChildren } func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { self.functions.append(node) return .skipChildren } func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { self.functions.append(node) return .skipChildren } } Indexer 1. Search for all declarations (func, init, deinit)

Slide 23

Slide 23 text

func sorted() -> Array { Sort 2. Sort functions by access level and kind

Slide 24

Slide 24 text

Rewrite class Rewriter: SyntaxRewriter { private let indexer: Indexer private var sortedFunctions: Array init(_ indexer: Indexer) { self.indexer = indexer self.sortedFunctions = indexer.sorted() } override func visit(_ node: DeinitializerDeclSyntax) -> DeclSyntax { sortedFunctions.removeFirst() } override func visit(_ node: InitializerDeclSyntax) -> DeclSyntax { sortedFunctions.removeFirst() } override func visit(_ node: FunctionDeclSyntax) -> DeclSyntax { sortedFunctions.removeFirst() } } 3. Rewrite source with new order

Slide 25

Slide 25 text

public func process(_ data: Data) throws -> String { guard let source = String(data: data, encoding: .utf8) else { throw Error.invalidInput } let parsed: SourceFileSyntax = try SyntaxParser.parse(source: source) // Gather information about the file var visitor = Indexer() parsed.walk(&visitor) // Rewrite file using visitor let rewritten = Rewriter(visitor).visit(parsed) var output = StringOutputStream() rewritten.write(to: &output) return output.string } Processor 4. Output source code

Slide 26

Slide 26 text

// // swift run reorder -file Sources/Conference/Conference.swift > output.swift // guard let executablePath = CommandLine.arguments.first else { fatalError("Missing executable") } let args = Array(CommandLine.arguments.dropFirst()) let commands = stride(from: 0, to: args.count - 1, by: 2).map { (command: args[$0].dropFirst(), value: args[$0+1]) } var err = StderrOutputStream() var out = StdoutOutputStream() for (cmd, value) in commands { switch cmd { case "file": err.write("Processing \(value)\n") let content = try Data(contentsOf: URL(fileURLWithPath: value)) let result = try Processor().process(content) out.write(result) break default: err.write("Error: Unknown command: \(cmd)\n") $ ./reorder -file Conference.swift

Slide 27

Slide 27 text

import Foundation public class Conference { public var name: String public let venue: String internal typealias Line = String private var attendees: Set private var sponsors: Set private var costs: Array public init(name: String, venue: String) { self.name = name self.venue = venue self.attendees = [] self.sponsors = [] self.costs = [] } private init() { self.name = "FrenchKit" self.venue = "Bâtiment" self.attendees = [] $ ./reorder -file Conference.swift

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

• Sort class/struct properties • Sort within extension scope • Sort static func/property HOMEWORK github.com/krzyzanowskim/reorder Submit Pull Request!

Slide 30

Slide 30 text

ONE MORE THING

Slide 31

Slide 31 text

IndexStoreDB IndexStoreDB is a source code indexing library. It provides a composable and efficient query API for looking up source code symbols, symbol occurrences, and relations. github.com/apple/indexstore-db

Slide 32

Slide 32 text

IndexStoreDB IndexStoreDB is a source code indexing library. It provides a composable and efficient query API for looking up source code symbols, symbol occurrences, and relations. github.com/apple/indexstore-db swift build --enable-index-store .build/x86_64-apple-macosx/debug/index/store

Slide 33

Slide 33 text

IndexStoreDB github.com/apple/indexstore-db $ swiftc -index-store-path index -index-file Sources/Conference/Conference.swift

Slide 34

Slide 34 text

StoreIndexer public struct StoreIndexer { public typealias Path = String public struct Function { public let symbol: Symbol public let location: SymbolLocation } private let indexURL: URL

Slide 35

Slide 35 text

IndexStoreDB 1. StoreIndexer fetch all files where Conference occurs 2. SwiftSyntax process files and output

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

ONE MISSING THING //===-------------------------------------------------------===// // SourceKit README //===-------------------------------------------------------===// Welcome to SourceKit! SourceKit is a framework for supporting IDE features like indexing, syntax-coloring, code-completion, etc. In general it provides the infrastructure that an IDE needs for excellent language support. SourceKit currently only supports the Swift language.

Slide 38

Slide 38 text

LINKS Building a Compiler in Swift - Nick Lockwood https://www.youtube.com/watch?v=uQNkrV0F07Q N. Hawes & A. Lorenz “Adding Index‐While‐Building and ..." https://www.youtube.com/watch?v=jGJhnIT-D2M Creating Refactoring Transformations for Swift https://www.skilled.io/u/swiftsummit/creating-refactoring-transformations-for-swift NSHipster - Swift Syntax https://nshipster.com/swiftsyntax/ reorder https://github.com/krzyzanowskim/reorder

Slide 39

Slide 39 text

THANK YOU @krzyzanowskim github.com/krzyzanowskim https://swift.best