Crates.io | reglex |
lib.rs | reglex |
version | 1.1.0 |
source | src |
created_at | 2022-02-05 19:43:32.649485 |
updated_at | 2022-02-06 11:31:27.674482 |
description | A rust lexer generator using regex |
homepage | https://github.com/nph278/reglex |
repository | https://github.com/nph278/reglex |
max_upload_size | |
id | 527545 |
size | 9,347 |
A small rust library for creating regex-based lexers
use reglex::{RuleList, rule_list, lex};
#[derive(Debug, PartialEq)]
enum Token {
Keyword,
Number(u64),
Left,
Right,
}
fn lexer(input: &String) -> Result<Vec<Token>, usize> {
let regexes: RuleList<Token> = rule_list! [
"kw" => |_| Some(Token::Keyword),
r"\d+" => |s: &str| Some(Token::Number(s.parse().unwrap())),
r"\{" => |_| Some(Token::Left),
r"\}" => |_| Some(Token::Right),
r"\s" => |_| None
];
lex(®exes, input)
}
fn main() {
assert_eq!(
lexer(&"kw { 12 53 }".to_string()),
Ok(vec![
Token::Keyword,
Token::Left,
Token::Number(12),
Token::Number(53),
Token::Right
])
);
assert_eq!(lexer(&"kw ERROR! { 12 53 }".to_string()), Err(3));
}