Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Jintin committed Feb 12, 2017
1 parent 33ea33f commit d2df7e1
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 101 deletions.
3 changes: 1 addition & 2 deletions CLI/OptionParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ class Options {
Indent.size = -1
}


static let options: [Option] = [
Option(options: ["-h", "--help"],
helpArguments: "",
Expand Down Expand Up @@ -60,7 +59,7 @@ class Options {
number: 0,
setter: { _ in
shared.verbose = true
}),
})
]

static func printHeader() {
Expand Down
14 changes: 13 additions & 1 deletion CLI/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,24 @@ func getFileType(for file: URL) -> FileType {
}
}

func chidDir(parent: URL) -> [URL] {
do {
let result = try FileManager.default
.contentsOfDirectory(atPath: parent.path).map {
URL(fileURLWithPath: $0, relativeTo: parent)
}
return result
} catch {
return []
}
}

func expandDirectory(at path: String, recursively: Bool) -> [URL] {
let parent = URL(fileURLWithPath: path)
switch getFileType(for: parent) {
case .directory:
var files = [URL]()
for child in (try? FileManager.default.contentsOfDirectory(atPath: parent.path).map({ URL(fileURLWithPath: $0, relativeTo: parent) })) ?? [] {
for child in chidDir(parent: parent) {
if recursively && getFileType(for: child) == .directory {
files.append(contentsOf: expandDirectory(at: child.path, recursively: recursively))
} else {
Expand Down
3 changes: 2 additions & 1 deletion Extension/SourceEditorCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import XcodeKit

class SourceEditorCommand: NSObject, XCSourceEditorCommand {

func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Swift.Void) {
func perform(with invocation: XCSourceEditorCommandInvocation,
completionHandler: @escaping (Error?) -> Swift.Void) {

let uti = invocation.buffer.contentUTI
if uti != "com.apple.dt.playground" && uti != "public.swift-source" {
Expand Down
8 changes: 0 additions & 8 deletions Extension/SourceEditorExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,6 @@ import XcodeKit
class SourceEditorExtension: NSObject, XCSourceEditorExtension {

func extensionDidFinishLaunching() {
// If your extension needs to do any work at launch, implement this optional method.
// print("extensionDidFinishLaunching")
}

// var commandDefinitions: [[XCSourceEditorCommandDefinitionKey: Any]] {
// print("commandDefinitions")
// // If your extension needs to return a collection of command definitions that differs from those in its Info.plist, implement this optional property getter.
// return []
// }

}
16 changes: 8 additions & 8 deletions Parser/Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ extension String {
break
}
}
// TODO: no need to new obj
// MARK: no need to new obj
if reFormat {
let obj = try SwiftParser(string: result).format()
return (obj, target)
Expand Down Expand Up @@ -202,7 +202,7 @@ extension String {
let list: [Character] = ["?", "!", "."]
while target < endIndex {
let next = self[target]
if next.isAZ() || list.contains(next) { // TODO: check complex case
if next.isAZ() || list.contains(next) { // MARK: check complex case
result.append(next)
target = index(after: target)
} else if next == "[" {
Expand Down Expand Up @@ -233,7 +233,6 @@ extension String {
var result = "<"
while target < endIndex {
let next = self[target]

switch next {
case " ":
result.keepSpace()
Expand Down Expand Up @@ -265,13 +264,13 @@ extension String {
result += block.string
continue
case "-":
if let end = index(target, offsetBy: 2, limitedBy: endIndex), let _ = range(of: "->", options: [], range: target ..< end) {
result.keepSpace()
result.append("->")
if isNext(string: "->", length: 2, strIndex: target) {
result.keepSpace()
result.append("-> ")
target = index(target, offsetBy: 2)
continue
}
return nil
default:
return nil
}
Expand All @@ -281,9 +280,10 @@ extension String {
return nil
}

//TODO: remove duplicate in Parser.swift
// MARK: remove duplicate in Parser.swift
func isNext(string target: String, length: Int, strIndex: String.Index) -> Bool {
if let stopIndex = self.index(strIndex, offsetBy: length, limitedBy: endIndex), let _ = self.range(of: target, options: [], range: strIndex ..< stopIndex) {
if let stopIndex = self.index(strIndex, offsetBy: length, limitedBy: endIndex),
let _ = self.range(of: target, options: [], range: strIndex ..< stopIndex) {
return true
}
return false
Expand Down
19 changes: 12 additions & 7 deletions Parser/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ extension SwiftParser {
}
}

func isBetween(words: (start: String, end: String, endLength: Int)...) -> Bool { //TODO:check word, not position
func isBetween(words: (start: String, end: String, endLength: Int)...) -> Bool {
// MARK: check word, not position
if strIndex < string.endIndex {
let startIndex = string.nextNonSpaceIndex(strIndex)
for word in words {
if let endIndex = string.index(startIndex, offsetBy: word.endLength, limitedBy: string.endIndex), let _ = string.range(of: word.end, options: [], range: startIndex ..< endIndex) {
if retString.lastWord() == word.start { //TODO: cache last word
if let endIndex = string.index(startIndex, offsetBy: word.endLength, limitedBy: string.endIndex),
let _ = string.range(of: word.end, options: [], range: startIndex ..< endIndex) {
if retString.lastWord() == word.start { // MARK: cache last word
return true
}
}
Expand All @@ -28,7 +30,8 @@ extension SwiftParser {

func isNext(word: String, length: Int) -> Bool {
let index = string.nextNonSpaceIndex(strIndex)
if let endIndex = string.index(index, offsetBy: length, limitedBy: string.endIndex), let _ = string.range(of: word, options: [], range: index ..< endIndex) {
if let endIndex = string.index(index, offsetBy: length, limitedBy: string.endIndex),
let _ = string.range(of: word, options: [], range: index ..< endIndex) {
return true
}
return false
Expand All @@ -37,16 +40,18 @@ extension SwiftParser {
func isNext(words: (str: String, length: Int)...) -> Bool {
let index = string.nextNonSpaceIndex(strIndex)
for word in words {
if let endIndex = string.index(index, offsetBy: word.length, limitedBy: string.endIndex), let _ = string.range(of: word.str, options: [], range: index ..< endIndex) {
if let endIndex = string.index(index, offsetBy: word.length, limitedBy: string.endIndex),
let _ = string.range(of: word.str, options: [], range: index ..< endIndex) {
return true
}
}
return false
}

//TODO: move to Entension.swift
// MARK: move to Entension.swift
func isNext(string target: String, length: Int) -> Bool {
if let endIndex = string.index(strIndex, offsetBy: length, limitedBy: string.endIndex), let _ = string.range(of: target, options: [], range: strIndex ..< endIndex) {
if let endIndex = string.index(strIndex, offsetBy: length, limitedBy: string.endIndex),
let _ = string.range(of: target, options: [], range: strIndex ..< endIndex) {
return true
}
return false
Expand Down
3 changes: 1 addition & 2 deletions Parser/Pref.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation

enum Pref: String {
case paraAlign = "paraAlign"
case paraAlign

static func getUserDefaults() -> UserDefaults {
return UserDefaults.init(suiteName: "com.jintin.swimat.config")!
Expand All @@ -20,4 +20,3 @@ enum Pref: String {
}

}

123 changes: 67 additions & 56 deletions Parser/SwiftParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,34 @@ enum FormatError: Error {
case stringError
}

let operatorList: [Character: [(String, Int)]] = [
"+": [("+=<", 3), ("+=", 2), ("+++=", 4), ("+++", 3), ("+", 1)],
"-": [("->", 2), ("-=", 2), ("-<<", 3)],
"*": [("*=", 2), ("*", 1)],
"/": [("/=", 2), ("/", 1)],
"~": [("~=", 2), ("~~>", 3), ("~>", 2)],
"%": [("%=", 2), ("%", 1)],
"^": [("^=", 2)],
"&": [("&&=", 3), ("&&&", 3), ("&&", 2), ("&=", 2), ("&+", 2), ("&-", 2), ("&*", 2), ("&/", 2), ("&%", 2)],
"<": [("<<<", 3), ("<<=", 3), ("<<", 2), ("<=", 2), ("<~~", 3), ("<~", 2), ("<--", 3), ("<-<", 3), ("<-", 2), ("<^>", 3), ("<|>", 3), ("<*>", 3), ("<||?", 4), ("<||", 3), ("<|?", 3), ("<|", 2), ("<", 1)],
">": [(">>>", 3), (">>=", 3), (">>-", 3), (">>", 2), (">=", 2), (">->", 3), (">", 1)],
"|": [("|||", 3), ("||=", 3), ("||", 2), ("|=", 2), ("|", 1)],
"!": [("!==", 3), ("!=", 2)],
"=": [("===", 3), ("==", 2), ("=", 1)]
]
let operatorList: [Character: [(String, Int)]] =
[
"+": [("+=<", 3), ("+=", 2), ("+++=", 4), ("+++", 3), ("+", 1)],
"-": [("->", 2), ("-=", 2), ("-<<", 3)],
"*": [("*=", 2), ("*", 1)],
"/": [("/=", 2), ("/", 1)],
"~": [("~=", 2), ("~~>", 3), ("~>", 2)],
"%": [("%=", 2), ("%", 1)],
"^": [("^=", 2)],
"&": [("&&=", 3), ("&&&", 3), ("&&", 2), ("&=", 2), ("&+", 2),
("&-", 2), ("&*", 2), ("&/", 2), ("&%", 2)],
"<": [("<<<", 3), ("<<=", 3), ("<<", 2), ("<=", 2), ("<~~", 3),
("<~", 2), ("<--", 3), ("<-<", 3), ("<-", 2), ("<^>", 3),
("<|>", 3), ("<*>", 3), ("<||?", 4), ("<||", 3), ("<|?", 3),
("<|", 2), ("<", 1)],
">": [(">>>", 3), (">>=", 3), (">>-", 3), (">>", 2), (">=", 2),
(">->", 3), (">", 1)],
"|": [("|||", 3), ("||=", 3), ("||", 2), ("|=", 2), ("|", 1)],
"!": [("!==", 3), ("!=", 2)],
"=": [("===", 3), ("==", 2), ("=", 1)]
]

fileprivate let negativeCheckSigns: [Character] = ["+", "-", "*", "/", "&", "|", "^", "<", ">", ":", "(", "[", "{", "=", ",", ".", "?"]
fileprivate let negativeCheckKeys = ["case", "return", "if", "for", "while", "in"]
fileprivate let numbers: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
fileprivate let negativeCheckSigns: [Character] =
["+", "-", "*", "/", "&", "|", "^", "<", ">", ":", "(", "[", "{", "=", ",", ".", "?"]
fileprivate let negativeCheckKeys =
["case", "return", "if", "for", "while", "in"]
fileprivate let numbers: [Character] =
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

class SwiftParser {
let string: String
Expand All @@ -49,42 +58,13 @@ class SwiftParser {

func check(char: Character) throws -> String.Index {
switch char {
case "+", "*", "%", ">", "|", "=":
return space(with: operatorList[char]!)!
case "-":
if let index = space(with: operatorList[char]!) {
return index
} else {
var noSpace = false
if !retString.isEmpty {
// check scientific notation
if strIndex != string.endIndex {
if retString.last == "e" && numbers.contains(string[string.index(after: strIndex)]) {
noSpace = true
}
}
// check negative
let last = retString.lastNonSpaceChar(retString.endIndex)
if last.isAZ() {
if negativeCheckKeys.contains(retString.lastWord()) {
noSpace = true
}
} else {
if negativeCheckSigns.contains(last) {
noSpace = true
}
}
}
if noSpace {
return add(char: char)
}
return space(with: "-", length: 1)
}
case "~", "^", "!", "&":
case "+", "*", "%", ">", "|", "=", "~", "^", "!", "&":
if let index = space(with: operatorList[char]!) {
return index
}
return add(char: char)
case "-":
return checkMinus(char: char)
case ".":
if isNext(char: ".") {
if isNext(string: "...", length: 3) {
Expand Down Expand Up @@ -112,7 +92,7 @@ class SwiftParser {
return space(with: operatorList[char]!)!
case "?":
if isNext(char: "?") {
// TODO: check double optional or nil check
// MARK: check double optional or nil check
return add(string: "??", length: 2)
} else if let ternary = try string.findTernary(from: strIndex) {
retString.keepSpace()
Expand All @@ -128,7 +108,7 @@ class SwiftParser {
case "#":
if isNext(string: "#if", length: 3) {
indent.count += 1
return addLine() //TODO: bypass like '#if swift(>=3)'
return addLine() // MARK: bypass like '#if swift(>=3)'
} else if isNext(string: "#else", length: 5) {
indent.count -= 1
trimWithIndent()
Expand Down Expand Up @@ -172,7 +152,7 @@ class SwiftParser {
}

retString += "{ "
return string.index(after: strIndex)//TODO: find next now space
return string.index(after: strIndex) // MARK: find next now space
} else {
return add(char: char)
}
Expand All @@ -184,7 +164,7 @@ class SwiftParser {
}

if char == "}" {
trimWithIndent(addExtra: false) // TODO: change to newline check
trimWithIndent(addExtra: false) // MARK: change to newline check
retString.keepSpace()
let next = string.index(after: strIndex)
if next < string.endIndex && string[next].isAZ() {
Expand All @@ -202,6 +182,37 @@ class SwiftParser {
return checkDefault(char: char)
}

func checkMinus(char: Character) -> String.Index {
if let index = space(with: operatorList[char]!) {
return index
} else {
var noSpace = false
if !retString.isEmpty {
// check scientific notation
if strIndex != string.endIndex {
if retString.last == "e" && numbers.contains(string[string.index(after: strIndex)]) {
noSpace = true
}
}
// check negative
let last = retString.lastNonSpaceChar(retString.endIndex)
if last.isAZ() {
if negativeCheckKeys.contains(retString.lastWord()) {
noSpace = true
}
} else {
if negativeCheckSigns.contains(last) {
noSpace = true
}
}
}
if noSpace {
return add(char: char)
}
return space(with: "-", length: 1)
}
}

func checkLine(_ char: Character, checkLast: Bool = true) -> String.Index {
trim()
newlineIndex = retString.endIndex
Expand Down Expand Up @@ -244,7 +255,7 @@ class SwiftParser {
switch char {
case "+", "-", "*", "=", ".":
return 1
case "/": // TODO: check word, nor char
case "/": // MARK: check word, nor char
break
case ":":
if !self.indent.inSwitch {
Expand Down Expand Up @@ -278,7 +289,7 @@ class SwiftParser {
}
}
indent.extra = 0
// TODO: check next if ? :
// MARK: check next if ? :
}
}

Expand Down
5 changes: 2 additions & 3 deletions Swimat/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {

func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application

}

func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application

}

func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}

}

Loading

0 comments on commit d2df7e1

Please sign in to comment.