-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAsmParser.swift
67 lines (62 loc) · 2.06 KB
/
AsmParser.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class AsmParser {
let contents: String
var output: String
var cursor: String.Index
var startComment: Bool {
contents[cursor] == "/" && contents[contents.index(after: cursor)] == "*"
}
var endComment: Bool {
contents[cursor] == "*" && contents[contents.index(after: cursor)] == "/"
}
var isMacroLine: Bool {
contents[cursor] == "#"
}
init(contents: String) {
self.contents = contents
self.cursor = contents.startIndex
self.output = ""
}
func advanceCursor(offset: Int = 1) {
cursor = contents.index(cursor, offsetBy: offset)
}
func writeOutput<S: StringProtocol>(_ outContent: S) {
output += outContent
}
func writeOutput(_ outContent: Character) {
writeOutput(String(outContent))
}
func parse() {
while cursor < contents.endIndex {
if isMacroLine {
while !contents[cursor].isNewline {
writeOutput(contents[cursor])
advanceCursor(offset: 1)
}
writeOutput(contents[cursor])
advanceCursor(offset: 1) // Skip '\n'
continue
} else if startComment {
while !endComment {
writeOutput(contents[cursor])
advanceCursor(offset: 1)
}
writeOutput(contents[cursor..<contents.index(cursor, offsetBy: 2)])
advanceCursor(offset: 2) // Skip '*/'
continue
} else if contents[cursor].isNewline {
advanceCursor(offset: 1)
writeOutput("\n")
} else {
writeOutput("\"")
while !contents[cursor].isNewline && !startComment {
writeOutput(contents[cursor])
advanceCursor(offset: 1)
}
writeOutput("\\n\"")
if startComment { continue }
advanceCursor(offset: 1)
writeOutput("\n")
}
}
}
}