2023-09-25 23:06:03 +00:00
|
|
|
//! This example grabs input from stdin, lexes it, and prints which lexer rules matched
|
|
|
|
#![allow(unused_imports)]
|
2024-03-01 02:58:50 +00:00
|
|
|
use cl_lexer::Lexer;
|
2024-03-01 01:36:06 +00:00
|
|
|
use cl_token::Token;
|
2023-10-17 03:26:32 +00:00
|
|
|
use std::{
|
|
|
|
error::Error,
|
|
|
|
io::{stdin, IsTerminal, Read},
|
|
|
|
path::{Path, PathBuf},
|
|
|
|
};
|
2023-09-25 23:06:03 +00:00
|
|
|
|
2023-09-27 23:13:01 +00:00
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
2023-10-17 03:26:32 +00:00
|
|
|
let conf = Config::new();
|
|
|
|
if conf.paths.is_empty() {
|
|
|
|
take_stdin()?;
|
|
|
|
} else {
|
|
|
|
for path in conf.paths.iter().map(PathBuf::as_path) {
|
2023-10-22 23:28:20 +00:00
|
|
|
lex_tokens(&std::fs::read_to_string(path)?, Some(path))?;
|
2023-09-25 23:06:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
2023-09-27 23:13:01 +00:00
|
|
|
}
|
2023-10-17 03:26:32 +00:00
|
|
|
|
|
|
|
struct Config {
|
|
|
|
paths: Vec<PathBuf>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Config {
|
|
|
|
fn new() -> Self {
|
|
|
|
Config { paths: std::env::args().skip(1).map(PathBuf::from).collect() }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn take_stdin() -> Result<(), Box<dyn Error>> {
|
|
|
|
if stdin().is_terminal() {
|
|
|
|
for line in stdin().lines() {
|
2023-10-22 23:28:20 +00:00
|
|
|
lex_tokens(&line?, None)?
|
2023-10-17 03:26:32 +00:00
|
|
|
}
|
|
|
|
} else {
|
2023-10-22 23:28:20 +00:00
|
|
|
lex_tokens(&std::io::read_to_string(stdin())?, None)?
|
2023-10-17 03:26:32 +00:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-10-22 23:28:20 +00:00
|
|
|
fn lex_tokens(file: &str, path: Option<&Path>) -> Result<(), Box<dyn Error>> {
|
2023-10-17 03:26:32 +00:00
|
|
|
for token in Lexer::new(file) {
|
2023-10-22 23:28:20 +00:00
|
|
|
let token = match token {
|
|
|
|
Ok(t) => t,
|
|
|
|
Err(e) => {
|
|
|
|
println!("{e:?}");
|
2023-10-26 00:28:54 +00:00
|
|
|
continue;
|
2024-01-23 07:51:00 +00:00
|
|
|
}
|
2023-10-22 23:28:20 +00:00
|
|
|
};
|
2023-10-17 03:26:32 +00:00
|
|
|
if let Some(path) = path {
|
|
|
|
print!("{path:?}:")
|
|
|
|
}
|
2023-10-22 23:28:20 +00:00
|
|
|
print_token(token);
|
2023-10-17 03:26:32 +00:00
|
|
|
}
|
2023-10-22 23:28:20 +00:00
|
|
|
Ok(())
|
2023-10-17 03:26:32 +00:00
|
|
|
}
|
|
|
|
|
2024-03-01 01:36:06 +00:00
|
|
|
fn print_token(t: Token) {
|
2023-10-17 03:26:32 +00:00
|
|
|
println!(
|
2023-10-24 02:02:09 +00:00
|
|
|
"{:02}:{:02}: {:#19} │{}│",
|
2023-10-17 03:26:32 +00:00
|
|
|
t.line(),
|
|
|
|
t.col(),
|
|
|
|
t.ty(),
|
2023-10-22 23:28:20 +00:00
|
|
|
t.data(),
|
2023-10-17 03:26:32 +00:00
|
|
|
)
|
|
|
|
}
|