Created
December 28, 2016 19:00
-
-
Save hollance/3cf72385ef7c2e5c414b4c3286225039 to your computer and use it in GitHub Desktop.
Simple recursive descent parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
let input = "15,7, 3 ,, [1,2,[3, 4, 5], 6],8" | |
//let input = "5,7,[1]" | |
var index = input.characters.startIndex | |
var lookahead = input[index] | |
var done = false | |
func eat() { | |
index = input.index(after: index) | |
if index != input.endIndex { | |
lookahead = input[index] | |
} else { | |
done = true | |
} | |
} | |
func bracket() -> String { | |
var symbol = "[" | |
eat() | |
while index != input.endIndex { | |
switch lookahead { | |
case "[": | |
symbol += bracket() | |
case "]": | |
eat() | |
return symbol + "]" | |
default: | |
symbol += String(lookahead) | |
eat() | |
} | |
} | |
fatalError("Missing closing ]") | |
} | |
func parseNext() -> String { | |
var symbol = "" | |
while index != input.endIndex { | |
switch lookahead { | |
case "[": | |
symbol += bracket() | |
case ",": | |
eat() | |
return symbol | |
default: | |
symbol += String(lookahead) | |
eat() | |
} | |
} | |
return symbol | |
} | |
var output: [String] = [] | |
while !done { | |
output.append(parseNext()) | |
} | |
print(output) | |
// Output is: ["15", "7", " 3 ", "", " [1,2,[3, 4, 5], 6]", "8"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment