Skip to content

Instantly share code, notes, and snippets.

@sinitcin
Created September 25, 2017 11:09
Show Gist options
  • Save sinitcin/3a31bdb32281365bbe3194b0fb4d7961 to your computer and use it in GitHub Desktop.
Save sinitcin/3a31bdb32281365bbe3194b0fb4d7961 to your computer and use it in GitHub Desktop.
LOR1
#[derive(Debug, Default, Clone, Copy)]
struct LexerT<'a> {
pos: usize,
text: &'a str,
token: &'a str,
}
fn next_token(state: LexerT) -> Option<LexerT> {
let mut start_pos = 0;
let mut end_pos = start_pos;
let ref slice = state.text[state.pos .. state.text.len()];
for ch in slice.chars() {
if ch.is_alphabetic() {
end_pos += 1;
} else if start_pos == end_pos {
if ch.is_whitespace() {
start_pos += 1;
end_pos += 1;
continue;
} else {
end_pos += 1;
break;
}
} else {
break;
}
}
if start_pos != end_pos {
Some(LexerT {pos: end_pos, text: slice, token: &slice[start_pos..end_pos]})
} else {
None
}
}
fn main() {
let mut lexer = LexerT {pos: 0, text: "Hello, world!", token: ""};
while let Some(lexer_now) = next_token(lexer) {
lexer = lexer_now;
println!("{:?}", lexer_now);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment