Skip to content

Instantly share code, notes, and snippets.

@hollance
Created December 28, 2016 19:00
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 hollance/3cf72385ef7c2e5c414b4c3286225039 to your computer and use it in GitHub Desktop.
Save hollance/3cf72385ef7c2e5c414b4c3286225039 to your computer and use it in GitHub Desktop.
Simple recursive descent parser
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