try rust parser
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
use tree_sitter::Parser;
|
||||
|
||||
pub fn parse_to_sexp(src: &str) -> Result<String, anyhow::Error> {
|
||||
let lang = tree_sitter_tcl::LANGUAGE;
|
||||
let mut parser = Parser::new();
|
||||
parser.set_language(&lang.into())?;
|
||||
let tree = parser
|
||||
.parse(src.as_bytes(), None)
|
||||
.ok_or_else(|| anyhow::anyhow!("failed to parse input"))?;
|
||||
Ok(tree.root_node().to_sexp())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_sample() {
|
||||
let src = r#"proc ProcName {arg1 arg2 {arg3 3}} {
|
||||
# Comment
|
||||
set var1 100
|
||||
}"#;
|
||||
let sexp = parse_to_sexp(src).expect("parse");
|
||||
assert!(sexp.contains("proc"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use std::io::{ self, BufRead };
|
||||
use serde::{ Deserialize, Serialize };
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
println!(
|
||||
"tcl_parser server starting (NDJSON stdin). Send JSON lines with {{'id':..., 'tcl': '...'}}"
|
||||
);
|
||||
let stdin = io::stdin();
|
||||
for line in stdin.lock().lines() {
|
||||
let line = line?;
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let req: Request = match serde_json::from_str(&line) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let resp = Response::error(None, format!("invalid request json: {}", e));
|
||||
println!("{}", serde_json::to_string(&resp)?);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let id = req.id.clone();
|
||||
match tcl_parser::parse_to_sexp(&req.tcl) {
|
||||
Ok(sexp) => {
|
||||
let resp = Response::ok(id, sexp);
|
||||
println!("{}", serde_json::to_string(&resp)?);
|
||||
}
|
||||
Err(e) => {
|
||||
let resp = Response::error(id, format!("parse error: {}", e));
|
||||
println!("{}", serde_json::to_string(&resp)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Request {
|
||||
id: Option<String>,
|
||||
tcl: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Response {
|
||||
id: Option<String>,
|
||||
ok: bool,
|
||||
result: Option<String>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
fn ok(id: Option<String>, result: String) -> Self {
|
||||
Self { id, ok: true, result: Some(result), error: None }
|
||||
}
|
||||
fn error(id: Option<String>, err: String) -> Self {
|
||||
Self { id, ok: false, result: None, error: Some(err) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user