Lex simple parentheses

This commit is contained in:
Eryn Wells 2016-12-16 10:10:05 -08:00
parent 3840f9ee02
commit a0eb34f9a2

View file

@ -9,7 +9,7 @@
import Foundation import Foundation
struct Token { struct Token: CustomDebugStringConvertible {
enum Kind { enum Kind {
case LeftParen case LeftParen
case RightParen case RightParen
@ -17,24 +17,38 @@ struct Token {
let kind: Kind let kind: Kind
let value: String let value: String
// MARK: CustomDebugStringConvertible
var debugDescription: String {
return "Token(kind: .\(kind), value: \"\(value)\")"
}
} }
class Lexer: IteratorProtocol { class Lexer {
typealias Element = Token
let input: String let input: String
private var index: String.Index var index: String.Index
init(input: String) { init(input: String) {
self.input = input self.input = input
self.index = input.startIndex self.index = input.startIndex
} }
}
// MARK: IteratorProtocol extension Lexer: Sequence, IteratorProtocol {
typealias Element = Token
func makeIterator() -> Lexer {
return self
}
func next() -> Token? { func next() -> Token? {
guard index != input.endIndex else {
return nil
}
var token: Token? var token: Token?
while token == nil { while token == nil {
let c = input[index] let c = input[index]
@ -46,6 +60,7 @@ class Lexer: IteratorProtocol {
default: default:
break break
} }
index = input.index(after: index)
} }
return token return token
} }