///|
priv struct Lexer {
input : String
mut cursor : Int32
mut start : Int32
}
///|
fn Lexer::new(input : String) -> Lexer {
{ input, cursor: 0, start: 0, }
}
///|
fn Lexer::consume(self : Lexer, unit : UInt16) -> Bool {
if self.cursor < self.input.length() && self.input[self.cursor] == unit {
self.cursor += 1
true
} else {
false
}
}
// Diagnostics point to the start of the token in the original string.
///|
fn Lexer::next(self : Lexer) -> Token raise PluralError {
let input = self.input
let end = input.length()
while self.cursor < end {
match input[self.cursor] {
' ' | '\t' | '\n' | '\r' | 11 | 12 => self.cursor += 1
_ => break
}
}
self.start = self.cursor
if self.cursor == end {
return End
}
let unit = input[self.cursor]
if unit >= '0' && unit <= '9' {
let mut value : UInt64 = 0
let mut overflow = false
while self.cursor < end {
let next = input[self.cursor]
if next < '0' || next > '9' {
break
}
let digit = next.to_uint64() - 48
if value > (0xffffffffffffffffUL - digit) / 10 {
overflow = true
} else if !overflow {
value = value * 10 + digit
}
self.cursor += 1
}
if overflow {
raise IntegerOverflow(
lexeme=input[self.start:self.cursor].to_owned(),
pos=self.start,
)
}
return Number(value)
}
self.cursor += 1
match unit {
'n' => Variable
'(' => LeftParen
')' => RightParen
'?' => Question
':' => Colon
'+' => Operator(Add)
'-' => Operator(Sub)
'*' => Operator(Mul)
'/' => Operator(Div)
'%' => Operator(Mod)
'!' => if self.consume('=') { Operator(NotEq) } else { Not }
'<' => Operator(if self.consume('=') { LtEq } else { Lt })
'>' => Operator(if self.consume('=') { GtEq } else { Gt })
'=' if self.consume('=') => Operator(Eq)
'&' if self.consume('&') => Operator(LogicalAnd)
'|' if self.consume('|') => Operator(LogicalOr)
_ =>
raise UnexpectedChar(
ch=input.get_char(self.start).unwrap_or('\uFFFD'),
pos=self.start,
)
}
}