assume utf-8

main
Alpha Chen 2 years ago
parent cba14f648a
commit 4525c22af9
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -6,7 +6,7 @@ pub fn compile(source: &str) -> Result<()> {
let mut line = None; let mut line = None;
loop { loop {
let token = scanner.scan()?; let token = scanner.scan();
if Some(token.line) != line { if Some(token.line) != line {
print!("{:4} ", token.line); print!("{:4} ", token.line);
line = Some(token.line); line = Some(token.line);

@ -15,7 +15,7 @@ impl<'a> Scanner<'a> {
} }
} }
pub fn scan(&mut self) -> Result<Token> { pub fn scan(&mut self) -> Token {
self.skip_whitespace(); self.skip_whitespace();
if self.peek().is_none() { if self.peek().is_none() {
@ -69,20 +69,20 @@ impl<'a> Scanner<'a> {
} }
} }
fn make_token(&self, kind: TokenKind) -> Result<Token> { fn make_token(&self, kind: TokenKind) -> Token {
Ok(Token { Token {
kind, kind,
value: std::str::from_utf8(&self.source[..self.current])?, value: std::str::from_utf8(&self.source[..self.current]).unwrap(),
line: self.line, line: self.line,
}) }
} }
fn error_token(&self, message: &'static str) -> Result<Token> { fn error_token(&self, message: &'static str) -> Token {
Ok(Token { Token {
kind: TokenKind::Error, kind: TokenKind::Error,
value: message, value: message,
line: self.line, line: self.line,
}) }
} }
fn advance(&mut self) -> char { fn advance(&mut self) -> char {
@ -135,7 +135,7 @@ impl<'a> Scanner<'a> {
self.source.get(self.current + 1).map(|&x| x as char) self.source.get(self.current + 1).map(|&x| x as char)
} }
fn string(&mut self) -> Result<Token> { fn string(&mut self) -> Token {
while matches!(self.peek(), Some(c) if c != '"') { while matches!(self.peek(), Some(c) if c != '"') {
if self.peek() == Some('\n') { if self.peek() == Some('\n') {
self.line += 1; self.line += 1;
@ -152,7 +152,7 @@ impl<'a> Scanner<'a> {
self.make_token(TokenKind::String) self.make_token(TokenKind::String)
} }
fn number(&mut self) -> Result<Token> { fn number(&mut self) -> Token {
while matches!(self.peek(), Some(c) if c.is_ascii_digit()) { while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
self.advance(); self.advance();
} }
@ -168,7 +168,7 @@ impl<'a> Scanner<'a> {
self.make_token(TokenKind::Number) self.make_token(TokenKind::Number)
} }
fn identifier(&mut self) -> Result<Token> { fn identifier(&mut self) -> Token {
while matches!(self.peek(), Some(c) if is_alpha(c) || c.is_ascii_digit()) { while matches!(self.peek(), Some(c) if is_alpha(c) || c.is_ascii_digit()) {
self.advance(); self.advance();
} }
@ -318,7 +318,7 @@ mod tests {
} }
fn assert_scan(scanner: &mut Scanner, kind: TokenKind) { fn assert_scan(scanner: &mut Scanner, kind: TokenKind) {
let token = scanner.scan().unwrap(); let token = scanner.scan();
assert_eq!(token.kind, kind); assert_eq!(token.kind, kind);
} }
} }

Loading…
Cancel
Save