在我的项目中,我想分析 PHP 文件的源代码并将其转换为 AST。 已经有一个用于此目的的 javascript 包,但它仅适用于节点。所以我尝试使用 Rust 库将 PHP 代码转换为 AST。然而,我对 Rust 没有任何经验,也没有取得任何进展:
文件 src-tauri/src/main.rs 内:
#[tauri::command]
fn php_to_ast(code: &str) -> String {
match parser::parse(code) {
Ok(ast) => {
format!("{:?}", ast)
}
}
}
invoke('php_to_ast', { code: value }).then((result) => {
this._ast = result;
console.log({ast: this._ast});
}).catch((error) => {
console.error({error});
});
error[E0004]: non-exhaustive patterns: `Err(_)` not covered
--> src/main.rs:8:11
|
8 | match parser::parse(code) {
| ^^^^^^^^^^^^^^^^^^^ pattern `Err(_)` not covered
|
note: `Result<Vec<php_parser_rs::parser::ast::Statement>, ParseErrorStack>` defined here
= note: the matched value is of type `Result<Vec<php_parser_rs::parser::ast::Statement>, ParseErrorStack>`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
11~ }
12+ Err(_) => todo!()
|
我知道我没有完全处理
parser::parse()
的返回值。作为比较,在
Rust 库示例中,调用如下所示:
fn main() -> Result<()> {
match parser::parse(CODE) {
Ok(ast) => {
println!("{:#?}", ast);
}
Err(err) => {
println!("{}", err.report(CODE, None, true, false)?);
println!("parsed so far: {:#?}", err.partial);
}
}
Ok(())
}
大概我还应该处理并返回错误(作为带有错误消息的字符串?)。
match parser::parse(code) {
Ok(ast) => format!("{:?}", ast);
Err(error) => /* Handle Error in Rust and return some indicator String */;
}
然后在您的打字稿代码中,您可以检查返回的错误字符串:
invoke("php_to_ast", { code: value })
.then((ast_or_error) => {
if (ast_or_error == "your_indicator") {
/* Handle error in typescript */
} else {
/* Use your ast */
}
})